Unable to send Response from Rest method - java

Here is the rest ws POST method code:
#POST
#Path("/json/saveuser")
#Consumes("application/json")
public ResponseBuilder saveUserJSON(User user) {
if (save(user)) {
return Response.status(HttpStatus.SC_OK);
}
return Response.status(HttpStatus.SC_BAD_REQUEST);
}
User is saved properly in DB.
But the line Response.status(HttpStatus.SC_OK); and Response.status(HttpStatus.SC_BAD_REQUEST);, is throwing below error:
Mar 06, 2015 1:38:49 PM com.sun.jersey.spi.container.ContainerResponse traceException
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.sun.jersey.core.spi.factory.ResponseBuilderImpl, and Java type class javax.ws.rs.core.Response$ResponseBuilder, and MIME media type application/octet-stream was not found
at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:278)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1326)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1239)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1229)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:420)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:497)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:684)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: com.sun.jersey.api.MessageException: A message body writer for Java class com.sun.jersey.core.spi.factory.ResponseBuilderImpl, and Java type class javax.ws.rs.core.Response$ResponseBuilder, and MIME media type application/octet-stream was not found
... 28 more
Did googling. And according to the posts in SO and other sites, added the jars as listed below (Some additional jars are also added for other dependency):
antlr-2.7.7.jar
com.sun.jersey.jersey-core-1.4.0.jar
com.sun.jersey.jersey-server-1.4.0.jar
dom4j-1.6.1.jar
gcm.server.jar
genson-0.98.jar
hibernate-commons-annotations-4.0.5.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
http-core-4.1.jar
jackson-all-1.9.0.jar
jackson-annotations-2.2.2.jar
jackson-core-2.2.2.jar
jandex-1.1.0.Final.jar
javassist-3.18.1-GA.jar
jboss-logging-3.1.3.GA.jar
jboss-logging-3.1.4.GA.jar
jboss-logging-annotations-1.2.0.Beta1.jar
jboss-transaction-api_1.2_spec-1.0.0.Final.jar
jersey-bundle-1.8.jar
jersey-container-servlet-core-2.16.jar
jersey-core-1.15.jar
jersey-json.jar
json_simple-1.1.jar
lucene-core-4.10.4.jar
mysql-connector-java-5.1.31.jar
slf4j-api-1.6.1.jar
xml-apis-1.3.03.jar
Not sure what am I missing? Any suggestion?

You have to return a Response instead of a ResponseBuilder:
#POST
#Path("/json/saveuser")
#Consumes("application/json")
public Response saveUserJSON(User user) {
if (save(user)) {
return Response.status(HttpStatus.SC_OK).build();
}
return Response.status(HttpStatus.SC_BAD_REQUEST).build();
}

Your stacktrace obviously points, that Jersey doesn't know, how to response with ResponseBuilder.
Return Response instead: change resource method signature and return result of build method, called upon builder.

Related

HTTP Status 500 - Servlet.init() for servlet Jersey Web Application threw exception

index.html
<html>
<body>
<h2>Jersey RESTful Web Application!</h2>
<p>Jersey resource
<p>Visit the Project Jersey website
for more information on Jersey!
</body>
</html>
MyResource.java
#Path("/myresource")
public class MyResource {
/** Method processing HTTP GET requests, producing "text/plain" MIME media
* type.
* #return String that will be send back as a response of type "text/plain".
*/
#GET
#Produces("text/plain")
public String getIt() {
return "Hi there!";
}
}
Error is Comming
HTTP Status 500 - Servlet.init() for servlet Jersey Web Application threw exception
--------------------------------------------------------------------------------
type Exception report
message Servlet.init() for servlet Jersey Web Application 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 Web Application threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
root cause
java.lang.NoSuchMethodError: com.sun.jersey.core.reflection.ReflectionHelper.getContextClassLoaderPA()Ljava/security/PrivilegedAction;
com.sun.jersey.spi.scanning.AnnotationScannerListener.<init>(AnnotationScannerListener.java:94)
com.sun.jersey.spi.scanning.PathProviderScannerListener.<init>(PathProviderScannerListener.java:59)
com.sun.jersey.api.core.ScanningResourceConfig.init(ScanningResourceConfig.java:79)
com.sun.jersey.api.core.PackagesResourceConfig.init(PackagesResourceConfig.java:104)
com.sun.jersey.api.core.PackagesResourceConfig.<init>(PackagesResourceConfig.java:78)
com.sun.jersey.api.core.PackagesResourceConfig.<init>(PackagesResourceConfig.java:89)
com.sun.jersey.spi.container.servlet.WebComponent.createResourceConfig(WebComponent.java:696)
com.sun.jersey.spi.container.servlet.WebComponent.createResourceConfig(WebComponent.java:674)
com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:205)
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:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.67 logs.
you would have use correct version if you want proper output latest version number is 1.19.1 use this try onee
May be problem with servelet api dependcy :
use this in your maven pom for exemple:
<!-- servlet api 3 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
Its seems a java version issue. compile the code with supporting jar(java version) only

