jaxrs - Unable to call the webservice : 404 Not Found Error - java

I have created a simple webservice but I am unable to call it. I get 404 Not found error.
package com.fms.mdw.rest;
#Path("/Search")
public class SearchWebService {
#POST
#Path("/searchData")
#Consumes(MediaType.APPLICATION_JSON)
#Produces("application/json")
public FMSResponseInfo getSearchData(SearchDTO searchDTO) {
System.out.println("Entered the getSearchData()");
FMSResponseInfo fmsResponseInfo = new FMSResponseInfo();
List<SearchDetailsDTO> searchDetailsDtoList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
SearchDetailsDTO searchDetailsDto = new SearchDetailsDTO();
searchDetailsDto.setBarcode("barcode" + i);
searchDetailsDto.setDocNo("docNo" + i);
searchDetailsDto.setDocType("docType" + i);
searchDetailsDtoList.add(searchDetailsDto);
}
fmsResponseInfo.setStatus("200");
fmsResponseInfo.setMessage("Success");
fmsResponseInfo.setData(searchDetailsDtoList);
System.out.println("Leaving the getSearchData()");
return fmsResponseInfo;
}
}
SearchDTO has two fields searchType, searchText both of type string.So the json payload will be {"searchType":"", "searchText":""}
I have registered the webservice in the following manner in web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>LatestFMS</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>LatestFMS Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.fms.mdw.rest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>LatestFMS Web Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
I am able to access the webpages, but I am unable to call the webservice. I am using RESTClient to send post request. The web server is apache tomcat 7 and jersey 2.16 .
The url I am hitting is http://localhost:8082/LatestFMS/rest/Search/searchData.
I am unable to resolve the issue, please help ! ! !

Related

How to call property file when project is loaded through web.xml in Java?

I have made a property file and loading my database connection from that file only. What I am doing is using Servlet context, I am getting the resource
and this code I have written in my login page (login.jsp) like this
<%ServletContext servletContext = getServletContext();
InputStream input = getServletContext().getResourceAsStream("/WEB-INF/db.properties");
if (input != null) {
InputStreamReader isr = new InputStreamReader(input);
BufferedReader reader = new BufferedReader(isr);
PrintWriter writer = response.getWriter();
String text;
while ((text = reader.readLine()) != null) {
/* System.out.println(text + "\n"); */
servletContext.setAttribute(text.split("=")[0], text.split("=")[1]);
}
}
%>
So it is taking the values from my property file whenever the user is logging in, but what I want is to load my property file through web.xml so whenever the projects load or server starts it loads the connection from that property file only once not whenever the user login it calls the property file.
So here is my Java connection class where I am assigning the values from property file:
ServletContext servletContext = getServletContext();
String driverDB = servletContext.getAttribute("driver").toString();
String conn_urlDB = servletContext.getAttribute("conn_url").toString();
String userNameDB = servletContext.getAttribute("userName").toString();
String passwordDB = servletContext.getAttribute("password").toString();
DBConnection.getDataBaseProperty(driverDB, conn_urlDB, userNameDB, passwordDB);
web.xml below
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>TouchPoint</display-name>
<welcome-file-list>
<welcome-file>Login.jsp</welcome-file>
</welcome-file-list>
<servlet>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.touchpoint.controller.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.touchpoint.controller.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/LogoutServlet</url-pattern>
</servlet-mapping>
</web-app>
ServletContextListener is tha answer for you,
You can check this blog post for a better understanding
https://www.journaldev.com/1945/servletcontextlistener-servlet-listener-example
put your config strings in the web.xml file then get notified on server startup through the servletContextListener
here's an extract from that blog post:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>ServletListenerExample</display-name>
<context-param>
<param-name>DBUSER</param-name>
<param-value>pankaj</param-value>
</context-param>
<context-param>
<param-name>DBPWD</param-name>
<param-value>password</param-value>
</context-param>
<context-param>
<param-name>DBURL</param-name>
<param-value>jdbc:mysql://localhost/mysql_db</param-value>
</context-param>
<listener>
<listener-class>com.journaldev.listener.AppContextListener</listener-class>
</listener>
You need to create a new class that will listen to the event of server startup:
public class AppContextListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext ctx = servletContextEvent.getServletContext();
String url = ctx.getInitParameter("DBURL");
String u = ctx.getInitParameter("DBUSER");
String p = ctx.getInitParameter("DBPWD");
}}

Writing to JSONobject through Restful Webservice

