Spring-MVC does not call repository method - spring

I am fairly new, and trying to make a query on my local database but the code throws a NullPointerException exception.
It is weird as it looks like it never calls the selected method of repository called findNamesByCat(String cat). It does not show the output of System.err.println("in repository"); that is located in this method.
Just after following line I called a method of another service and that works!!
List<Name> Names = myService.findNamesByCat(cat);
Error
Mar 18, 2015 1:29:07 PM
org.apache.catalina.core.StandardWrapperValve invoke
... threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.myproject.web.MyController.showCategoryNames(MyController.java:41)
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:483)
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:777)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
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:620)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
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:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
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)
Code
#Controller
public class myController {
#Autowired
private MyService myService;
#RequestMapping(value = "/{cat}", method = RequestMethod.GET)
public String showCategoryNames(#PathVariable String cat, Model model) {
System.err.println("in web"); //shows this
List<Name> Names = myService.findNamesByCat(cat);
System.err.println(Names.size()); //this is line 41
model.addAttribute("Names", Names);
model.addAttribute("cat", cat);
return "cat";
}
#Service
public class MyServiceImpl implements MyService {
#Autowired
private NameRepository nameRepository;
#Override
#Transactional(readOnly = true)
public List<Name> findListOfNamesByCat(String cat) {
System.err.println("in service"); //does not show this
return nameRepository.findNamesByCat(cat);
}
}
#Repository
public class NameRepositoryImp implements NameRepository {
#Autowired
SessionFactory sessionFactory;
#Override
public List<Name> findNamesByCat(String cat){
System.err.println("in repository"); //does not show this
try {
Criteria crit = sessionFactory.getCurrentSession().createCriteria(
Name.class);
crit.add(Restrictions.eq("category", cat));
return crit.list();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Servlet
<context:annotation-config />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<context:component-scan base-package="com.myproject" />
UPDATE
I made following changes as well but it does not work yet.
#Controller
public class myController {
#Autowired
#Qualifier("repositoryService")
private MyService myService;
#Service(value = "repositoryService")
public class MyServiceImpl implements MyService {
#Autowired
#Qualifier("repositoryMain")
private NameRepository nameRepository;
#Repository(value = "repositoryMain")
public class NameRepositoryImpl implements NameRepository {
#Autowired
SessionFactory sessionFactory;

You defined #PathVariable String cat, but didn't mark it correctly in #RequestMapping, add {} for PathVariable "cat", like this:
#RequestMapping(value = "/{cat}", method = RequestMethod.GET)

The issue was that, for some reasons the body of the methods that I was calling were empty and the correct bodies where replaced by body of other methods. After replacing the bodies and cleaning the project it started working. Thank you for your attempt to help and apologies for the confusion.

Related

Spring #Transactional calling abstract superclass method throws org.hibernate.HibernateException

I have read over 20 questions on stackoverflow related to this, but none of them worked.
Basically I have a service abstract superclass with 3 methods. Persist is like a template method, whereas save and update are overriden only when needed.
public abstract class BaseService<E> implements ServiceImpl{
protected E save(E object, Class<E> returnedClass){//save object}
protected E update(E object){//update object}
public boolean persist(E object) {
//validation rules
if(shouldSave) {
save(object);
}else {
update(object);
}
}
}
Then I have this subclass
#Service
#Transactional
public CompanyService extends BaseService<Company> {
#Autowired
private CompanyRepository repository;
public void testSaving(Company company) {
repository.save(company);
}
#Override //from service impl
public CommpanyRepositoy getRepository() {
return repository;
}
}
and this is my entry point
#RestController
#RequestMapping("/company")
public CompanyRestController {
#Autowired
private CompanyService service;
#RequestMapping(value = "/save", method = RequestMethod.POST)
public boolean save(#RequestBody Company company) {
return service.persist(company);
}
}
Now, the thing is, if I call for the testSaving method, everything goes right. BUT, when I call the persist method, it always give the error mentioned. I have tried lot's of things, like adding #Transactional to the BaseService superclass and even adding it to my repository doesn't work. Please, I need to fix this, its driving me crazy. Any advice?
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:134)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1014)
at br.com.jeffersontpadua.spring.generic.BaseRepository.getSession(BaseRepository.java:56)
at br.com.jeffersontpadua.spring.generic.BaseRepository.save(BaseRepository.java:27)
at br.com.jeffersontpadua.spring.service.BaseService.save(BaseService.java:45)
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.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:723)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
at br.com.jeffersontpadua.spring.service.CompanyService$$EnhancerBySpringCGLIB$$a3329725.save(<generated>)
at br.com.jeffersontpadua.spring.service.BaseService.persist(BaseService.java:34)
at br.com.jeffersontpadua.spring.rest.CompanyRestController.save(CompanyRestController.java:41)
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:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
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:963)
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.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 br.com.jeffersontpadua.spring.filter.RequestFilter.doFilter(RequestFilter.java:34)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
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:436)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
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 is intentional, see SPR-7824.
You basically need to place the #Transactional annotation on the super-class rather than the subclass and that will cause all subclass methods to be transactional as well as those on the superclass.
If you cannot do that, override the methods in the subclass and delegate to the superclass.
I finaly found a way to make this happen, so, for anyone who is still struggling to solve this, the trick is to add #Transactional(propagation = Propagation.REQUIRES_NEW) to your superclass xD

Spring EJB remote

I need help to call EJB Remote (EJB project DAO) from dynamic web project (spring). i use a WildFly 8 server
IN EJB project
PersonDaoRemote
#Remote
public interface PersonDaoRemote {
public void addPerson(Person p);
}
PersonDaoImpl
#Stateless #RemoteBinding(jndiBinding="PersonDao")
public class PersonDaoImpl implements PersonDaoLocal,PersonDaoRemote{
#PersistenceContext(unitName="UniQPersistence") private EntityManager em;
#Override public void addPerson(Person p) { em.persist(p);
}
In Web project
Application-context
<bean id="myComponent"
class="org.springframework.ejb.access.LocalStatelessSessionProxyFactoryBean">
<property name="jndiName" value="ejb/PersonDao"/>
<property name="businessInterface" value="com.mycom.MyComponent"/>
</bean>
<bean id="SecurityController" class="com.uniqweb.controller.SecurityController">
<property name="myComponent" ref="myComponent"/>
</bean>
Mycomponent interface
public interface MyComponent {
public void addPerson(Person p);
}
controller
#Controller
public class SecurityController {
private MyComponent myComponent;
public void setMyComponent(MyComponent myComponent) {
this.myComponent = myComponent;
}
#RequestMapping(value = "/addtest",params="submit", method = RequestMethod.POST)
public String test(ModelMap model,#RequestParam(value = "error", required = false) String error,
#RequestParam("username") String logout) {
System.out.println(logout);
Person p=new Person();
p.setId(1);
myComponent.addPerson(p); line66
return "login";
}
}
console
Caused by: java.lang.NullPointerException
at com.uniqweb.controller.SecurityController.login3(SecurityController.java:66) [classes:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.8.0_45]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) [rt.jar:1.8.0_45]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.8.0_45]
at java.lang.reflect.Method.invoke(Method.java:497) [rt.jar:1.8.0_45]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) [spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776) [spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705) [spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) [spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) [spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) [spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966) [spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
... 30 more
Regrding to the following link:
https://docs.jboss.org/author/display/WFLY8/JNDI+Reference?_sscc=t
Your JNDI name should be like:
ejb:myapp/myejbjar/MyEjbName!com.test.MyRemoteInterface

Spring mvc Autowiring fails

TrackerRepoImpl.java
#Repository("TrackerRepo")
public class TrackerRepoImpl implements TrackerRepo { //repository interface implementation
#Autowired
private SessionFactory sessionFactory;
#Override
public Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
#Override
public void save(Event event) {
getCurrentSession().save(event);
}
}
TrackerServiceImpl.java
#Service("TrackerService")
public class TrackerServiceImpl implements TrackerService { //service interface implementation
#Autowired
private TrackerRepo repo;
#Override
#Transactional
public void save(Event event) {
repo.save(event);
}
}
RootConfig.java
#Configuration
#EnableTransactionManagement
#ComponentScan(basePackages={"com.tracker"},excludeFilters={#Filter(type=FilterType.ANNOTATION,value=EnableWebMvc.class)})
public class RootConfig {
#Bean //session factory bean
public LocalSessionFactoryBean factoryBean(DataSource dataSource)
{
LocalSessionFactoryBean bean=new LocalSessionFactoryBean();
bean.setDataSource(dataSource);
Properties properties=new Properties();
properties.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
bean.setHibernateProperties(properties);
bean.setPackagesToScan("com.tracker");
return bean;
}
#Bean //datbase details
public DataSource dataSource()
{
DriverManagerDataSource dataSource=new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost/tracker");
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory);
return txManager;
}
#Bean
public BeanPostProcessor persistenceTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
}
errors:
Jun 29, 2015 1:33:10 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/tracker] threw exception [Request processing failed; nested exception is org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread] with root cause
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:134)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1014)
at com.tracker.web.dao.TrackerRepoImpl.getCurrentSession(TrackerRepoImpl.java:22)
at com.tracker.web.dao.TrackerRepoImpl.save(TrackerRepoImpl.java:27)
at com.tracker.web.service.TrackerServiceImpl.save(TrackerServiceImpl.java:22)
at com.tracker.web.controllers.MainController.submitPlannedPage(MainController.java:77)
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: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.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
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:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)