Spring Boot Actuator - "/shutdown" Fails With 500 Error

Background Information
I have a Spring Boot web application using Actuator for the production utilities.
The application works fine, and the management port works great. I can browse statistics, check health etc. I also enabled the remote shut-down endpoint, and it properly shows up in the localhost:{mgmt_port}/actuator list of endpoints.
My Problem
When I go to localhost:{mgmt_port}/shutdown though, I see:
<Map>
<timestamp>1453905900007</timestamp>
<status>500</status>
<error>Internal Server Error</error>
<exception>org.springframework.web.HttpRequestMethodNotSupportedException</exception>
<message>Request method 'GET' not supported</message>
<path>/shutdown</path>
</Map>
Useful Information
The whole application still seems to be running after hitting the shut-down link. I can still pull data from my custom application endpoints.
The management URL provided by Spring actuator also seems to still be running fine after hitting shut down.
Console Output Before Issue
10:01:42.496 [main] INFO o.s.b.c.e.t.TomcatEmbeddedServletContainer -
Tomcat started on port(s): 8002 (http) 10:01:42.499 [main] INFO
com.xyz.api.Main - Started Main in 5.956 seconds (JVM
running for 6.381)
Console Output After Issue
10:03:29.090 [http-nio-8003-exec-1] INFO
o.a.c.c.C.[Tomcat-1].[localhost].[/] - Initializing Spring
FrameworkServlet 'dispatcherServlet' 10:03:29.090
[http-nio-8003-exec-1] INFO o.s.web.servlet.DispatcherServlet -
FrameworkServlet 'dispatcherServlet': initialization started
10:03:29.126 [http-nio-8003-exec-1] INFO
o.s.web.servlet.DispatcherServlet - FrameworkServlet
'dispatcherServlet': initialization completed in 36 ms 10:03:29.151
[http-nio-8003-exec-1] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] -
Servlet.service() for servlet [dispatcherServlet] in context with path
[] threw exception [Request method 'GET' not supported] with root
cause org.springframework.web.HttpRequestMethodNotSupportedException:
Request method 'GET' not supported
at org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping.handleNoMatch(RequestMappingInfoHandlerMapping.java:204)
~[spring-webmvc-4.2.4.RELEASE.jar!/:4.2.4.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.lookupHandlerMethod(AbstractHandlerMethodMapping.java:382)
~[spring-webmvc-4.2.4.RELEASE.jar!/:4.2.4.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:322)
~[spring-webmvc-4.2.4.RELEASE.jar!/:4.2.4.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:60)
~[spring-webmvc-4.2.4.RELEASE.jar!/:4.2.4.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerMapping.getHandler(AbstractHandlerMapping.java:351)
~[spring-webmvc-4.2.4.RELEASE.jar!/:4.2.4.RELEASE]
at org.springframework.boot.actuate.autoconfigure.EndpointWebMvcChildContextConfiguration$CompositeHandlerMapping.getHandler(EndpointWebMvcChildContextConfiguration.java:212)
~[spring-boot-actuator-1.3.2.RELEASE.jar!/:1.3.2.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.getHandler(DispatcherServlet.java:1120)
~[spring-webmvc-4.2.4.RELEASE.jar!/:4.2.4.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:932)
~[spring-webmvc-4.2.4.RELEASE.jar!/:4.2.4.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
~[spring-webmvc-4.2.4.RELEASE.jar!/:4.2.4.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)
~[spring-webmvc-4.2.4.RELEASE.jar!/:4.2.4.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860)
~[spring-webmvc-4.2.4.RELEASE.jar!/:4.2.4.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
~[tomcat-embed-core-8.0.30.jar!/:8.0.30]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
~[spring-webmvc-4.2.4.RELEASE.jar!/:4.2.4.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
~[tomcat-embed-core-8.0.30.jar!/:8.0.30]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
~[tomcat-embed-core-8.0.30.jar!/:8.0.30]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
~[tomcat-embed-core-8.0.30.jar!/:8.0.30]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
~[tomcat-embed-core-8.0.30.jar!/:8.0.30]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
[tomcat-embed-core-8.0.30.jar!/:8.0.30]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
[tomcat-embed-core-8.0.30.jar!/:8.0.30]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
[tomcat-embed-core-8.0.30.jar!/:8.0.30]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
[tomcat-embed-core-8.0.30.jar!/:8.0.30]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
[tomcat-embed-core-8.0.30.jar!/:8.0.30]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
[tomcat-embed-core-8.0.30.jar!/:8.0.30]
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
[tomcat-embed-core-8.0.30.jar!/:8.0.30]
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
[tomcat-embed-core-8.0.30.jar!/:8.0.30]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
[tomcat-embed-core-8.0.30.jar!/:8.0.30]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
[tomcat-embed-core-8.0.30.jar!/:8.0.30]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_51]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_51]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
[tomcat-embed-core-8.0.30.jar!/:8.0.30]
at java.lang.Thread.run(Unknown Source) [na:1.8.0_51]
Answering my own question to help others in the future. I'm a chump... The /actuator URL lists all available commands, and all of them work based on a GET request.
The /shutdown URL actually requires a HTTP POST to be sent to it in order to activate it though. I didn't see this noted anywhere in the docs.
Sample CURL Command:
> curl -X POST http://hostname:8003/shutdown
Output Of Shutdown Command:
<SingletonMap><message>Shutting down, bye...</message></SingletonMap>

SQLNestedException: Cannot create PoolableConnectionFactory (Access denied for user '<<USERNAME>>'#'SERVERIP' (using password: YES))

I'm having an OpenShift site which is trying to connect to an external MySQL server. Below is the code I have so far.
public class BaseDAO {
static final String DB_DRIVER = "com.mysql.jdbc.Driver";
DataSource datasource;
public BaseDAO() {
System.out.println("+++++ " +Calendar.getInstance().getTime());
try{
InitialContext ic = new InitialContext();
Context initialContext = (Context) ic.lookup("java:comp/env");
datasource = (DataSource) initialContext.lookup("jdbc/MySQLDS");
Class.forName(DB_DRIVER).newInstance();
} catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e.getCause());
}
}
}
All my DAO classes extend the BaseDAO so I won't have to type all of this 5-6 times.
After some configuration, this does work on a local MySQL server. I have created a small application that either sends me to the index.jsp when the array gathered from the database is not null or not empty, and sends me to the about.jsp if it either is empty or null.
Now in both the local and the external database I have create a table with the same name, column 'day' and inserted 1 value. When I run this locally it sends me to the index page, but when I run this via my OpenShift webpage it sends me to the about page.
This is the error found in the SSH/app-root/logs/jbossews.log (username and serverip commented out)
:
NOTE: THE SERVERIP AND LOGINCREDENTIALS ARE PROVIDED BY THE DATASOURCE OF OPENSHIFT
The path to the DAO is: OpeningsTijdenServlet --> (static)ServiceProvider --> OTService --> OpeningsTijdenDAO (extends BaseDAO)
INFO: Server startup in 10894 ms
+++++ Mon Oct 12 16:07:51 EDT 2015
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Access denied for user '<<USERNAME>>'#'SERVERIP' (using password: YES))
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:1551)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1390)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1046)
at main.java.database.OpeningsTijdenDAO.selectTijden(OpeningsTijdenDAO.java:16)
at main.java.database.OTService.getTijden(OTService.java:13)
at main.java.servlets.GetTijdenServlet.doPost(GetTijdenServlet.java:17)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:683)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1042)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.sql.SQLException: Access denied for user '<<USERNAME>>'#'SERVERNAME' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1078)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4187)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4119)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:927)
Something wrong with your credential. try to change credential or server configuration.
Any of the hosting server you have to select "localhost"/"127.0.0.1" as your DB Host.

