Not sure why, but when an endpoint return a String, the ResponseBodyAdvice always throws a Casting exception. Any other data type such as Long, List worked as desired, only the String data got exception. Any suggestion on how to fix this issue?
#RestController
public class AppController {
private static Logger logger = LogManager.getLogger(AppController.class);
#RequestMapping(path = "/hello",
method = GET)
public String hello() {
logger.info("... AppController.hello()");
return "hello, world!";
}
#RequestMapping(path = "/timestamp",
method = GET)
public long timestamp() {
logger.info("... AppController.timestamp()");
return System.currentTimeMillis();
}
}
here is the adviser:
#ControllerAdvice
public class ResponseAdviser implements ResponseBodyAdvice<Object> {
private static Logger logger = LogManager.getLogger(ResponseAdviser.class);
#Override
public boolean supports(MethodParameter returnType,
Class<? extends HttpMessageConverter<?>> converterType) {
logger.trace("... ResponseAdviser.supports()");
return true;
}
#Override
public Object beforeBodyWrite(Object body,
MethodParameter returnType,
MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request,
ServerHttpResponse response) {
logger.info("... ResponseAdviser.beforeBodyWrite()");
Response resp = new Response();
resp.setData(body);
return resp;
}
}
And the Reponse class is basically, adding a timestamp and enclose endpoint returned data
#Data
public class Response {
private Date timestamp;
private Object data;
public Response() {
this.timestamp = new Date();
}
}
Here is the stack trace:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: org.phan.message.Response cannot be cast to java.lang.String] with root cause
java.lang.ClassCastException: org.phan.message.Response cannot be cast to java.lang.String
at org.springframework.http.converter.StringHttpMessageConverter.getContentLength(StringHttpMessageConverter.java:41) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.http.converter.AbstractHttpMessageConverter.addDefaultHeaders(AbstractHttpMessageConverter.java:260) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:205) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:247) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:174) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:81) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:113) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55) ~[spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:110) ~[spring-boot-actuator-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:106) ~[spring-boot-actuator-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.14.jar:8.5.14]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_121]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_121]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.14.jar:8.5.14]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_121]
You can try this code below:
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
converters.add(0, new MappingJackson2HttpMessageConverter());
}
}
Reason:
The root cause of ClassCastException thrown is that you convert the response type from String to Response in the method ResponseAdviser.beforeBodyWrite.
When your return type of a controller request method is String, the HttpMessageConverter instance used to convert the return value is StringHttpMessageConverter.
The sequence of converters to use when processing your return value of a controller method is like this:
ByteArrayHttpMessageConverter cannot process String return type.
As we know, before write and flush the response, ContentLength should be calculated(when add http headers). The implements of StringHttpMessageConverter.getContentLength is like this:
We can see, the type of input parameter str is String, but actually, the response type has already been modified to Response. So the ClassCastException thrown.
Solution:
Tell spring framework, don't use StringHttpMessageConverter to process String return type in controller method. You just need to add a MappingJackson2HttpMessageConverter in front of StringHttpMessageConverter.
sample code:
#Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>>
converters) {
WebMvcConfigurer.super.configureMessageConverters(converters);
converters.add(0, new MappingJackson2HttpMessageConverter());
}
}
Why MappingJackson2HttpMessageConverter won't throw the ClassCastException? Just take a look at the implements(in its super class AbstractJackson2HttpMessageConverter):
The type of input parameter object is Object, so it can process both String and Response.
In the ResponseBodyAdvice class, add the beforeBodyWrite method:
#Override
public Object beforeBodyWrite(Object body, MethodParameter returnType,
MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request, ServerHttpResponse response) {
...
Response resp = new Response();
resp.setData(body);
//返回值body为String类型时
if (body != null && body instanceof String) {
try {
response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
return objectMapper.writeValueAsString(resp);
} catch (JsonProcessingException e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e.getMessage(), e);
}
}
...
}
Since you are using the #RestController annotation to identify your rest endpoint, if you would like to attach an Advice to it you have to use the #RestControllerAdvice annotation designed for rest endpoints.
This error occurs because the return type of beforeBodyWrite method and your requestmapping method should be same. You may try always return the Response in your controller...
All other types like fastJson or javabean have no errors except String. So I write additional code to handle String types. You can overwrite the Response's toString(), and if the coming type is String then you return Response.toString(). This may solve your problem
I recommend using the following code, override the extendMessageConverters method and remove the converters which instance of StringHttpMessageConverter class, as you don't need them at all.
By the way, If you choose to override configureMessageConverters method as your solution, it will work, but in the meantime, the properties you put in application.yml will not have any effects cause the default configuration method(which can load the properties by file) will not execute.
#Configuration
public class RestfulResponseConfigurer implements WebMvcConfigurer {
#Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.removeIf(httpMessageConverter -> httpMessageConverter instanceof StringHttpMessageConverter);
}
}
Related
I am trying to save the data in my db (already saving it in lportal). For that i created a connection file and wrote all the required code. Like we do in JDBC. I am able to store the data in lportal(default one) but when I tried to save it in my db.
I am getting below exception.
java.lang.ClassNotFoundException: org.postgresql.Driver cannot be found by ""
I tried adding the JAR to the folder but still the same thing. In JDBC we can add the JAR in lib folder but it doesn't seem to work here.
I also tried adding the jar to the tomcat bundle in lib and lib/ext folder but nothing seems to happen.
I also added the following line in my build.gradle file but no results.
compile group: 'org.postgresql', name: 'postgresql', version: '42.2.25'
Can someone help regarding this as where and how to add JAR or any other file so that I can save the data in db at the same time as lportal.
EDIT 1:
Stacktrace
java.lang.ClassNotFoundException: org.postgresql.Driver cannot be found by my.registration.form_1.0.0
at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:508)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:419)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:411)
at org.eclipse.osgi.internal.loader.ModuleClassLoader.loadClass(ModuleClassLoader.java:150)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at my.registration.form.portlet.DatabaseConnection.initializeDatabase(DatabaseConnection.java:16)
at my.registration.form.portlet.RegistrationDAO.addOrganization(RegistrationDAO.java:14)
at my.registration.form.portlet.MyRegistrationFormPortlet.addOrganization(MyRegistrationFormPortlet.java:242)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.liferay.portal.kernel.portlet.LiferayPortlet.callActionMethod(LiferayPortlet.java:189)
at com.liferay.portal.kernel.portlet.bridges.mvc.MVCPortlet.callActionMethod(MVCPortlet.java:415)
at com.liferay.portal.kernel.portlet.LiferayPortlet.processAction(LiferayPortlet.java:97)
at com.liferay.portal.kernel.portlet.bridges.mvc.MVCPortlet.processAction(MVCPortlet.java:260)
at com.liferay.portlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:77)
at com.liferay.portal.kernel.portlet.PortletFilterUtil.doFilter(PortletFilterUtil.java:50)
at com.liferay.portal.kernel.servlet.PortletServlet.service(PortletServlet.java:108)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.eclipse.equinox.http.servlet.internal.registration.EndpointRegistration.service(EndpointRegistration.java:153)
at org.eclipse.equinox.http.servlet.internal.servlet.ResponseStateHandler.processRequest(ResponseStateHandler.java:62)
at org.eclipse.equinox.http.servlet.internal.context.DispatchTargets.doDispatch(DispatchTargets.java:120)
at org.eclipse.equinox.http.servlet.internal.servlet.RequestDispatcherAdaptor.include(RequestDispatcherAdaptor.java:48)
at com.liferay.portlet.internal.InvokerPortletImpl.invoke(InvokerPortletImpl.java:564)
at com.liferay.portlet.internal.InvokerPortletImpl.invokeAction(InvokerPortletImpl.java:610)
at com.liferay.portlet.internal.InvokerPortletImpl.processAction(InvokerPortletImpl.java:299)
at com.liferay.portal.monitoring.internal.portlet.MonitoringInvokerPortlet.processAction(MonitoringInvokerPortlet.java:216)
at com.liferay.portlet.internal.PortletContainerImpl._processAction(PortletContainerImpl.java:490)
at com.liferay.portlet.internal.PortletContainerImpl.lambda$processAction$0(PortletContainerImpl.java:148)
at com.liferay.portlet.internal.PortletContainerImpl._preserveGroupIds(PortletContainerImpl.java:395)
at com.liferay.portlet.internal.PortletContainerImpl.processAction(PortletContainerImpl.java:141)
at com.liferay.portlet.SecurityPortletContainerWrapper.processAction(SecurityPortletContainerWrapper.java:95)
at com.liferay.portlet.RestrictPortletContainerWrapper.processAction(RestrictPortletContainerWrapper.java:78)
at com.liferay.portal.kernel.portlet.PortletContainerUtil.processAction(PortletContainerUtil.java:118)
at com.liferay.portal.action.LayoutAction.processLayout(LayoutAction.java:346)
at com.liferay.portal.action.LayoutAction.execute(LayoutAction.java:174)
at com.liferay.portal.struts.PortalRequestProcessor._processActionPerform(PortalRequestProcessor.java:706)
at com.liferay.portal.struts.PortalRequestProcessor._process(PortalRequestProcessor.java:646)
at com.liferay.portal.struts.PortalRequestProcessor.process(PortalRequestProcessor.java:194)
at com.liferay.portal.servlet.MainServlet.process(MainServlet.java:1067)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at com.liferay.portal.servlet.MainServlet.callParentService(MainServlet.java:598)
at com.liferay.portal.servlet.MainServlet.service(MainServlet.java:575)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:119)
at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:103)
at com.liferay.portal.apio.internal.architect.servlet.filter.APIDocumentationFilter.processFilter(APIDocumentationFilter.java:74)
at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
at com.liferay.portal.servlet.filters.uploadservletrequest.UploadServletRequestFilter.processFilter(UploadServletRequestFilter.java:111)
at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
at com.liferay.portal.servlet.filters.password.modified.PasswordModifiedFilter.processFilter(PasswordModifiedFilter.java:57)
at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
at com.liferay.portal.servlet.filters.secure.BaseAuthFilter.processFilter(BaseAuthFilter.java:340)
at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
at com.liferay.portal.monitoring.internal.servlet.filter.MonitoringFilter.processFilter(MonitoringFilter.java:178)
at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilter.doFilter(InvokerFilter.java:101)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:712)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:459)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:384)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312)
at com.liferay.friendly.url.internal.servlet.FriendlyURLServlet.service(FriendlyURLServlet.java:372)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at com.liferay.portal.servlet.ServletAdapter.service(ServletAdapter.java:98)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:119)
at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:103)
at com.liferay.portal.apio.internal.architect.servlet.filter.APIDocumentationFilter.processFilter(APIDocumentationFilter.java:74)
at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
at com.liferay.portal.servlet.filters.uploadservletrequest.UploadServletRequestFilter.processFilter(UploadServletRequestFilter.java:111)
at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
at com.liferay.portal.servlet.filters.strip.StripFilter.processFilter(StripFilter.java:340)
at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
at com.liferay.portal.servlet.filters.i18n.I18nFilter.processFilter(I18nFilter.java:360)
at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
at com.liferay.portal.servlet.filters.password.modified.PasswordModifiedFilter.processFilter(PasswordModifiedFilter.java:57)
at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
at com.liferay.portal.servlet.filters.secure.BaseAuthFilter.processFilter(BaseAuthFilter.java:340)
at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
at com.liferay.portal.servlet.filters.autologin.AutoLoginFilter.processFilter(AutoLoginFilter.java:260)
at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
at com.liferay.portal.sharepoint.SharepointFilter.processFilter(SharepointFilter.java:88)
at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
at com.liferay.portal.servlet.filters.virtualhost.VirtualHostFilter.processFilter(VirtualHostFilter.java:263)
at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:144)
at com.liferay.portal.monitoring.internal.servlet.filter.MonitoringFilter.processFilter(MonitoringFilter.java:178)
at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDirectCallFilter(InvokerFilterChain.java:188)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:96)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDirectCallFilter(InvokerFilterChain.java:188)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:96)
at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:176)
at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145)
at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92)
at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:389)
at com.liferay.portal.servlet.filters.urlrewrite.UrlRewriteFilter.processFilter(UrlRewriteFilter.java:65)
at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:49)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDoFilter(InvokerFilterChain.java:207)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:112)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDirectCallFilter(InvokerFilterChain.java:168)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:96)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDirectCallFilter(InvokerFilterChain.java:168)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:96)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.processDirectCallFilter(InvokerFilterChain.java:188)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:96)
at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilter.doFilter(InvokerFilter.java:101)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:491)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:764)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1388)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
EDIT 2:
My connection class
package my.registration.form.portlet;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection
{
protected static Connection initializeDatabase()throws SQLException, ClassNotFoundException
{
String driver = "org.postgresql.Driver";
String url = "jdbc:postgresql://localhost:5432/my_lportal";
String user = "user";
String password = "password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,user,password);
return conn;
}
}
DAO:
public class RegistrationDAO
{
public static void addOrganization(long OrganizationId, String organizationName, long countryId) throws ClassNotFoundException, SQLException
{
Connection conn = DatabaseConnection.initializeDatabase();
String query = "insert into organization(OrganizationId, organizationName, countryId) values(?,?,?)";
try
{
PreparedStatement prestmt = conn.prepareStatement(query);
prestmt.setLong(1, OrganizationId);
prestmt.setString(2, organizationName);
prestmt.setLong(3, countryId);
System.out.println("Organization Added Successfully in my_lportal Database !!");
prestmt.executeUpdate();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
Controller:
#ProcessAction(name = "addOrganization")
public void addOrganization(ActionRequest actionRequest, ActionResponse actionResponse) throws IOException, PortletException
{
ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
long UserId = themeDisplay.getUserId();
String organizationName = ParamUtil.getString(actionRequest, "organizationName");
String country = ParamUtil.getString(actionRequest, "country");
String type = "organization";
long countryId = ParamUtil.getLong(actionRequest, "countryId");
long statusId = ParamUtil.getLong(actionRequest, "statusId");
try
{ // For storing in lportal(default)
Organization organization = OrganizationLocalServiceUtil.addOrganization
(
UserId, 0, organizationName, type, 0,
countryId, 12017, null, false, null
);
_log.info("Organization Added Successfully !!");
// For storing in my database
long OrganizationId = organization.getOrganizationId();
RegistrationDAO.addOrganization(OrganizationId, organizationName, countryId);
_log.info("Organization Added Successfully in my_lportal Database !!");
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
First of all your question is very confusing. So you want to use a PostgreSQL for your Liferay Portal right?
You configured everything correctly and downloaded the driver from https://jdbc.postgresql.org/download/postgresql-42.4.1.jar?
Just put this driver in tomcat/lib not ext (maybe it is not configured to load). Restart the server.
Please provide the complete startup log output.
EDIT1:
Ok now I see what is wrong. Your gradle file need to compileInclude instead of compile the lib. The scope compile is only for compilation phase but you also need the library during runtime in the portlet so thats why you need to compileInclude it.
OSGI is a bit tricky when it comes to dependencies because you will get errors after this compileInclude. The portlet will tell you that there are missing dependencies. You can put them to an ignore list.
build.gradle - add line
compileInclude group: 'org.postgresql', name: 'postgresql', version: '42.4.1'
You need to put some packages to not import them in the bnd.bnd file. Just copy the Import-Package part. It needs to be copied in exact this way!
Bundle-Name: test-redirect-jsp
Bundle-SymbolicName: test.redirect.jsp
Bundle-Version: 1.0.0
Export-Package: test.redirect.jsp.constants
Import-Package:\
!com.sun.jna*,\
!org.osgi.service.jdbc*,\
!waffle.windows.auth*,\
*
The driver class should now be available during runtime.
MyTest
public class StaticTest {
public static void test() {
String driver = "org.postgresql.Driver";
try {
Class c = Class.forName(driver);
System.out.println(c.getName());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Called
#ProcessAction(name = "addOrganization")
public void addOrganization(ActionRequest actionRequest, ActionResponse actionResponse)
throws IOException, PortletException {
StaticTest.test();
}
Please be adviced that my and your solution are very dirty. This is not how it would be done and recommended. The clean way would be setup a second datasource via properties and build your external entities via service builder.
Again - please refer to https://help.liferay.com/hc/en-us/articles/360018160911-Connecting-Service-Builder-to-External-Data-Sources
At start up liferay provides the option using which we can change liferay database. Following is the steps for the same.
1.1) Create a database in postgresql(like lportal).
1.2) Select the change database option at liferay start up.
1.3) Enter your databse url,username and password.
You can create a file with name portal-ext.properties in Liferay root folder(check attached screen shot).
Add following database configuration.
Postgresql
jdbc.default.driverClassName= enter driver
jdbc.default.url= enter URL
jdbc.default.username= enter UserName
jdbc.default.password= enter Password
I am learning unit testing. I have implemented unit test for the spring boot controller in my sample project. When I run the test class, every time it returns 400 status (Expected 200). After i did a research and I have found that if(entity.getStatusCode().equals(HttpStatus.OK)) { is line which gives exception. It might be because it uses return of Service2.
However, code is working fine without running test cases. I have attached MyController and MyControllerTest classes.
My Controller
#RestController
#RequestMapping("/user")
public class UserController {
private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
#Autowired
private UserManagementService userManageService;
#Autowired
private AdminManagementService adminManageService;
#Autowired
private AuthenticateManagementService authService;
#PutMapping("/change-password")
public ResponseEntity<?> changePassword(#RequestHeader("Authorization") String token,
#RequestBody PasswordChangeRequestDTO passwordChangeRequestDTO) {
ResponseDTO finalResponse = new ResponseDTO();
try {
LOGGER.info("Changing user password.");
KeycloakLoginResponseDTO keycloakResponse = authService.auhtenticate(passwordChangeRequestDTO.getLoginRequestDTO());
ResponseEntity<?> logoutEntity = authService.logout(token, keycloakResponse.getSession_state());
if(logoutEntity.getStatusCode().equals(HttpStatus.OK)) {
LOGGER.info("User password matched");
}
String userId = adminManageService.getUserByName(token, passwordChangeRequestDTO.getLoginRequestDTO().getUsername());
ResponseEntity<?> entity = userManageService.changePassword(token, passwordChangeRequestDTO, userId);
LOGGER.info("USER : " + "" +"has successfully changed password.");
finalResponse.setMessageCode(HttpStatus.OK);
finalResponse.setMessage("Password changed successfully");
finalResponse.setError(false);
ResponseEntity<ResponseDTO> finalEntity = ResponseEntity.ok().body(finalResponse);
return finalEntity;
}catch (Exception e) {
e.printStackTrace();
LOGGER.error("Error has occured while changing password of USER : " + "" + ".");
finalResponse.setMessageCode(HttpStatus.EXPECTATION_FAILED);
finalResponse.setMessage("Oops! Looks like you have entered the wrong password in the 'Old Password' field");
finalResponse.setMessageDetail(e.getMessage());
finalResponse.setError(true);
ResponseEntity<ResponseDTO> finalEntity = ResponseEntity.badRequest().body(finalResponse);
return finalEntity;
}
}
}
Controller Unit test class
#RunWith(SpringRunner.class)
#WebMvcTest(UserController.class)
public class UserControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private UserManagementService userManageService;
#MockBean
private AdminManagementService adminManageService;
#MockBean
private AuthenticateManagementService authService;
#InjectMocks
private UserController userController;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
#Test
public void testChangePasswordhappyPath() throws Exception {
PasswordChangeRequestDTO passwordChangeRequestDTO = new PasswordChangeRequestDTO();
LoginRequestDTO loginRequestDTO = new LoginRequestDTO();
loginRequestDTO.setClient_id("test_client");
loginRequestDTO.setGrant_type("test_grant_type");
loginRequestDTO.setPassword("test_password");
loginRequestDTO.setUsername("test_user");
CredentialsRequestDTO credentialsRequestDTO = new CredentialsRequestDTO();
credentialsRequestDTO.setTemporary(false);
credentialsRequestDTO.setType("password");
credentialsRequestDTO.setValue("test_password");
passwordChangeRequestDTO.setLoginRequestDTO(loginRequestDTO);
passwordChangeRequestDTO.setCredentialsRequestDTO(credentialsRequestDTO);
ResponseEntity<String> mockResponse = new ResponseEntity<String>("", HttpStatus.OK);
when(userManageService.changePassword("Token", passwordChangeRequestDTO, "UserId")).thenReturn(mockResponse);
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(passwordChangeRequestDTO);
mockMvc.perform(put("/user/change-password", passwordChangeRequestDTO)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", "Token")
.content(json)
.characterEncoding("utf-8"))
.andExpect(status().isOk()).andReturn();
}
}
What am i doing wrong here. Is there anything to add to my MyControllerTest class or How can i cover this test case. Any help would be grateful.
UPDATED
I have also added e.printStackTrace()
java.lang.NullPointerException
at com.mycode.controller.UserController.changePassword(UserController.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
at org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:919)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:663)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:166)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:182)
at com.mycode.controller.UserControllerTest.testChangePasswordhappyPath(UserControllerTest.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Failed to start bean eurekaAutoServiceRegistration caused by No Scope registered for scope name 'refresh'
#SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
#EnableDiscoveryClient
public class WebRun extends SpringBootServletInitializer {
public SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(WebRun.class);
}
public static void main(String[] args) {
SpringApplication.run(WebRun.class, args);
}
}
2-May-2019 16:45:22.965 信息 [http-nio-9999-exec-1]
org.apache.catalina.core.ApplicationContext.log Initializing Spring
FrameworkServlet 'dispatcher' 22-May-2019 16:46:04.846 严重
[http-nio-9999-exec-1] org.apache.catalina.core.ApplicationContext.log
StandardWrapper.Throwable
org.springframework.context.ApplicationContextException: Failed to
start bean 'eurekaAutoServiceRegistration'; nested exception is
java.lang.IllegalStateException: No Scope registered for scope name
'refresh' at
org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:178)
at
org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:50)
at
org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:348)
at
org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:151)
at
org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:114)
at
org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:880)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546)
at
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
at
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:540)
at
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
at
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:171)
at javax.servlet.GenericServlet.init(GenericServlet.java:158) at
org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1142)
at
org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:789)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:660)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:798)
at
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:808)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
at
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748) Caused by:
java.lang.IllegalStateException: No Scope registered for scope name
'refresh' at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:337)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at
org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35)
at
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.getTarget(CglibAopProxy.java:705)
at
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
at
com.netflix.appinfo.ApplicationInfoManager$$EnhancerBySpringCGLIB$$4652f076.getInfo()
at
org.springframework.cloud.netflix.eureka.serviceregistry.EurekaServiceRegistry.maybeInitializeClient(EurekaServiceRegistry.java:55)
at
org.springframework.cloud.netflix.eureka.serviceregistry.EurekaServiceRegistry.register(EurekaServiceRegistry.java:37)
at
org.springframework.cloud.netflix.eureka.serviceregistry.EurekaAutoServiceRegistration.start(EurekaAutoServiceRegistration.java:73)
at
org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:175)
... 30 more 22-May-2019 16:46:04.847 严重 [http-nio-9999-exec-1]
org.apache.catalina.core.StandardWrapperValve.invoke Allocate
exception for servlet [dispatcher] java.lang.IllegalStateException:
No Scope registered for scope name 'refresh' at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:337)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at
org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35)
at
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.getTarget(CglibAopProxy.java:705)
at
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
at
com.netflix.appinfo.ApplicationInfoManager$$EnhancerBySpringCGLIB$$4652f076.getInfo()
at
org.springframework.cloud.netflix.eureka.serviceregistry.EurekaServiceRegistry.maybeInitializeClient(EurekaServiceRegistry.java:55)
at
org.springframework.cloud.netflix.eureka.serviceregistry.EurekaServiceRegistry.register(EurekaServiceRegistry.java:37)
at
org.springframework.cloud.netflix.eureka.serviceregistry.EurekaAutoServiceRegistration.start(EurekaAutoServiceRegistration.java:73)
at
org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:175)
at
org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:50)
at
org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:348)
at
org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:151)
at
org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:114)
at
org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:880)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546)
at
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
at
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:540)
at
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
at
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:171)
at javax.servlet.GenericServlet.init(GenericServlet.java:158) at
org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1142)
at
org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:789)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:660)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:798)
at
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:808)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
at
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
I think you have a mistake in your project configuration or a version mismatching in your dependencies.
Case(1):
Please check you don't have more than one class that extends SpringBootServletInitializer.
In one of the my projects, I had the two below classes by mistake:
#SpringBootApplication
#EnableEurekaClient
public class MyApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(MyApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
public class ServletInitializer extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(CamponoApplication.class);
}
}
Therefore, I deleted the second class from the my project and the problem was solved.
I hope this helps you
I've got a simple Rest Controller that returns ResponseEntity<Void>. I'm trying to call it though Feign client and getting NPE while decoding the result. Spring cloud version: Angel.SR3, Feign version: 8.9.0
Changing the return value to ResponseEntity<String> and passing some dummy value solves the problem, but is it supposed to work with Void return type?
java.lang.NullPointerException: null
at org.springframework.cloud.netflix.feign.support.ResponseEntityDecoder.decode(ResponseEntityDecoder.java:43)
at feign.SynchronousMethodHandler.decode(SynchronousMethodHandler.java:146)
at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:118)
at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:71)
at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:94)
at com.sun.proxy.$Proxy95.testPost(Unknown Source)
at com.test.TestResource.testGet(TestResource.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
RestController:
#RestController
public class TestResource {
#RequestMapping(value = "/test", method = RequestMethod.GET, consumes="application/json", produces="application/json")
ResponseEntity<Void> testPost() {
return new ResponseEntity<>(HttpStatus.OK);
}
}
Feign Client to access the rest resource:
#FeignClient("order-service")
public interface TestClient {
#RequestMapping(value = "/test", method = RequestMethod.GET, consumes="application/json", produces="application/json")
ResponseEntity<Void> testGet();
}
Call of the feign client:
#Service
public class Test {
#Autowired
private TestClient testClient;
void test() {
testClient.testGet(); // this line triggers NPE
}
}
The issue is fixed on the 1.0.x line and will be in Angel.SR4, it already worked in Brixton.M1, but I forward ported the test. See https://github.com/spring-cloud/spring-cloud-netflix/issues/539 for the commits.
I'm using a REST service with CXF that does a GET request with an int parameter.
#Path("parkingservice")
public interface ParkingService {
/**
* #param id
* #return
*/
#GET
#Path("/parkings/{id}/parkingState")
#Produces(MediaType.APPLICATION_JSON)
ParkingState getStatus(#PathParam("id") int id);
}
I call my service this way :
http://domain.com:8087/services/rest/parkingservice/parkings/2805/parkingState
When I put a number, it works, but when I put a String, I have this exception :
WARNING: javax.ws.rs.NotFoundException: java.lang.NumberFormatException: For input string: "dd"
at org.apache.cxf.jaxrs.utils.InjectionUtils.handleParameter(InjectionUtils.java:322)
at org.apache.cxf.jaxrs.utils.InjectionUtils.createParameterObject(InjectionUtils.java:845)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.readFromUriParam(JAXRSUtils.java:1041)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.createHttpParameterValue(JAXRSUtils.java:733)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.processParameter(JAXRSUtils.java:708)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.processParameters(JAXRSUtils.java:655)
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.processRequest(JAXRSInInterceptor.java:238)
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.handleMessage(JAXRSInInterceptor.java:99)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:271)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:239)
at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:223)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:203)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:137)
at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:158)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:243)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doGet(AbstractHTTPServlet.java:168)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:219)
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:472)
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:947)
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:1009)
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$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:680)
Caused by: java.lang.NumberFormatException: For input string: "dd"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:449)
at java.lang.Integer.valueOf(Integer.java:554)
at org.apache.cxf.common.util.PrimitiveUtils.read(PrimitiveUtils.java:60)
at org.apache.cxf.jaxrs.utils.InjectionUtils.handleParameter(InjectionUtils.java:310)
... 34 more
I'd like to avoid having this exception no matter what type I give..or to find a way to handle this exception with a message like "please provide a good Id"
Thanks a lot
Add an exception mapper to your rest layer. Code goes something like this :
package com.cxf.util;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
public class CustomExceptionMapper implements
ExceptionMapper<NotFoundException> {
public CustomExceptionMapper () {
}
#Override
public Response toResponse(NotFoundException arg0) {
//your logic and return accordingly
return Response.serverError().build();
}
}
And you if you are using Spring to maintain your service beans and cxf configuration then add this mapper as a bean under jaxrs:providers tag, where jaxrs is this : xmlns:jaxrs="http://cxf.apache.org/jaxrs"
Whenever your application will throw notfoundexception it will go in this class.
Second option is that you can take this parameter as String then parse it in your try catch block. On NumberformatException return 400 status code. Since you have a custom POJO as return, you can take a object of HttpServletResponse from org.apache.cxf.jaxrs.ext.MessageContext and set status in it. Below is a dummy code:
public class RestServiceImpl implements RestService{
#Context
MessageContext context;
public CustomPojo getData(String id){
HttpServletResponse httpResponse = context.getHttpServletResponse();
try{
}catch(NumberFormatException e){
httpResponse.setStatusCode(400);
}
}
}
Use the below signature for getStatus method, this would work both ways.
ParkingState getStatus(#PathParam("id") String id);
Your getStatus(#PathParam("id") int id); takes integer as an argument and you are trying to pass String instead of int, that's why it's throwing an exception of NumberFormatException.
You have to handle it,or make a Check is the incoming value is int if not then so a message "please provide a valid input".