Exception Handler not working on a spring boot app

I have created a spring boot application defined like this :
#Configuration
#EnableAutoConfiguration
#ComponentScan
public class Application {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
}
I have also created a RestController for this application with a request mapping
I have then created a specific exception :
public class MyOwnException extends Exception {
public MyOwnException (String message) {
super(message);
}
}
And then defined a class for globalling handling all of my exception
#ControllerAdvice(annotations = RestController.class)
public class MyOwnExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler(MyOwnException.class)
#ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "File or folder is unwrittable")
public #ResponseBody
ExceptionJSONInfo handleMyOwnException(
HttpServletRequest request, Exception ex) {
ExceptionJSONInfo response = new ExceptionJSONInfo();
response.setUrl(request.getRequestURL().toString());
response.setMessage(ex.getMessage());
return response;
}
Here is my controller code :
#RestController
#RequestMapping(value="/you/should")
public class MyOwnController {
#RequestMapping(value="/try/this", method=RequestMethod.GET, produces = "application/pdf")
public FileSystemResource processSomething(HttpServletResponse response) throws MyOwnException {
FileSystemResource afileRessource = new FileSystemResource();
if (true)
throw new MyOwnException("File not readable: " + finalFileWithEncryptedName);
return afileRessource
}
}
Unfortunately the handler is never been called instead I get following stacktrace :
2015-02-26 17:37:34.914 ERROR 6512 --- [nio-9050-exec-5] .a.c.c.C.[.[.[.p.k.p.[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [/myOwnContext] threw exception [Request processing failed; nested exception is MyOwnException: My onw exception message] with root cause MyOwnException: MyOwnExceptionMessage
at MyOwnController.myOwnCOntrollerMethod(MyOwnController.java:164)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:110)
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.EndpointWebMvcAutoConfiguration$ApplicationContextHeaderFilter.doFilterInternal(EndpointWebMvcAutoConfiguration.java:280)
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.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:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration$MetricsFilter.doFilterInternal(MetricFilterAutoConfiguration.java:90)
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.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:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1736)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1695)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:722)
Can anybody please help me find why my ControllerAdvise is never being called?
Try adding #EnableWebMvc annotation to your configuration class and make sure your controller advice is being scanned.
If anyone has the same problem and "adding #EnableWebMvc annotation to your configuration class" didn't solve the problem, the solution can be in correctly naming your package. If your package is wrongly named it won't be scanned and therefore exception handler will never be triggered.
More about packages here: https://www.baeldung.com/java-packages
Basically your package and directory structure should be the same...
#EnableAspectJAutoProxy
works for me,
#EnableWebMvc does not.
Spring boot 2.0