Making Servlet 2.5 code Servlet 3.0 compatible and vice versa

I have a class that implements javax.servlet.Filter and inside that filter, I'm instantiating an instance of InterceptHttpRequestFilter and InterceptHttpResponseFilter (which are used to modify the incoming and outgoing request and response)
Example:
public class InterceptHttpRequestFilter implements HttpServletRequest {
private HttpServletRequest httpReq;
final StringBuffer sb = new StringBuffer();
public InterceptHttpRequestFilter(ServletRequest request) {
this.httpReq = (HttpServletRequest) request;
try {
StringWriter sw = new StringWriter();
IOUtils.copy(request.getInputStream(), sw);
sb.append(sw.getBuffer().toString());
} catch (IOException e) {
e.printStackTrace();
}
}
....
When deploying this project on Tomcat6 using Servlet 2.5, everything works as it should.
Deploy it on Tomcat 7 and I get an AbstractMethodError:
SEVERE: Servlet.service() for servlet [_______] in context with path [/__________-1.0.0] threw exception [Filter execution threw an exception] with root cause
java.lang.AbstractMethodError
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:225)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at com.mycee.project.filter.MyFilter.doFilter(MyFilter.java:182)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
The obvious solution is to implement all the missing methods required by Servlet Version 3's HttpRequest / Response interfaces.
The maven dependency on mvnrepository is still in alpha:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
So my question is, does middle ground exist that will allow me to run this project on both Tomcat6 (Servlet 2.5) and Tomcat7 (Servlet 3.0) without having to tinker with my InterceptHttpRequestFilter and InterceptHttpResponseFilter ?
That's why it's recommended to extend HttpServletRequestWrapper instead of implementing HttpServletRequest directly.
HttpServletRequestWrapper has implementations of all required methods, therefore it should solve the problem.

