I have the following class :
package test
import org.apache.log4j.Logger;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path("/test")
public class test {
private static Logger logger = Logger.getLogger(test.class);
#GET
public Response getMsg() {
logger.info("Inside getMsg()");
String output = "hello world";
return Response.status(200).entity(output).build();
}
#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();
}
}
Track is just an object of another class
I have the following dependencies in my POM :
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.17.1</version>
</dependency>
and this is my servlet mapping
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
Everytime I use the
BASEURL/rest/test -> Correct response ( Hello world)
BASEURL/rest/test/get -> Type:GET
response: <html><head><title>Apache Tomcat/7.0.42 - Error report</title></head><body><h1>HTTP Status 500 - Internal Server Error</h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u>Internal Server Error</u></p><p><b>description</b> <u>The server encountered an internal error that prevented it from fulfilling this request.</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/7.0.42</h3></body></html>
also in the tomcat execution I can see the error:
Jan 27, 2014 1:41:28 PM
com.sun.jersey.spi.container.ContainerResponse logException
SEVERE: Mapped exception to response: 500 (Internal Server Error)
javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message body writer for Java class com.myProj.jsp.rest.Track, and Java type class com.gsipartners.apimgmtut
at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:285)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1437)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:662)
Caused by: com.sun.jersey.api.MessageException: A message body writer for Java class com.myProj.jsp.rest.Track, and Java type class com.myProj.jsp.rest.Track, and MIM
... 24 more
I have no idea why this is not working
Looks like it's having a problem writing the Track java object back in the response.
You don't appear to have Moxy in your POM. Do you have some form of JSON Marshaller in your classpath?
Have a look at this: https://jersey.java.net/documentation/latest/media.html#json.moxy
Related
I am using Jersey version 1.12 and i am facing the error that is
A message body writer for Java class java.lang.Boolean, and Java type boolean, and MIME media type application/octet-stream was not found
at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:285)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1451)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1363)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1353)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:414)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:708)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
my code is
#POST
#Path("/save/{Name}/{data}")
#Consumes("application/x-www-form-urlencoded")
public String saveDataMap(#QueryParam("number") String number,
#PathParam("data") String data,
#PathParam("Name") String appName
MultivaluedMap<String, String> formParam) throws Exception{
boolean response =false'
try{
// some business logic
response =true
}
return response;
}
After Googling this error i found that this is due to you are not specifying the content type of the data you are sending - so Jersey is not able to locate the right MessageBodyWritter to serialize
after this i added produces anotation to the method with the MediaType.TEXT_PLAIN but it doesn't work ,but when i changed return type of method to String it started working.
I simply wants to know whats problem with boolean ,why it is not working with boolean ? and how to solve this problem without changing boolean to String ?
any help will be greatly appreciated.
I usually code these methods like this:
#POST
#Path("/save/{Name}/{data}")
#Consumes("application/x-www-form-urlencoded")
#Produces(MediaType.TEXT_PLAIN)
public Response saveDataMap(#QueryParam("number") String number,
#PathParam("data") String data,
#PathParam("Name") String appName
MultivaluedMap<String, String> formParam) throws Exception{
boolean response =false
try{
// some business logic
response =true
}
return Response.ok().entity(String.valueOf(response)).build();
}
The only changes is that it returns a jersey HTTP response building it from a string from a boolean.
I hope it helps.
Regards,
Cris.
How to use asynchronous callbacks of jersey 2 in tomcat server.
I found some examples in Jersey manual : https://jersey.java.net/documentation/latest/user-guide.html#d0e8496.
But the issue occurs when I'm tring to test following code with this: https://jersey.java.net/documentation/latest/user-guide.html#d0e8615 code as mentioned on Jersey 2 Manual.
-------------------------------------------------------------------------------------------------------------------------------
As, manual version has been changed, I'm posting the codes over here:
This is my Service:
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.CompletionCallback;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path("/resource")
public class AsyncResource {
private static int numberOfSuccessResponses = 0;
private static int numberOfFailures = 0;
private static Throwable lastException = null;
#GET
public void asyncGetWithTimeout(#Suspended final AsyncResponse asyncResponse) {
System.out.println("AsyncResource.asyncGetWithTimeout()");
asyncResponse.register(new CompletionCallback() {
#Override
public void onComplete(Throwable throwable) {
if (throwable == null) {
// no throwable - the processing ended successfully
// (response already written to the client)
numberOfSuccessResponses++;
} else {
numberOfFailures++;
lastException = throwable;
}
}
});
new Thread(new Runnable() {
#Override
public void run() {
String result = veryExpensiveOperation();
asyncResponse.resume(result);
}
private String veryExpensiveOperation() {
// ... very expensive operation
return "Hi";
}
}).start();
}
}
This is client:
ClientConfig clientConfig = new ClientConfig();
Client client = ClientBuilder.newClient(clientConfig);
WebTarget webTarget = client.target("http://localhost:8080/Jersey2.5Service/rest");
WebTarget target = webTarget.path("resource");
final AsyncInvoker asyncInvoker = target
.request().async();
final Future<Response> responseFuture = asyncInvoker.get();
System.out.println("Request is being processed asynchronously.");
final Response response = responseFuture.get();
// get() waits for the response to be ready
System.out.println("Response received." +response.readEntity(String.class));
web.xml
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>
org.glassfish.jersey.servlet.ServletContainer
</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>main.java</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
These are the jars I'm using:
asm-all-repackaged-2.2.0-b21.jar
cglib-2.2.0-b21.jar
guava-14.0.1.jar
hk2-api-2.2.0-b21.jar
hk2-locator-2.2.0-b21.jar
hk2-utils-2.2.0-b21.jar
javax.annotation-api-1.2.jar
javax.inject-2.2.0-b21.jar
javax.servlet-api-3.0.1.jar
javax.ws.rs-api-2.0.jar
jaxb-api-2.2.7.jar
jersey-client.jar
jersey-common.jar
jersey-container-servlet-core.jar
jersey-container-servlet.jar
jersey-server.jar
org.osgi.core-4.2.0.jar
osgi-resource-locator-1.0.1.jar
persistence-api-1.0.jar
servlet-api-3.0.jar
validation-api-1.1.0.Final.jar
These errors are coming:
Jan 31, 2014 4:06:53 PM org.glassfish.jersey.servlet.internal.ResponseWriter suspend
WARNING: Attempt to put servlet request into asynchronous mode has failed. Please check your servlet configuration - all Servlet instances and Servlet filters involved in the request processing must explicitly declare support for asynchronous request processing.
java.lang.IllegalStateException: Not supported.
at org.apache.catalina.connector.Request.startAsync(Request.java:1676)
at org.apache.catalina.connector.RequestFacade.startAsync(RequestFacade.java:1031)
at org.glassfish.jersey.servlet.async.AsyncContextDelegateProviderImpl$ExtensionImpl.suspend(AsyncContextDelegateProviderImpl.java:87)
at org.glassfish.jersey.servlet.internal.ResponseWriter.suspend(ResponseWriter.java:120)
at org.glassfish.jersey.server.ServerRuntime$AsyncResponder.suspend(ServerRuntime.java:758)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:330)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:106)
at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:259)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:318)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:236)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1010)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:373)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:382)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:345)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:220)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Jan 31, 2014 4:06:53 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [HelloServlet] in context with path [/Jersey2.5Service] threw exception [javax.ws.rs.ProcessingException: Attempt to suspend a connection of an asynchronous request failed in the underlying container.] with root cause
javax.ws.rs.ProcessingException: Attempt to suspend a connection of an asynchronous request failed in the underlying container.
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:331)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:106)
at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:259)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:318)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:236)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1010)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:373)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:382)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:345)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:220)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
For me the solution was to add support for Async in a Servlet Filter. The error message gave me a hint:
Attempt to put servlet request into asynchronous mode has failed. Please check your servlet configuration - all Servlet instances and Servlet filters involved in the request processing must explicitly declare support for asynchronous request processing
I am using Spring for Dependency Injection and using the default Jersey servlet. For Spring I use a Delegating Filter Proxy. I needed to declare for the Filter asycn support true.
So for the servlet:
<servlet>
<servlet-name>myserlet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
AND add async support true for the the Spring filter as well.
<filter>
<description>Spring filter</description>
<display-name>spring-filter</display-name>
<filter-name>springFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<async-supported>true</async-supported>
</filter>
I hope this might help for you and others.
I know this question is very old, but for people who are facing this issue Please update Tomcat Server to the Latest Version 8.** . Tomcat starting from version 8 has support for Async Processing.
For Async callback you can use Guava lib. For example:
#GET
#Produces(MediaType.APPLICATION_JSON)
#ManagedAsync
public void getBooks(#Suspended final AsyncResponse response){
ListenableFuture<Collection<Book>> bookFuture = dao.getBooksAsync();
Futures.addCallback(bookFuture, new FutureCallback<Collection<Book>>() {
public void onSuccess(Collection<Book> books){
response.resume(books);
}
public void onFailure(Throwable thrown){
response.resume(thrown);
}
});
}
And in my book DAO I have:
BookDao(){
books = new HashMap<String,Book>();
Book b1 = new Book();
service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
}
Collection<Book> getBooks(){
return(books.values());
}
ListenableFuture<Collection<Book>> getBooksAsync(){
ListenableFuture<Collection<Book>> future =
service.submit(new Callable<Collection<Book>>() {
public Collection<Book> call() throws Exception{
return getBooks();
}
});
return(future);
}
This might be too late, but upgrading to tomcat 9 will resolve this issue, without you modifying anything in the server
I have the following dependencies for jersey in my web application
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.8</version>
</dependency>
when I use #Consumes(MediaType.APPLICATION_JSON) or #Produces(MediaType.APPLICATION_JSON) i get a server error . Similarly if I try and use XML . Is it because of the libraries I am using ?
my java class
import org.apache.log4j.Logger;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path("/test")
public class test {
private static Logger logger = Logger.getLogger(test.class);
#GET
#Produces(MediaType.TEXT_PLAIN) // works perfectly
public Response getMsg()
{
logger.info("Inside getMsg()");
String output = "hello world";
return Response.status(200).entity(output).build();
}
/* #GET // I get a HTTP 500 , server error
#Path("/get")
#Produces(MediaType.APPLICATION_JSON)
public Track getTrackInJSON() {
Track track = new Track();
track.setTitle("Enter Sandman");
track.setSinger("Metallica");
return track;
}
*/
#GET
#Path("/get")
#Produces(MediaType.APPLICATION_JSON)
public Response getTrackInJSON() {
Track track = new Track();
track.setTitle("Enter Sandman");
track.setSinger("Metallica");
//String test = " hello world";
return Response.status(201).entity(track).build();
}
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
// #Produces(Me)
public Response createTrackInJSON(Track track) {
String result = "Track saved : " + track;
return Response.status(201).entity(result).build();
}
#POST
#Path("/getValue")
#Produces(MediaType.APPLICATION_XML)
public void createXML()
{
String result = " get the track";
// return result.createXML();
// check this line
}
}
when I use a rest client to access the #GET resource I get this error :
<u>Internal Server Error</u></p><p><b>description</b> <u>The server encountered an internal error that prevented it from fulfilling this request.</u>
when I use the rest client to access the #POST resource I get this error:
<u>Internal Server Error</u></p><p><b>description</b> <u>The server encountered an internal error that prevented it from fulfilling this request.</u>
this is what I get from the Tomcat error logs
Jan 29, 2014 11:00:21 AM com.sun.jersey.spi.container.ContainerResponse logException
SEVERE: Mapped exception to response: 500 (Internal Server Error)
javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message body writer for Java class com.myProj.jsp.rest.Track, and Java type class com.gsipartners.apimgmtut
at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:285)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1437)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:662)
Caused by: com.sun.jersey.api.MessageException: A message body writer for Java class com.myProj.jsp.rest.Track, and Java type class com.myProj.jsp.rest.Track, and MIM
... 24 more
the Track class
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 + "]";
}
}
You should annotate your Track class with JAXB annotations and Jersey will use its MessageBodyWriter to serialize/marshall the returned entity (track) into the response outputstream. Or you'll need to provide your own implementation of MessageBodyWriter for the Track type to write the serialized form in the response outputstream. Otherwise, Jersey doesn't know how to do it.
I'm trying to implement a REST WS. The following code works ok:
#Path("/MyRest")
#WebService
public class MyService {
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/{id}")
public Response test(#PathParam("id") String id) {
String str = "{\"status\":\"ok\",\"id\":\"" + id + "\"}";
return Response.status(200).entity(str).build();
}
}
web.xml:
<?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>WSRest</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>test</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>
Now i'm trying to do it with an Interface. The interface would be like follows, I guess:
#Path("/MyRest")
#WebService
public interface IService {
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/{id}")
public Response test(#PathParam("id") String id);
}
And now the WS implementation would be like this, right?:
public class MyService implements IService{
#Override
public Response test(#PathParam("id") String id) {
String str = "{\"status\":\"ok\",\"id\":\"" + id + "\"}";
return Response.status(200).entity(str).build();
}
}
I'm getting "HTTP Status 500 - Servlet.init() for servlet Jersey REST Service threw exception" when I try to "run" it again :/
Any ideas? Thanks in advance.
Full exception:
type Exception report
message Servlet.init() for servlet Jersey REST Service threw exception
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet.init() for servlet Jersey REST Service threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2430)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2419)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
java.lang.Thread.run(Thread.java:722)
root cause
com.sun.jersey.spi.inject.Errors$ErrorMessagesException
com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136)
com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:795)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:790)
com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:491)
com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:321)
com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:207)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:376)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:559)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2430)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2419)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
java.lang.Thread.run(Thread.java:722)
An example of a web method using an interface:
Web service implementation:
#Path("/WS")
#WebService
public class WebService implements IWebService {
#Override
#POST
#Consumes("application/json")
#Produces("application/json")
#Path("/Login")
public Response Login(JSONObject data) {
//stuff here
}
}
Interface:
public interface IWebService {
#POST
#Consumes("application/json")
#Produces("application/json")
#Path("/Login")
public Response Login(JSONObject data);
}
First time I'm trying a WebService using jersey. The below code I got from some blog.
I am getting following 500 error when I'm trying Java Web service using jersey client
javax.servlet.ServletException: Servlet.init() for servlet Jersey Root REST Service threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1008)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
root cause
java.lang.NoClassDefFoundError: org/objectweb/asm/ClassVisitor
com.sun.jersey.api.core.ScanningResourceConfig.init(ScanningResourceConfig.java:79)
com.sun.jersey.api.core.servlet.WebAppResourceConfig.init(WebAppResourceConfig.java:102)
com.sun.jersey.api.core.servlet.WebAppResourceConfig.<init>(WebAppResourceConfig.java:89)
com.sun.jersey.api.core.servlet.WebAppResourceConfig.<init>(WebAppResourceConfig.java:74)
com.sun.jersey.spi.container.servlet.WebComponent.getWebAppResourceConfig(WebComponent.java:672)
com.sun.jersey.spi.container.servlet.ServletContainer.getDefaultResourceConfig(ServletContainer.java:415)
com.sun.jersey.spi.container.servlet.ServletContainer.getDefaultResourceConfig(ServletContainer.java:582)
com.sun.jersey.spi.container.servlet.WebServletConfig.getDefaultResourceConfig(WebServletConfig.java:87)
com.sun.jersey.spi.container.servlet.WebComponent.createResourceConfig(WebComponent.java:703)
com.sun.jersey.spi.container.servlet.WebComponent.createResourceConfig(WebComponent.java:678)
com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:203)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:374)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:557)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1008)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)'
Below 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" 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>RestFulWeb</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Jersey Root REST Service</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 Root REST Service</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>'
Here i tried adding the package also that didn't help:
Added only one jar file jersey-bundle-1.14.jar. The following is my Jersey server
package com.rest.server;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.rest.data.Hello;
// POJO, no interface no extends
// The class registers its methods for the HTTP GET request using the #GET annotation.
// Using the #Produces annotation, it defines that it can deliver several MIME types,
// text, XML and HTML.
// The browser requests per default the HTML MIME type.
//Sets the path to base URL + /hello
#Path("/hello")
public class HelloWorldRest {
#GET
#Path("/{param}/")
public String getMsg(#PathParam("param") String msg) {
String output = "Jersey say : " + msg;
return output;
}
#GET
#Path("/world")
public String getFixedMsg(String msg) {
String output = "Jersey say : fixed path" + msg;
return output;
}
// This method is called if TEXT_PLAIN is request
#GET
//#Path("helloworld")
#Produces(MediaType.TEXT_PLAIN)
public String sayPlainTextHello() {
System.out.println("sayPlain");
return "Hello Jersey";
}
// This method is called if XML is request
#GET
//#Path("helloworld")
#Produces(MediaType.TEXT_XML)
public String sayXMLHello() {
System.out.println("sayXML");
return "" + " Hello Jersey" + "";
}
// This method is called if HTML is request
#GET
//#Path("helloworld")
#Produces(MediaType.TEXT_HTML)
public String sayHtmlHello() {
System.out.println("sayHTML");
return "<html> " + "<title>" + "Hello Jersey" + "</title>"
+ "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
}
// This method is called if JSON is request
#GET
//#Path("helloworld")
#Produces(MediaType.APPLICATION_JSON)
public Hello sayJsonHello() {
return new Hello("Hello", "Jersey");
}
#POST
#Produces(MediaType.APPLICATION_JSON)
public Hello createHello(Hello hello)
{
System.out.println("post");
return hello;
}
}'
currently I'm trying only with GET hitting the following url http://localhost:8080/RestFulWeb/hello, I am getting the 505 error.
DO i missed any jar files , but i didn't get any compile time error.
This is caused by the missing of asm.jar,
Add this dependency
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.3.1</version>
</dependency>
While writing a webservice I was getting following error:
INFO: Scanning for root resource and provider classes in the packages:
com.webservice.services
Exception in thread "main" java.lang.NoClassDefFoundError: org/objectweb/asm/ClassVisitor
at com.sun.jersey.api.core.ScanningResourceConfig.init(ScanningResourceConfig.java:79)
at com.sun.jersey.api.core.PackagesResourceConfig.init(PackagesResourceConfig.java:104)
at com.sun.jersey.api.core.PackagesResourceConfig.<init>(PackagesResourceConfig.java:78)
at com.webservice.StartWebService.startAttrService(StartWebService.java:32)
at com.webservice.StartWebService.main(StartWebService.java:20)
Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.ClassVisitor
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 5 more
I included asm.jar in my java project and error gone.
I was following steps from restful-web-services-first-application-mock-service-using-pure-java