I am learning how to use Restful Webservice, i dont really know if my approach is good or totally wrong, so bear with me
I got a project structure, which look like this :
I want to by calling the right URL, save the string accordingly in Datum.Json
Here is my Java Class of the WebService :
package Rest;
#Path("/calendar")
public class CalendarTest {
public List<Date> dates;
#GET
#Path("/dates/get/")
#Produces(MediaType.APPLICATION_XML)
public List<Date> getUsers(){
return dates;
}
#PUT
#Path("/dates/put/{param1}+{param2}")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public void updateDate(#PathParam("param1") String city, #PathParam("param2") String date) throws IOException {
JSONObject obj = new JSONObject();
obj.put("City", city);
obj.put("Date", date);
try (FileWriter file = new FileWriter("/RestTest/Datum.json")) {
file.write(obj.toJSONString());
System.out.println("Successfully Copied JSON Object to File...");
System.out.println("\nJSON Object: " + obj);
}
}
}
I tested the localhost, it works fine (i can open the form.html with my localhost)
My web.xml file :
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Restful Web Application</display-name>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>
org.glassfish.jersey.servlet.ServletContainer
</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>Rest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<security-constraint>
</security-constraint>
</web-app>
But when i tried the URL http://localhost:8080/RestTest/rest/calendar/dates/put/Berlin+20-12-2019
It says the method not allowed.
Can anyone explain to me why ?
It's because when you are typing in a URL in your browser, it sends a HTTP GET request by default, so it throws an error because you do not have a GET request handler for that URL, you only have a handler for a PUT request.
You can't change the browser's default request type. What you have to do is send the request yourself using something like jQuery in your frontend / javascript.
How to send a PUT/DELETE request in jQuery?
You could use the ajax method:
$.ajax({
url: '/rest/calendar/dates/put/Berlin+20-12-2019',
type: 'PUT',
success: function(result) {
// Do something with the result
}
});

Ajax call is not hitting the rest service returning 404 error

I am new to the rest api, and trying to hit the service method using jquery ajax. The main problem is ,the service class is not getting called and I am getting the error 404 from the server.
This is my web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>AudienceManagement</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.inf.dashboardapp.api</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
</web-app>
This is my js file :
var myData=[];
$('#ajax').click(function(){
alert('ajax');
$.ajax({
type: "GET",
dataType: "json",
url: "http://localhost:8080/AudienceManagement/api/ref/check",
success: function(data){
alert(data);
myData=data;
},
error: function(data){
alert('error');
},
complete: function(data) {
alert('complete')
}
});
});
This is my service class.
#Path("ref")
public class DataAPI {
#Path("check")
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response fetchBoatingTypeList() {
System.out.println("Entered");
String returnValue = null;
Response response = null;
try {
JSONObject obj = new JSONObject();
obj.put("name", "Bhavana");
obj.put("num", new Integer(100));
obj.put("balance", new Double(1000.21));
obj.put("is_vip", new Boolean(true));
response = Response.status(Status.OK).entity(obj).build();
} catch (Exception e) {
//String returnString = "{\"message\":\""
//+ AppConfig.PROPERTIES.getProperty(e.getMessage()) + "\"}";
String returnString="ERRRRRRROR ";
response = Response.status(Status.SERVICE_UNAVAILABLE)
.entity(returnString).build();
}
return response;
}
}
This is the error that I am getting when I made an ajax call.
GET http://localhost:8080/AudienceManagement/api/ref/check 404 (Not Found)

Receiving payload request and displaying it on a webpage using spring

First of all I'm new to Spring and tried my best to get this working. So this is my question.
I have a spring MVC project which is supposed to receive a request payload (JSON request) and display the payload body on a webpage. Please see my project content and the controller class below
#Controller
public class CallbackPayloadController {
public CallbackPayloadController() {
System.out.println("In controller class!!!!");
}
#RequestMapping(value = "/requestreceiver", consumes = "application/json", method = RequestMethod.POST)
public void receivePayload(#RequestBody String payload) {
System.out.println("In the controller method....");
System.out.println("Payload is : " + payload);
}
}
Now if I do a POST to http://localhost:8080/PayloadReceiver/requestreceiver/ using POSTMAN it says HTTP STATUS 404. My Json content that I am posting is
{
"key":"123"
}
My web.xml is as follows
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>PayloadReceiver</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>requestreceiver</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>requestreceiver</servlet-name>
<url-pattern>/requestreceiver.jsp</url-pattern>
<url-pattern>/requestreceiver.html</url-pattern>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
Second question is if I successfully receive the payload, how do I display the payload content on a new webpage?
Try to add the return statement to your method like this:
#RequestMapping(value = "/requestreceiver",consumes="...",method = RequestMethod.POST)
public String receivePayload(...)
...
return "requestreceiver";

Setting Jackson 2 with Jersey and Tomcat

I have no maven project with Jersey and Tomcat. For my Json object for now i use lib:--> org.json.JSONObject. Now i want to integrate my project with Jackson but how?..
My web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>RESTful</display-name>
<servlet>
<servlet-name>restJerseyServlet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.fasterxml.jackson.jaxrs.json;com.rest.proof</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>restJerseyServlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
Example how i create a JsonObject:
JSONObject json = new JSONObject();
List<JSONObject> list = new ArrayList<JSONObject>();
Element elementsByTag = doc.getElementsByTag("table").get(1);
Elements rows = elementsByTag.getElementsByTag("tr");
for (Element row : rows) {
String ex = row.getElementsByTag("td").get(1).text();
String exx = row.getElementsByTag("td").get(2).text();
String exxx = row.getElementsByTag("td").get(3).text();
JSONObject jsonObject = new JSONObject();
jsonObject.put("Feat1", ex);
jsonObject.put("Feat2", exx);
jsonObject.put("Feat3", exxx);
list.add(jsonObject);
}
json.accumulate("Response", 200);
json.accumulate("List", list);
String result = "" + json;
return json;
i have this error when i try to consume a API:
com.fasterxml.jackson.databind.type.TypeFactory and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)
I fixed with this; in the web.xml i put:
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.fasterxml.jackson.jaxrs;com.rest.proof</param-value>
</init-param>
and use a ObjectNode not a JsonObject

Categories