Exception while trying to use jersey and jaxb

The following code:
#POST
#Path("/previous-status/{current}")
#Consumes(MediaType.APPLICATION_XML)
#Produces(MediaType.TEXT_PLAIN)
public String getPreviousStepStatus(#PathParam("current") JAXBElement<WorkflowStep> step) {
WorkflowStep wfStep = step.getValue();
return DBAccessor.getPrevStepStatus(wfStep);
}
Produces the following exception:
javax.servlet.ServletException: Servlet.init() for servlet Jersey Rest Service threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
java.lang.Thread.run(Thread.java:662)
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:771)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:766)
com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:488)
com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:318)
com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:609)
com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:210)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:373)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:556)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
java.lang.Thread.run(Thread.java:662)
If it is commented I don't get the exception. The currently used libraries in the web application are:
asm-3.1.jar
jersey-core-1.11.jar
jersey-server-1.11.jar
jsr311-api-1.1.1.jar
jersey-servlet-1.11.jar
activation.jar (part of jaxb distribution)
jaxb-api.jar
jaxb-impl.jar
stax-api-1.0.1.jar
woodstox-core-asl-4.1.2.jar
The reason I have included the last 5 libraries in the list is this article from developer works
Furthermore from the tomcat start up log I see the following:
SEVERE: The following errors and warnings have been detected with resource and/or provider classes:
SEVERE: Missing dependency for method public java.lang.String restful.SilverLine.getPreviousStepStatus(javax.xml.bind.JAXBElement) at parameter at index 0
SEVERE: Method, public java.lang.String restful.SilverLine.getPreviousStepStatus(javax.xml.bind.JAXBElement), annotated with POST of resource, class restful.SilverLine, is not recognized as valid resource method.
Any ideas will be appreciated?
PathParameter and entity is something different, try following:
#POST
#Path("/previous-status/{order}")
#Consumes(MediaType.APPLICATION_XML)
#Produces(MediaType.TEXT_PLAIN)
public String getPreviousStepStatus(#PathParam("order") int order, JAXBElement<WorkflowStep> step) {
...
WorkflowStep wfStep = step.getValue();
return DBAccessor.getPrevStepStatus(wfStep);
}
in this case, you can do requests like POST http://host/previous-status/10 and put whatever you want into entity.
You had xml in path param (which is part of URL), which is not possible to use. Your request would look like POST http://host/previous-status/<some-xml><foo>bar</foo></some-xml > , which is .. not good idea and not supported.
You should take a look at Jersey user guide: http://jersey.java.net/nonav/documentation/latest/ , topics like path param injection, accessing entity and working with XML are well covered there.

Categories

Resources