Error when starting jax-rs server - java

I am getting the following error when trying to start my web service locally
SEVERE: The ResourceConfig instance does not contain any root resource classes.
com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.
at com.sun.jersey.server.impl.application.RootResourceUriRules.<init>(RootResourceUriRules.java:99)
at com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1359)
at com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:180)
at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:799)
at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:795)
at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:795)
at com.sun.jersey.api.container.ContainerFactory.createContainer(ContainerFactory.java:172)
at com.sun.jersey.api.container.ContainerFactory.createContainer(ContainerFactory.java:264)
at com.sun.jersey.api.container.ContainerFactory.createContainer(ContainerFactory.java:246)
at com.sun.jersey.api.container.httpserver.HttpServerFactory.create(HttpServerFactory.java:117)
at com.sun.jersey.api.container.httpserver.HttpServerFactory.create(HttpServerFactory.java:92)
at com.swiped.main.ServerStart.main(ServerStart.java:14)
My classes look as follows;
public class ExposedFunctions {
private static Logger logger = Logger.getLogger(ExposedFunctions.class);
private DBFactoryController controller = new DBFactoryController();
public ExposedFunctions(){
if(controller!= null){
controller.buildCache();
}
}
#GET
#Path("/add/{username}/{password}/{email}/{firstname}/{lastname}")
#Produces(MediaType.TEXT_PLAIN)
public String register(#PathParam("username") String username, #PathParam("password") String password, #PathParam("email") String email, #PathParam("firstname") String firstname, #PathParam("lastname") String lastname) {
if(StringUtilities.stringEmptyOrNull(username, password, email, firstname, lastname)){
logger.error("String was null or empty when registering");
}
RegistrationStatus status = controller.register(username, password, email, firstname, lastname);
return status.getValue();
}
}
My web xml is as follows;
<?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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>com.swiped.service</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.swiped.service</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
And I kick it all off with my main class which looks as follows;
#SuppressWarnings("restriction")
public static void main(String[] args){
try{
HttpServer server = HttpServerFactory.create(BASE_URI);
server.start();
System.out.println("Press Enter to stop the server. ");
System.in.read();
server.stop(0);
}catch(Exception e){
e.printStackTrace();
}
}
I have noticed that plenty of people have had a similar error however there is lots of varying advice given for individual circumstances making it hard for me to find a solution for this error. Does anyone see anything obviously wrong with my approach and if so please could you help me in resolving it?
Thanks for your time

Annotate ExposedFunctions with #Path, too.
#Path("/")
public class ExposedFunctions {
Edit: The class is the root resource while the methods are sub resources. You must have both.

Related

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
}
});

spring com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes

I've just started my first simple spring program. I'm trying to make a Rest API using Jersey framework with spring. Its a very basic simple program to fetch list of countries. But, however it throws the error. I've gone through other solutions, none of them worked.
Web.xml
<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>Spring MVC Application</display-name>
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</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>
</web-app>
Error which I get is
SEVERE: StandardWrapper.Throwable
com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.
at com.sun.jersey.server.impl.application.RootResourceUriRules.<init>(RootResourceUriRules.java:99)
at com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1359)
at com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:180)
at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:799)
at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:795)
at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
My program
package org.arpit.java2blog.jaxrs;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.arpit.java2blog.bean.Country;
#Path("/countries")
public class CountryRestService {
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<Country> getCountries() {
System.out.println("Getting countries");
List<Country> listOfCountries = new ArrayList<Country>();
listOfCountries = createCountryList();
return listOfCountries;
}
#GET
#Path("{id: \\d+}")
#Produces(MediaType.APPLICATION_JSON)
public Country getCountryById(#PathParam("id") int id) {
List<Country> listOfCountries = new ArrayList<Country>();
listOfCountries = createCountryList();
for (Country country : listOfCountries) {
if (country.getId() == id)
return country;
}
return null;
}
// Utiliy method to create country list.
public List<Country> createCountryList() {
Country indiaCountry = new Country(1, "India");
Country chinaCountry = new Country(4, "China");
Country nepalCountry = new Country(3, "Nepal");
Country bhutanCountry = new Country(2, "Bhutan");
List<Country> listOfCountries = new ArrayList<Country>();
listOfCountries.add(indiaCountry);
listOfCountries.add(chinaCountry);
listOfCountries.add(nepalCountry);
listOfCountries.add(bhutanCountry);
return listOfCountries;
}
}
URL
http://localhost:8080/HelloWeb/rest/countries
What is missing in this one?
You don't have your Jersey servlet (ServletContainer) configured in your web.xml to pick up any resource classes. So Jersey starts up with no resources registered.
With web.xml generally the way to go, is to set an init-param to tell Jersey to scan a certain package for classes annotated with #Path and #Provider. To do that, just add the following
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>the.package.you.want.to.scan</param-value>
</init-param>
...
</servlet>

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";

REST API is unable to work in JSON format

I am new to developing REST API with Java. I made a very simple one using the mkyong tutorials, where it only says "hello". I am using Apache Tomcat.
Now I am trying to develop a one where it will return the JSON objects. I am attempting the example here - http://www.mkyong.com/webservices/jax-rs/json-example-with-jersey-jackson/. Some of the code are changed (ex: package name).Below is my code.
Track.java
package com.tutorialspoint;
/**
*
* #author Yohan
*/
public class Track {
String title;
String singer;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSinger() {
return singer;
}
public void setSinger(String singer) {
this.singer = singer;
}
#Override
public String toString() {
return "Track [title=" + title + ", singer=" + singer + "]";
}
}
JsonService.java
package com.tutorialspoint;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
*
* #author Yohan
*/
#Path("/json/metallica")
public class JsonService {
#GET
#Path("/get")
#Produces(MediaType.APPLICATION_JSON)
public Track getTrackInJSON() {
Track track = new Track();
track.setTitle("Enter Sandman");
track.setSinger("Metallica");
return track;
}
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
public Response createTrackInJSON(Track track) {
String result = "Track saved : " + track;
return Response.status(201).entity(result).build();
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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>Restful Web Application</display-name>
<servlet>
<servlet-name>NewServlet</servlet-name>
<servlet-class>NewServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>Jersey RESTful 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.tutorialspoint</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>NewServlet</servlet-name>
<url-pattern>/NewServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Jersey RESTful Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
My application is not a marven project. So the added libraries are below.
I tested the application with the below URL.
http://localhost:8080/RESTFUL_API_SAMPLE/rest/json/metallica/get
All I got is the below page
Any idea about why I am not getting the expected result?
Currently you don't have any JSON/POJO support. The jersey-json jar and the POJOMappingFeature configuration in your web.xml is for Jersey 1.x, which won't work for Jersey 2.x. For all the jars you need for Jersey 2.x support, see this answer.

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

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 ! ! !

Categories