I have hibernate filter like this:
#Entity
#FilterDef(name = "filter_name", parameters = { #ParamDef(name = "tenatId", type = "long") })
#Filter(name = "filter_name", condition = "tenant_id = :tenantId")
public class MyEntity {
private long tenantId;
}
And I want to enable this filter every time request come, so I create Request Interceptor like this:
#Configuration
public class RequestInterceptor implements HandlerInterceptorAdapter {
#PersistenceContext
private EntityManager entityManager;
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
Filter filter = entityManager.unwrap(Session.class).enableFilter("filter_name");
filter.setParameter("tenantId", myService.getTentantId());
}
}
But I cannot the transaction manager, got error:
java.lang.IllegalStateException: No transactional EntityManager available
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:272)
at com.sun.proxy.$Proxy184.unwrap(Unknown Source)
at id.gdplabs.koi.api.config.security.RequestInterceptor.preHandle(RequestInterceptor.java:27)
at org.springframework.web.servlet.handler.WebRequestHandlerInterceptorAdapter.preHandle(WebRequestHandlerInterceptorAdapter.java:56)
at org.springframework.web.servlet.HandlerExecutionChain.applyPreHandle(HandlerExecutionChain.java:134)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:958)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
...
It works if I move the code to controller:
#RequestMapping(method = RequestMethod.GET, value = "/test")
public List<MyEntity> test() {
Filter filter = entityManager.unwrap(Session.class).enableFilter("filter_name");
filter.setParameter("tenantId", myService.getTentantId());
return myService.findAll();
}
Do you have idea why I cannot unwrap hibernate session in the Interceptor?
Any suggestion are welcome, Thanks!
Related
I have an endpoint on my controller which takes a list of IDs. For each ID I fetch details from a REST endpoint which I would like to do asynchronously. This is my implementation:
#PostMapping("/leaderboard")
#ApiOperation("Get clients leaderboard statistics")
public List<Dto> clientLeaderboard(#RequestBody List<String> accountIds) {
IntStream.range(0, accountIds.size()).parallel().forEach(i -> {
AccountDTO accountDTO = accountMaintenanceRestClient.getAccount(accountIds.get(i));
// More logic
}
}
This then gives me the error:
Unhandled exception occurred
java.lang.IllegalStateException: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
I've actually experienced this error before and managed to fix it in an answer here. Is the same solution applicable here? If so how can I provide my existing executor to this parallel stream?
Edit
AccountMaintenanceRestClient code. I'm using OpenFeign as part of this.
public interface AccountMaintenanceRestClient {
#RequestLine("GET /account/{accountId}")
#Profiled(tag = "AccountMaintenanceRestClient.{$0}.getAccountBalance", logFailuresSeparately = true)
AccountDTO getAccount(#Param("accountId") String accountId);
#RequestLine("GET /referencedata/statuscode")
#Profiled(tag = "AccountMaintenanceRestClient.getStatusCodes", logFailuresSeparately = true)
Map<String, String> getStatusCodes();
#RequestLine("GET /referencedata/websites")
#Profiled(tag = "AccountMaintenanceRestClient.getWebsitesIds", logFailuresSeparately = true)
List<WebSiteDTO> getWebsitesIds();
}
Stacktrace:
java.lang.IllegalStateException: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.util.concurrent.ForkJoinTask.getThrowableException(ForkJoinTask.java:593)
at java.util.concurrent.ForkJoinTask.reportException(ForkJoinTask.java:677)
at java.util.concurrent.ForkJoinTask.invoke(ForkJoinTask.java:735)
at java.util.stream.ForEachOps$ForEachOp.evaluateParallel(ForEachOps.java:160)
at java.util.stream.ForEachOps$ForEachOp$OfInt.evaluateParallel(ForEachOps.java:189)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:233)
at java.util.stream.IntPipeline.forEach(IntPipeline.java:404)
at java.util.stream.IntPipeline$Head.forEach(IntPipeline.java:560)
at com.foobar.wt.igip.gateway.web.controllers.surge.paris.SurgeParisController.clientLeaderboard(SurgeParisController.java:58)
at com.foobar.wt.igip.gateway.web.controllers.surge.paris.SurgeParisController$$FastClassBySpringCGLIB$$a143909.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:667)
at com.foobar.wt.igip.gateway.web.controllers.surge.paris.SurgeParisController$$EnhancerBySpringCGLIB$$67cb3a1e.clientLeaderboard(<generated>)
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 org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:854)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:765)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
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.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:54)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:111)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at uk.co.igindex.commons.bluegreen.IGClusterDetailsFilter.doFilter(IGClusterDetailsFilter.java:46)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:208)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:347)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:263)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:128)
at org.springframework.boot.web.support.ErrorPageFilter.access$000(ErrorPageFilter.java:66)
at org.springframework.boot.web.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:103)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:121)
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:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1757)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1716)
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 thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131)
at org.springframework.web.context.support.WebApplicationContextUtils.currentRequestAttributes(WebApplicationContextUtils.java:309)
at org.springframework.web.context.support.WebApplicationContextUtils.access$400(WebApplicationContextUtils.java:64)
at org.springframework.web.context.support.WebApplicationContextUtils$RequestObjectFactory.getObject(WebApplicationContextUtils.java:325)
at org.springframework.web.context.support.WebApplicationContextUtils$RequestObjectFactory.getObject(WebApplicationContextUtils.java:320)
at org.springframework.beans.factory.support.AutowireUtils$ObjectFactoryDelegatingInvocationHandler.invoke(AutowireUtils.java:307)
at com.sun.proxy.$Proxy134.getHeader(Unknown Source)
at com.foobar.wt.igip.gateway.support.FeignSSOTokenRequestInterceptor.apply(FeignSSOTokenRequestInterceptor.java:22)
at feign.SynchronousMethodHandler.targetRequest(SynchronousMethodHandler.java:158)
at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:88)
at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:76)
at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:103)
at com.sun.proxy.$Proxy156.getAccount(Unknown Source)
at com.foobar.wt.igip.gateway.web.controllers.surge.paris.SurgeParisController.lambda$clientLeaderboard$2(SurgeParisController.java:59)
at java.util.stream.ForEachOps$ForEachOp$OfInt.accept(ForEachOps.java:205)
at java.util.stream.Streams$RangeIntSpliterator.forEachRemaining(Streams.java:110)
at java.util.Spliterator$OfInt.forEachRemaining(Spliterator.java:693)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.ForEachOps$ForEachTask.compute(ForEachOps.java:291)
at java.util.concurrent.CountedCompleter.exec(CountedCompleter.java:731)
at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
FeignSSOTokenRequestInterceptor:
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
#Component
public class FeignSSOTokenRequestInterceptor implements RequestInterceptor {
private static final String SSO_HEADER_NAME = "X-SECURITY-TOKEN";
private final HttpServletRequest request;
#Autowired
public FeignSSOTokenRequestInterceptor(HttpServletRequest request) {
this.request = request;
}
#Override
public void apply(RequestTemplate requestTemplate) {
requestTemplate.header(SSO_HEADER_NAME, request.getHeader(SSO_HEADER_NAME));
}
}
Your FeignSSOTokenRequestInterceptor depends on HttpServletRequest proxied bean.
The request is exposed via threadlocal so threads in threadpool has no knowledge/aware of it, hence exception occurs when it try to read the request from threadlocal map.
So basically the problem narrowed down to how to set the request to the threadpool's thread context.
Setup a threadpool like your referenced post then submit the task,
#Autowired
ThreadPoolTaskExecutor poolExecutor;
CountdownLatch counter = new CountdownLatch(accountIds.size());
IntStream.range(0, accountIds.size()) // Note that .parallel is omitted
.forEach(() -> poolExecutor.submit(() -> {
try {
your task
} finally {
counter.countDown();
}
}))
counter.await(); // Wait for all tasks complete
This is prefered way, because the default parallel stream is used a common shared pool, you should not place a task has heavy IO like API access to that)
I would like to throw some light on the question.
FeignSSOTokenRequestInterceptor is your custom RequestInterceptor and you are trying to access ServletRequest inside the apply method which is evident from the stack trace
RequestObjectFactory.getObject(WebApplicationContextUtils.java:320)
This RequestObjectFactory is a static inner class which gives you access the current request
private static class RequestObjectFactory implements ObjectFactory<ServletRequest>, Serializable {
private RequestObjectFactory() {
}
public ServletRequest getObject() {
return WebApplicationContextUtils.currentRequestAttributes().getRequest();
}
public String toString() {
return "Current HttpServletRequest";
}
}
the current request is derived from the RequestContextHolder class which gets the attribute from the current thread as shown below after a series of method calls
//This is the current thread which holds the request attributes
private static final ThreadLocal<RequestAttributes> requestAttributesHolder = new NamedThreadLocal("Request attributes");
//This is the place where you get the actual exception from the spring RequestContextHolder class.
public static RequestAttributes currentRequestAttributes() throws IllegalStateException {
RequestAttributes attributes = getRequestAttributes();
if (attributes == null) {
if (jsfPresent) {
attributes = RequestContextHolder.FacesRequestAttributesFactory.getFacesRequestAttributes();
}
if (attributes == null) {
throw new IllegalStateException("No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.");
}
}
return attributes;
}
public static RequestAttributes getRequestAttributes() {
RequestAttributes attributes = (RequestAttributes)requestAttributesHolder.get();
if (attributes == null) {
attributes = (RequestAttributes)inheritableRequestAttributesHolder.get();
}
return attributes;
}
final verdict:
so make sure you are not trying to access the ServletRequest from the RequestInterceptor if you are using parallel streams. since parallel streams must be used only with stateless, non-interfering, and associative operations
since requestAttributesHolder.get() looks for the current thread do not use parallel streams on it as shown below .which is not recommended and parallelism has a lot of things to be considered refer(link)
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
#SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
if you do not have any code that is accessing the current request and it's being called from the OpenFeign class files then the only way is to use the sequential streams instead of parallel streams.which is straightforward
accountIds.stream().forEach(accountId -> {
AccountDTO accountDTO = accountMaintenanceRestClient.getAccount(accountId);
// More logic
}
I have some REST Web Services in Spring Boot (version 1.5.13)
I would like to use #ControllerAdvice to handle the exceptions thrown by the controllers.
For the API testA below, the #ControllerAdvice class is able to capture and handle the exception if id=123, however, if id is not equals to 123, my program is not able to convert the ResponseEntity to JSON and "org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation (406)" is thrown.
If I uncomment the #EnableWebMvc below, the ResponseEntity is able to return the JSON result correctly, however, the #ControllerAdvice will not be able to capture the exception.
#RestController("SpocController")
//#EnableWebMvc
#RequestMapping(value = { "/testing" })
public class TestController
{
#GetMapping(value = "/testA", produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody ResponseEntity<Object> testA(#RequestParam String id) throws IOException
{
if(id.equals("123"))
{
throw new IOException("customized exception");
}
Map<String,Object> body = new HashMap<String, Object>();
body.put("hello", "hihi");
return new ResponseEntity<Object>(body, HttpStatus.OK);
}
#GetMapping(value = "/testB", produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String testB(#RequestParam String id) throws IOException
{
if(id.equals("123"))
{
throw new IOException("customized exception");
}
return "{ \"ok\":\"test ok\" }";
}
}
For API testB, as the return type is String, it was able to return the string in JSON, and #ControllerAdvice is also able to capture and handle the exception.
This is my ControllerAdvice:
#ControllerAdvice
public class TestExceptionHandler
{
#ResponseBody
#ExceptionHandler(IOException.class)
protected ResponseEntity<Object> handleIOException(IOException ex)
{
Map<String, Object> map = new HashMap<String, Object>();
map.put("message", ex.getMessage());
return new ResponseEntity(map, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
This is the HttpMediaTypeNotAcceptableException (406) I mentioned above.
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:259)
at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:208)
at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:81)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:113)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
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:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
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:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468)
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)
1) No matter where I put the #EnableWebMvc (in #RestController, #ControllerAdvice or other classes), my #ExceptionHandler will not be able to capture any exception. Any idea why it happens?
2) I would like to get my API testA working as I really want to return a ResponseEntity type and the exception thrown by it can be captured by the #ControllerAdvice. Any advice is welcomed.
Thanks in advance.
With #RestController,
No need to use #ResponseBody, you can view the document for more detail.
-Make sure your request mapping work and log something.
-Try using #RestControllerAdvice for #RestController
Found the culprit, after commenting the following section of code, everything works like a charm. Anyway, thank you everyone!
public HandlerExceptionResolver handlerExceptionResolver()
{
return new HandlerExceptionResolver()
{
#Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception)
{
return null;
}
};
}
#RestController
#RequestMapping(value = { "/testing" })
public class ExceptionController {
#GetMapping(value = "/testA", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> testA(#RequestParam String id) throws IOException
{
if(id.equals("123"))
{
throw new IOException("customized exception");
}
Map<String,Object> body = new HashMap<String, Object>();
body.put("hello", "hihi");
return new ResponseEntity<Object>(body, HttpStatus.OK);
}
#GetMapping(value = "/testB", produces = MediaType.APPLICATION_JSON_VALUE)
public String testB(#RequestParam String id) throws IOException
{
if(id.equals("123"))
{
throw new IOException("customized exception");
}
return "{ \"ok\":\"test ok\" }";
}
}
2.change your advice controller-:
package com.ad.blog.controller;
import java.io.IOException;
import java.util.Optional;
import org.springframework.hateoas.VndErrors;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
#org.springframework.web.bind.annotation.ControllerAdvice
#RequestMapping(produces = "application/vnd.error+json")
public class ControllerAdvice {
#ExceptionHandler(IOException.class) public ResponseEntity < VndErrors > notFoundException(final IOException e) {
return error(e, HttpStatus.NOT_FOUND, e.getMessage());
}
private ResponseEntity < VndErrors > error(final Exception exception, final HttpStatus httpStatus, final String logRef) {
final String message = Optional.of(exception.getMessage()).orElse(exception.getClass().getSimpleName());
return new ResponseEntity < > (new VndErrors(logRef, message), httpStatus);
}
}
you need to add hateos dependency in your pom.xml file.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
#EnableWebMVc annotation is used to enable MVC Java config that overrides the DispatcherServlet defaults configuration.if you want to override default configuration then create a class-:
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
}
I need to add additional business-logic for POST method. For now, I'm going to reuse the logic from RepositoryEntityController for getting and save the needed object.
#RepositoryRestController
#RequestMapping("/customPost")
public class UserController implements ApplicationEventPublisherAware {
private final UserRepository userRepository;
private final RepositoryRestConfiguration config;
private final HttpHeadersPreparer headersPreparer;
private ApplicationEventPublisher publisher;
#Autowired
public UserController(UserRepository userRepository, RepositoryRestConfiguration config, HttpHeadersPreparer headersPreparer) {
this.userRepository = userRepository;
this.config = config;
this.headersPreparer = headersPreparer;
}
public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
#ResponseBody
#RequestMapping(
value = {"/{repository}"},
method = {RequestMethod.POST}
)
public ResponseEntity<ResourceSupport> postCollectionResource(PersistentEntityResource payload, PersistentEntityResourceAssembler assembler, #RequestHeader(value = "Accept", required = false) String acceptHeader) throws HttpRequestMethodNotSupportedException {
return this.createAndReturn(payload.getContent(), assembler, this.config.returnBodyOnCreate(acceptHeader));
}
private ResponseEntity<ResourceSupport> createAndReturn(Object domainObject, PersistentEntityResourceAssembler assembler, boolean returnBody) {
publisher.publishEvent(new BeforeCreateEvent(domainObject));
Object savedObject = userRepository.save((User) domainObject);
publisher.publishEvent(new AfterCreateEvent(savedObject));
PersistentEntityResource resource = returnBody ? assembler.toFullResource(savedObject) : null;
HttpHeaders headers = headersPreparer.prepareHeaders(resource);
addLocationHeader(headers, assembler, savedObject);
return ControllerUtils.toResponseEntity(HttpStatus.CREATED, headers, resource);
}
private void addLocationHeader(HttpHeaders headers, PersistentEntityResourceAssembler assembler, Object source) {
String selfLink = assembler.getSelfLinkFor(source).getHref();
headers.setLocation((new UriTemplate(selfLink)).expand(new Object[0]));
}
}
The code which I sent - is working ok. But the issue is that I need to add some request mapping #RequestMapping("/customPost") to controller.
Without this mapping - method will not work. I tried to have the same controller but without "/customPost" mapping. I got this exception at start of applicaton:
caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'repositoryEntityController' method
public org.springframework.http.ResponseEntity<org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryEntityController.postCollectionResource(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.data.rest.webmvc.PersistentEntityResource,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler,java.lang.String) throws org.springframework.web.HttpRequestMethodNotSupportedException
to {[/{repository}],methods=[POST],produces=[application/hal+json || application/json]}: There is already 'userController' bean method
public org.springframework.http.ResponseEntity<org.springframework.hateoas.ResourceSupport> com.project.controller.UserController.postCollectionResource(org.springframework.data.rest.webmvc.PersistentEntityResource,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler,java.lang.String) throws org.springframework.web.HttpRequestMethodNotSupportedException mapped.
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry.assertUniqueMethodMapping(AbstractHandlerMethodMapping.java:576) ~[spring-webmvc-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry.register(AbstractHandlerMethodMapping.java:540) ~[spring-webmvc-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.registerHandlerMethod(AbstractHandlerMethodMapping.java:264) ~[spring-webmvc-4.3.14.RELEASE.jar:4.3.14.RELEASE]
I also tried to remove "/customPost" mapping from controller and change mapping in metod to "/users". But for this case, I have this exception:
java.lang.NullPointerException: null
at org.springframework.data.rest.webmvc.config.RootResourceInformationHandlerMethodArgumentResolver.resolveArgument(RootResourceInformationHandlerMethodArgumentResolver.java:86) ~[spring-data-rest-webmvc-2.6.10.RELEASE.jar:na]
at org.springframework.data.rest.webmvc.config.PersistentEntityResourceHandlerMethodArgumentResolver.resolveArgument(PersistentEntityResourceHandlerMethodArgumentResolver.java:113) ~[spring-data-rest-webmvc-2.6.10.RELEASE.jar:na]
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121) ~[spring-web-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:158) ~[spring-web-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128) ~[spring-web-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) ~[spring-webmvc-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) ~[spring-webmvc-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) ~[spring-webmvc-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) ~[spring-webmvc-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) ~[tomcat-embed-core-8.5.27.jar:8.5.27]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.27.jar:8.5.27]
The question is: how can I have needed logic without adding "/customPost" mapping?
Spring Data REST emits its own events when working with entities:
BeforeCreateEvent
AfterCreateEvent
BeforeSaveEvent
AfterSaveEvent
BeforeLinkSaveEvent
AfterLinkSaveEvent
BeforeDeleteEvent
AfterDeleteEvent
You can listen to these events to add your additional business logic. For example, to perform something after the SDR creates a new User (with POST method) or saves (updates) the existent User (with PUT/PATCH methods), you can use such a handler:
#Component
#RepositoryEventHandler
public class UserEventHandler {
private final UserServie userServie;
public UserEventHandler(UserServie userServie) {
this.userServie = userServie;
}
#HandleAfterCreate
public void handleAfterCreateUser(User user) {
userService.afterCreate(user)
}
#HandleAfterSave
public void handleAfterSaveUser(User user) {
userService.afterSave(user)
}
}
P.S. If I'm not mistaken, SDR emits these events outside the current transactions, only before it is started or after it is committed. You need to take this into account when implementing your business logic...
NOTE: This may sound a duplicate but I have everything working from other threads
I am implementing my own dao classes with spring and I am not able to configure spring with hibernate properly or maybe something else is at fault.
I am using java based configuration but still getting error. Please have a look
Hibernate configuration:
#Configuration
#ComponentScan("com.caveatemptor")
#EnableJpaRepositories
#EnableTransactionManagement
public class SpringDataJPAConfiguration {
private Logger LOG = LoggerFactory.getLogger(SpringDataJPAConfiguration.class);
// #Bean(destroyMethod = "close")
// public BasicDataSource dataSource() {
// BasicDataSource basicDataSource = new BasicDataSource();
// basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
// basicDataSource.setUrl("jdbc:mysql://localhost/ce");
// basicDataSource.setUsername("root");
// basicDataSource.setPassword("root");
// basicDataSource.setInitialSize(1);
// basicDataSource.setMaxIdle(5);
// basicDataSource.setMaxOpenPreparedStatements(10);
// LOG.debug("+++++++++++++Datasource Configured");
// return basicDataSource;
// }
#Bean
public DriverManagerDataSource dataSource() {
DriverManagerDataSource basicDatasource = new DriverManagerDataSource();
basicDatasource.setDriverClassName("com.mysql.jdbc.Driver");
basicDatasource.setUrl("jdbc:mysql://localhost/ce");
basicDatasource.setUsername("root");
basicDatasource.setPassword("root");
LOG.debug("+++++++++++++Datasource Configured");
return basicDatasource;
}
// #Bean
// public LocalContainerEntityManagerFactoryBean entityManager() {
// LocalContainerEntityManagerFactoryBean bean = new
// LocalContainerEntityManagerFactoryBean();
// bean.setDataSource(this.dataSource());
// bean.setLoadTimeWeaver(this.instrumentationLoadTimeWeaver());
// bean.setJpaProperties(this.jpaProperties());
// bean.setJpaVendorAdapter(this.vendorAdapter());
// bean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
// bean.setPackagesToScan("com.caveatemptor.core");
// bean.setPersistenceUnitName("jpwh");
// LOG.info("==================[Entity Manage Configured]==================");
// return bean;
// }
#Bean
public HibernateJpaVendorAdapter vendorAdapter() {
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setShowSql(true);
adapter.setGenerateDdl(true);
LOG.info("==================[Hibernate Jpa Vendor Configured]==================");
return adapter;
}
#Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setDataSource(this.dataSource());
jpaTransactionManager.setJpaProperties(this.jpaProperties());
// jpaTransactionManager.setEntityManagerFactory(this.entityManager().getObject());
return jpaTransactionManager;
}
#Bean
public InstrumentationLoadTimeWeaver instrumentationLoadTimeWeaver() {
return new InstrumentationLoadTimeWeaver();
}
public Properties jpaProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "create");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
properties.setProperty("hibernate.show_sql", "true");
properties.setProperty("hibernate.format_sql", "true");
properties.setProperty("hibernate.ejb.naming_strategy", "org.hibernate.cfg.DefaultNamingStrategy");
properties.setProperty("hibernate.order_by.default_null_ordering", "first");
LOG.info("==================[JPA Properties Configured]==================");
return properties;
}
#Bean
public SessionFactory sessionFactory() {
LocalSessionFactoryBuilder bean = new LocalSessionFactoryBuilder(this.dataSource());
bean.setProperties(this.jpaProperties());
bean.addPackage("com.ceveatemptor");
LOG.info("Session Factory Configured+++++++++++++++++++");
return bean.buildSessionFactory();
}
}
This is a multimodule project using maven and therefore it is configured in web module as:
public class DispatcherServletInitConfiguration extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { SpringDataJPAConfiguration.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebServletInitConfiguration.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Generic DAO Class:
public abstract class GenericDAOImpl<T, ID extends Serializable> implements GenericDAO<T, ID> {
#PersistenceContext
protected EntityManager em;
protected final Class<T> entityClass;
public GenericDAOImpl(Class<T> entityClass) {
this.entityClass = entityClass;
}
#Override
public T makePersistent(T entity) {
return em.merge(entity);
}
}
Since Most of threads mentioned that I need a #Transactional and here is the implementation
#Repository
#Transactional
#javax.transaction.Transactional
public class ItemDAOImpl extends GenericDAOImpl<Item, Long> implements ItemDAO {
public ItemDAOImpl() {
super(Item.class);
}
}
The Stacktrace:
Sep 02, 2017 11:30:22 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/portal] threw exception [Request processing failed; nested exception is javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'merge' call] with root cause
javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'merge' call
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:282)
at com.sun.proxy.$Proxy77.merge(Unknown Source)
at com.caveatemptor.core.dao.GenericDAOImpl.makePersistent(GenericDAOImpl.java:53)
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 org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy79.makePersistent(Unknown Source)
at com.caveatemptor.web.controllers.ItemController.saveItem(ItemController.java:38)
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 org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
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:52)
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:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
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)
This may be a typo or some major configuration error, I am not getting it.
Any Insight will be helpful.
EDIT 1: If you need any other information, Please let me know.
EDIT 2 I am open to all kind of suggestions even If it is to change entire configuration for hibernate/jpa module. But only Java/annotation based configuration
EDIT 3 I Solved it by migrating server from tomcat to wildfly and configured JNDI data source and now it is working fine.
TL;DR:
Service method annotated with #Transactional(propagation = Propagation.NOT_SUPPORTED)
Hibernate 5.0.4.Final: everything works as expected (method is executed without transaction)
Hibernate 5.2.5.Final: javax.persistence.TransactionRequiredException: no transaction is in progress is thrown
as a testcase for this issue I created a simple maven web app and the only change made in code (copy-paste from old working project) was Hibernate version bump in pom.xml
Question:
What is the proper way to execute service methods without transaction nowadays?
Code snippets (Spring used as a main framework):
DAO:
#Repository
public class UrlDaoImpl implements UrlDao {
#Autowired
private SessionFactory sessionFactory;
#Override
public List<Url> getAllUrls() {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("from Url");
return query.list();
}
}
Service:
#Service
public class UrlServiceImpl implements UrlService {
#Autowired
private UrlDao urlDao;
#Override
#Transactional // THIS WORKS IN NEW HIBERNATE
public List<Url> getAllUrls() {
return urlDao.getAllUrls();
}
#Override
#Transactional(propagation = Propagation.NOT_SUPPORTED) // THIS USED TO WORK BUT NOW THROWS EXCEPTION
public List<Url> getAllUrlsNoTxn() {
return urlDao.getAllUrls();
}
}
Controller:
#Controller
public class HomeController {
#Autowired
private UrlService urlService;
#RequestMapping(value = "/", method = RequestMethod.GET, produces = "text/plain")
public String entryPoint() {
urlService.getAllUrls();
System.out.println("--------------------- ok");
return "ok";
}
#RequestMapping(value = "/no-txn", method = RequestMethod.GET, produces = "text/plain")
public String entryPointNoTxn() {
// EXCEPTION WILL BE THROWN BELOW
urlService.getAllUrlsNoTxn();
System.out.println("--------------------- ok no txn");
return "ok no txn";
}
}
Stacktrace for the exception in new Hibernate:
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.persistence.TransactionRequiredException: no transaction is in progress
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
root cause
javax.persistence.TransactionRequiredException: no transaction is in progress
org.hibernate.internal.SessionImpl.checkTransactionNeeded(SessionImpl.java:3439)
org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1410)
org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1406)
org.springframework.orm.hibernate5.SessionFactoryUtils.flush(SessionFactoryUtils.java:144)
org.springframework.orm.hibernate5.SpringSessionSynchronization.beforeCommit(SpringSessionSynchronization.java:95)
org.springframework.transaction.support.TransactionSynchronizationUtils.triggerBeforeCommit(TransactionSynchronizationUtils.java:95)
org.springframework.transaction.support.AbstractPlatformTransactionManager.triggerBeforeCommit(AbstractPlatformTransactionManager.java:932)
org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:744)
org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730)
org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:504)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:292)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
com.sun.proxy.$Proxy32.getAllUrlsNT(Unknown Source)
com.example.web.controller.HomeController.entryPointNoTxn(HomeController.java:31)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:220)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
Ok, after few hours of trying different configurations (before posting this question to SO), I finally found the solution.
For new Hibernate versions there is another required parameter that must be declared on #Transactional if you want to execute a method without a transaction: readOnly = true. So the working example of the Service part is:
#Service
public class UrlServiceImpl implements UrlService {
#Autowired
private UrlDao urlDao;
#Override
#Transactional
public List<Url> getAllUrls() {
return urlDao.getAllUrls();
}
#Override
#Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED) // ADDED READONLY TO WORK IN NEW HIBERNATE VERSIONS
public List<Url> getAllUrlsNoTxn() {
return urlDao.getAllUrls();
}
}
I also confirmed that this works on debug by calling ((org.hibernate.engine.transaction.internal.TransactionImpl) session.getTransaction()).isActive(); which returns true for the first Service method (with transaction) and false for the second Service method (with Propagation.NOT_SUPPORTED).