"No CurrentSessionContext configured" when application try perform a query in the database

In my current spring-boot project, when I try do a query in the database, through this method from my dao class (it's the unique I used in this step of the development):
public class Dao<E extends Model> {
#Autowired
private SessionFactory sessionFactory;
...
#Transactional
public E findByField(String field, String value) {
return (E) sessionFactory.getCurrentSession().createQuery("from "+clazz.getSimpleName()+" where "+field+" = :data").setParameter("data", value).uniqueResult();
}
}
I am getting this error:
org.springframework.security.authentication.InternalAuthenticationServiceException: No CurrentSessionContext configured!
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:110)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:132)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:177)
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:211)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
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:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1736)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1695)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.HibernateException: No CurrentSessionContext configured!
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1012)
at org.store.generic.persistence.Dao.findByField(Dao.java:47)
at org.store.generic.persistence.Dao$$FastClassBySpringCGLIB$$ac46d9f5.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:708)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644)
at org.store.model.usuario.UsuarioDao$$EnhancerBySpringCGLIB$$426a101d.findByField(<generated>)
at org.store.security.AcessoService.loadUserByUsername(AcessoService.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy64.loadUserByUsername(Unknown Source)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:102)
... 35 common frames omitted
this method is called from this service class:
#Component
public class AcessoService implements UserDetailsService {
#Autowired
private UsuarioDao usuario;
#Override
#Transactional
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Usuario account = (Usuario) usuario.findByField("login", username);
if(account==null)
throw new UsernameNotFoundException("No such user: " + username);
else if (account.getRole().isEmpty())
throw new UsernameNotFoundException("User " + username + " has no authorities");
List<Permission> lista = new ArrayList<Permission>();
int max = account.getRole().size();
for(int i=0; i<max; i++) {
int max2 = account.getRole().get(i).getPermission().size();
for(int j=0; j<max2; j++)
lista.add(account.getRole().get(i).getPermission().get(j));
}
boolean accountIsEnabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
return new User(account.getLogin(), account.getSenha(), accountIsEnabled, accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities(lista));
}
}
This is my application.properties file:
# jdbc.X
spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/mystore?charSet=LATIN1
spring.datasource.username=klebermo
spring.datasource.password=123
# hibernate.X
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=create-drop
and I have this configuration class to set the sessionFactory bean:
#Configuration
public class HibernateConfig {
#Bean
public HibernateJpaSessionFactoryBean sessionFactory(EntityManagerFactory emf) {
HibernateJpaSessionFactoryBean factory = new HibernateJpaSessionFactoryBean();
factory.setEntityManagerFactory(emf);
return factory;
}
}
anyone can see what I am missing here?
Ok, then after more searches I finally find a solution for this problem. I solvw this adding this method to my Dao class:
public Session getSessionFactory() {
try {
return sessionFactory.getCurrentSession();
} catch (Exception e) {
return sessionFactory.openSession();
}
}
and changing the call:
sessionFactory.getCurrentSession()
in the methods for this:
getSessionFactory()
UPDATE
another solution I found it's use
#Autowired
private EntityManagerFactory factory;
and
public EntityManager getEntityManager() {
return factory.createEntityManager();
}
in my dao class, and in each one of the methods, use something like this:
#Transactional
public void insert(E object) {
getEntityManager().persist(object);
}

Resources