Submitted data aren't stored in the database - spring

In my current spring-boot project, I have a page built with Thymeleaf, where I have a form like that:
<form class="form" role="form" method="post" th:action="#{/__${command.getClass().getSimpleName()}__/cadastra}">
...
</form>
which is rendered to this:
<form class="form" role="form" method="post" action="/Usuario/cadastra">
...
</form>
the problem happens when I try submit the form: the following error is triggered:
error: "Internal Server Error"
exception: "org.thymeleaf.exceptions.TemplateInputException"
message: "Error resolving template "Usuario/cadastra", template might not exist or might not be accessible by any of the configured Template Resolvers"
path: "/Usuario/cadastra"
status: 500
timestamp: 1417225370311
in the console, this is displayed:
2014-11-28 22:42:50.303 ERROR 32286 --- [nio-8080-exec-4] org.thymeleaf.TemplateEngine : [THYMELEAF][http-nio-8080-exec-4] Exception processing template "Usuario/cadastra": Error resolving template "Usuario/cadastra", template might not exist or might not be accessible by any of the configured Template Resolvers
2014-11-28 22:42:50.305 ERROR 32286 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: Error resolving template "Usuario/cadastra", template might not exist or might not be accessible by any of the configured Template Resolvers] with root cause
org.thymeleaf.exceptions.TemplateInputException: Error resolving template "Usuario/cadastra", template might not exist or might not be accessible by any of the configured Template Resolvers
at org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:245)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1104)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1060)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1011)
at org.thymeleaf.spring4.view.ThymeleafView.renderFragment(ThymeleafView.java:335)
at org.thymeleaf.spring4.view.ThymeleafView.render(ThymeleafView.java:190)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1221)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1005)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:952)
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.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
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.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.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:146)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
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)
anyone can see what's the problem here?
PS.: the handler for the submitted data is this controller method:
#RequestMapping(value = "cadastra", method=RequestMethod.POST)
public void cadastra(#ModelAttribute("object") E object, BindingResult result) {
serv.cadastra(object);
}
UPDATE
I solve the error above adding the annotation #ResponseBody to the method in controller, but now I have another issue: despite no more errors are being displayed, the submitted data isn't saved in the database (same occurs if I try update or remove the object).
The methods in controller which handle this operations are:
#RequestMapping(value = "cadastra", method=RequestMethod.POST)
#ResponseBody
public void cadastra(#ModelAttribute("object") E object, BindingResult result) {
serv.cadastra(object);
}
#RequestMapping(value = "altera", method=RequestMethod.POST)
#ResponseBody
public void altera(#ModelAttribute("object") E object, BindingResult result) {
serv.altera(object);
}
#RequestMapping(value = "remove", method=RequestMethod.POST)
#ResponseBody
public void remove(#ModelAttribute("object") E object, BindingResult result) {
serv.remove(object);
}
In my service class:
#PreAuthorize("hasPermission(#user, 'cadastra_'+#this.this.name)")
#Transactional
public void cadastra(E object) {
dao.insert(object);
}
#PreAuthorize("hasPermission(#user, 'altera_'+#this.this.name)")
#Transactional
public void altera(E object) {
dao.update(object);
}
#PreAuthorize("hasPermission(#user, 'remove_'+#this.this.name)")
#Transactional
public void remove(E object) {
dao.delete(object);
}
and in my Dao class:
#Transactional
public void insert(E object) {
getEntityManager().persist(object);
}
#Transactional
public void update(E object) {
getEntityManager().merge(object);
}
#Transactional
public void delete(E object) {
getEntityManager().remove(object);
}
what's wrong now?

The problem is that the template is missing. If your template is in a different location than the default you need to to return a String from your #RequestMapping.

I managed to fix this pŕoblem using this structure to the methods of my dao class:
public void insert(E object) {
EntityManager entityManager = getEntityManager();
entityManager.getTransaction().begin();
entityManager.persist(object);
entityManager.getTransaction().commit();
}

Related

Spring Mail Tutorial Help, receiving null pointer exception

I'm following the Spring Mail documentation steps 27.1 - 27.2.2 in the Spring Mail tutorial. My goal is to add email functionality to an already created Spring-MVC project. I'm running into a java.lang.NullPointerException, when creating a new SimpleMailMessage Object (more details in full stacktrace below).
SimpleOrderManager
I tried to stay as close as possible to the tutorial
public class SimpleOrderManager implements OrderManager {
private MailSender mailSender;
private SimpleMailMessage templateMessage;
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
public void setTemplateMessage(SimpleMailMessage templateMessage) {
this.templateMessage = templateMessage;
}
public void placeOrder(User user) {
SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
msg.setTo(user.getEmail());
msg.setText("Dear you");
try{
this.mailSender.send(msg);
}
catch (MailException ex) {
System.err.println(ex.getMessage());
}
}
I found a related case that remains unresolved.
I added Javax Mail dependencies to Maven.
Also, I've created a applicationContext-mail.xml configuration file which I made sure to be referenced by the web.xml file
applicationContext-mail.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="mail.location.company.edu"/>
</bean>
<!-- this is a template message that we can pre-load with default state -->
<bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="myEmail#mail.org"/>
<property name="subject" value="Your order"/>
</bean>
<bean id="reminderManager" class="edu.company.peerreview.mvc.utility.SimpleOrderManager">
<property name="mailSender" ref="mailSender"/>
<property name="templateMessage" ref="templateMessage"/>
</bean>
</beans>
stacktrace
SEVERE: Servlet.service() for servlet [peerReview] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at edu.example.department.peerreview.mvc.utility.SimpleOrderManager.placeOrder(SimpleOrderManager.java:61)
at edu.example.department.peerreview.mvc.HomeController.home(HomeController.java:25)
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:212)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:629)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:590)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:874)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:779)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
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.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:312)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:116)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:324)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:324)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:101)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:324)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:324)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:324)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:324)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:324)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:182)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:324)
at edu.example.department.peerreview.security.RequestParameterAuthenticationFilter.doFilter(RequestParameterAuthenticationFilter.java:58)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:324)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:324)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:324)
at org.springframework.security.web.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:125)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:324)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:174)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:196)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
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)
The error comes from the Assert statement
Spring Source Code for SimpleMailMessage
public SimpleMailMessage(SimpleMailMessage original) {
Assert.notNull(original, "The 'original' message argument cannot be null");
this.from = original.getFrom();
this.replyTo = original.getReplyTo();
if (original.getTo() != null) {
this.to = copy(original.getTo());
}
if (original.getCc() != null) {
this.cc = copy(original.getCc());
}
if (original.getBcc() != null) {
this.bcc = copy(original.getBcc());
}
this.sentDate = original.getSentDate();
this.subject = original.getSubject();
this.text = original.getText();
}
To my knowledge, I've completed all the instructions from the tutorial. In the simpleOrderManager, I tried using an empty constructor when creating a new instance SimpleMailMessage msg = new SimpleMailMessage() but that gives me a null pointer expection error when executingthis.mailSender.send(msg);`
Edit: add home action from Home controller
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Model model) {
// Redirect to the user's dashboard
SimpleOrderManager qaFollowUp = new SimpleOrderManager();
User user = userDAO.findById(485);
qaFollowUp.placeOrder(user);
return "redirect:/users/" + getAuthenticatedUser().getId() + "/dashboard/" + UserHelper.getURLName(getAuthenticatedUser());
}
You have to let Spring inject the SimpleOrderManager bean. If you create it with new Spring won't be aware of it (it is not part of the application context) and won't autowire it's dependencies (the templateMessage in your case).

OAuth2 - Spring security: ClientCredentialsTokenEndpointFilter not working

I am implementing OAuth2 authentication and I totally don't understand why my CustomCredentialsTokenEndpointFilter does not work.
When I launch the application in debugging mode, neither of debug checkpoints is hit.
I need the filter to be overriden and change the implementation of authentication attempt.
Is there a mistake in my configuration?
Authentication Adapter:
#Configuration
#EnableWebSecurity
#ComponentScan("com.springapp.mvc")
#Order(3)
class OAuth2AuthenticationConfigurationAdapter extends WebSecurityConfigurerAdapter {
#Autowired
private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler;
#Autowired
#Qualifier("clientDetailsService")
private ClientDetailsService oauth2ClientDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.anonymous()
.disable();
http
.requestMatchers()
.antMatchers("/oauth/token")
.and()
.authorizeRequests()
.anyRequest()
.fullyAuthenticated();
http
.httpBasic()
.authenticationEntryPoint(oAuth2AuthenticationEntryPoint())
.and()
.addFilterBefore(clientCredentialsTokenEndpointFilter(), BasicAuthenticationFilter.class)
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.exceptionHandling()
.accessDeniedHandler(oAuth2AccessDeniedHandler);
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(clientDetailsUserDetailsService());
}
#Bean
ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter() {
final ClientCredentialsTokenEndpointFilter tokenEndpointFilter = new CustomClientCredentialsTokenEndpointFilter();
try {
tokenEndpointFilter.setAuthenticationManager(authenticationManagerBean());
tokenEndpointFilter.setAuthenticationEntryPoint(oAuth2AuthenticationEntryPoint());
tokenEndpointFilter.setAuthenticationFailureHandler(authenticationFailureHandler());
tokenEndpointFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler());
tokenEndpointFilter.setAllowOnlyPost(true);
return tokenEndpointFilter;
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
#Bean
OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler() {
return new OAuth2AccessDeniedHandler();
}
AuthenticationSuccessHandler authenticationSuccessHandler() {
return new OAuth2AuthenticationSuccessHandler();
}
AuthenticationFailureHandler authenticationFailureHandler() {
return new OAuth2AuthenticationFailureHandler();
}
UserDetailsService clientDetailsUserDetailsService() {
final ClientDetailsUserDetailsService service = new ClientDetailsUserDetailsService(oauth2ClientDetailsService);
return service;
}
#Bean
OAuth2AuthenticationEntryPoint oAuth2AuthenticationEntryPoint() {
final OAuth2AuthenticationEntryPoint entryPoint = new OAuth2AuthenticationEntryPoint();
entryPoint.setRealmName("oauth/client");
entryPoint.setTypeName("Basic");
return entryPoint;
}
static final class CustomClientCredentialsTokenEndpointFilter extends ClientCredentialsTokenEndpointFilter {
#Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
final Authentication authentication = super.attemptAuthentication(request, response);
return authentication;
}
}
static final class OAuth2AuthenticationFailureHandler implements AuthenticationFailureHandler {
#Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
String s = request.toString();
}
}
static final class OAuth2AuthenticationSuccessHandler implements AuthenticationSuccessHandler {
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
String s = request.toString();
}
}
}
Http request:
curl -X POST -H "Authorization: Basic **************************" -v -d "username=my.user&password=pass&client_id=my.user&cla-7c9d-426b-a942-cc166438f996&grant_type=password&scope=[read, write]" http://localhost:8080/oauth/token
Log after invoking request.
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is error="invalid_client", error_description="Given client ID does not match authenticated client"
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:943)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:833)
javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:807)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:201)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
</pre></p><p><b>root cause</b> <pre>error="invalid_client", error_description="Given client ID does not match authenticated client"
org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory.createTokenRequest(DefaultOAuth2RequestFactory.java:104)
org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.getAccessToken(TokenEndpoint.java:81)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:748)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:931)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:833)
javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:807)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:201)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
I know where the exception occurs and what causes it and in order to fix this I must provide custom filter.
Ok, the explanation can be found here. If you decide to use custom filter, you cannot use it with
/oauth/token
path.
However, I tried to implement custom token endpoint and I didn't succeed with path mapping. Someone did and here is the example.

org.springframework.expression.spel.SpelEvaluationException: EL1004E:(pos 15):Method call: Method getId() cannot be found on java.util.ArrayList type

I need help fixing this error, in the first place I want to get all commands then when I choose one I should get more detail about command chosen.
BaseEntity.java
#MappedSuperclass
public class BaseEntity implements Serializable {
#Id
#GeneratedValue
private Long id;
public Long getId() {
return id;
}
public void setId( Long id ) {
this.id = id;
}
}
Command.java
#Entity
#Table( name = "cmd" )
public class Command extends BaseEntity {
String private name;
//getter&setter
}
CommandDao.java
public Command loadById( Long id ) {
Assert.notNull( id );
Command cmd = null;
Query query = getEntityManger().createQuery( "select u from "
+ getPersistentClass().getSimpleName()
+ " u where u.id= :id" ).setParameter( "id", id );
try {
cmd = (Command) query.getSingleResult();
} catch ( NoResultException e ) {
}
return cmd;
}
#Override
#Transactional( readOnly = true )
public List<Command> listeCmd() {
Query query = getEntityManger().createQuery( "from " + getPersistentClass().getSimpleName() );
List<Command> cmd = (List) query.getResultList();
return cmd;
}
CommandServiceImpl.java
private CommandDao commandDao;
public List<Command> list() {
return commandDao.listeCmd();
}
public Command cmdPick( Long id ) {
List<Command> l = Command Dao.listeCmd();
Command cmd = null;
for ( int i = 0; i < l.size(); i++ ) {
if ( l.get( i ).getId() == id ) {
cmd = commandDao.loadById( id );
}
}
return cmd;
}
applicationContext.xml
<bean id="commandDao" class="xx.xx.xx.CommandDao" />
<!-- Services Declaration -->
<bean id="commandService" class="xx.xx.xx.CommandServiceImpl">
<property name="commandDao" ref="commandDao" /></property>
</bean>
flow.xml
<var name="command" class="xx.xx.xx.Command" />
<view-state id="shwo" view="show.xhtml" model="command">
<on-render>
<evaluate expression="commandService.liste()" result="viewScope.list"/>
</on-render>
<transition on="pick">
<evaluate expression="commandService.cmdPick(command.getId())"
result="flowScope.list" />
</transition>
</view-state>
Show.xhtml
<h:form>
<p:dataTable var="car" value="#{list}">
<p:column>
<h:outputText value="#{car.name}" />
<h:commandLink action="pick" value="#{car.id}"/>
</p:column>
</p:dataTable>
</h:form>
Error
12:57:22,883 DEBUG ActionExecutor:49 - Executing [EvaluateAction#1360f6d expression = commandService.commandService.cmdPick(command.getId()), resultExpression = flowScope.command]
12:57:22,883 DEBUG AnnotatedAction:142 - Putting action execution attributes map[[empty]]
12:57:22,884 DEBUG AnnotatedAction:149 - Clearing action execution attributes map[[empty]]
12:57:22,886 DEBUG FlowExecutionImpl:590 - Attempting to handle [org.springframework.webflow.execution.ActionExecutionException: Exception thrown executing [AnnotatedAction#127eb1c targetAction = [EvaluateAction#1360f6d expression = commandService.commandService.cmdPick(command.getId()), resultExpression = flowScope.command], attributes = map[[empty]]] in state 'show' of flow 'main' -- action execution attributes were 'map[[empty]]'] with root cause [org.springframework.expression.spel.SpelEvaluationException: EL1004E:(pos 15): Method call: Method getId() cannot be found on java.util.ArrayList type]
12:57:22,886 DEBUG FlowExecutionImpl:611 - Rethrowing unhandled flow execution exception
12:57:22,887 DEBUG SessionBindingConversationManager:99 - Unlocking conversation 1
mai 31, 2014 12:57:22 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [Spring MVC Dispatcher Servlet] in context with path [/Colocation] threw exception [Request processing failed; nested exception is org.springframework.webflow.execution.ActionExecutionException: Exception thrown executing [AnnotatedAction#127eb1c targetAction = [EvaluateAction#1360f6d expression = commandService.commandService.cmdPick(command.getId()), resultExpression = flowScope.command], attributes = map[[empty]]] in state 'show' of flow 'main' -- action execution attributes were 'map[[empty]]'] with root cause
org.springframework.expression.spel.SpelEvaluationException: EL1004E:(pos 15): Method call: Method getId() cannot be found on java.util.ArrayList type
at org.springframework.expression.spel.ast.MethodReference.findAccessorForMethod(MethodReference.java:182)
at org.springframework.expression.spel.ast.MethodReference.getValueInternal(MethodReference.java:106)
at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:57)
at org.springframework.expression.spel.ast.MethodReference.getValueInternal(MethodReference.java:65)
at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:57)
at org.springframework.expression.spel.ast.SpelNodeImpl.getTypedValue(SpelNodeImpl.java:102)
at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:97)
at org.springframework.binding.expression.spel.SpringELExpression.getValue(SpringELExpression.java:84)
at org.springframework.webflow.action.EvaluateAction.doExecute(EvaluateAction.java:75)
at org.springframework.webflow.action.AbstractAction.execute(AbstractAction.java:188)
at org.springframework.webflow.execution.AnnotatedAction.execute(AnnotatedAction.java:145)
at org.springframework.webflow.execution.ActionExecutor.execute(ActionExecutor.java:51)
at org.springframework.webflow.engine.support.ActionTransitionCriteria.test(ActionTransitionCriteria.java:82)
at org.springframework.webflow.engine.support.TransitionCriteriaChain.test(TransitionCriteriaChain.java:71)
at org.springframework.webflow.engine.Transition.canExecute(Transition.java:195)
at org.springframework.webflow.engine.Transition.execute(Transition.java:211)
at org.springframework.webflow.engine.impl.FlowExecutionImpl.execute(FlowExecutionImpl.java:393)
at org.springframework.webflow.engine.impl.RequestControlContextImpl.execute(RequestControlContextImpl.java:214)
at org.springframework.webflow.engine.TransitionableState.handleEvent(TransitionableState.java:119)
at org.springframework.webflow.engine.Flow.handleEvent(Flow.java:555)
at org.springframework.webflow.engine.impl.FlowExecutionImpl.handleEvent(FlowExecutionImpl.java:388)
at org.springframework.webflow.engine.impl.RequestControlContextImpl.handleEvent(RequestControlContextImpl.java:210)
at org.springframework.webflow.engine.ViewState.handleEvent(ViewState.java:232)
at org.springframework.webflow.engine.ViewState.resume(ViewState.java:196)
at org.springframework.webflow.engine.Flow.resume(Flow.java:545)
at org.springframework.webflow.engine.impl.FlowExecutionImpl.resume(FlowExecutionImpl.java:258)
at org.springframework.webflow.executor.FlowExecutorImpl.resumeExecution(FlowExecutorImpl.java:169)
at org.springframework.webflow.mvc.servlet.FlowHandlerAdapter.handle(FlowHandlerAdapter.java:183)
at org.springframework.faces.webflow.JsfFlowHandlerAdapter.handle(JsfFlowHandlerAdapter.java:48)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
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.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
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:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:744)
You are specifying model for form as command and viewscope variable also as command on render. Change this viewscope variable to commandList and make corresponding change in view as well. Then in commandLink write a JavaScript onclick function to capture the id selected by user and assign it a field in Command. Lets say this field defined as selectedId in model command. Pass this value to cmdPick method in evaluate expression.

Spring Data MongoDB + QueryDSL + DBRef = Exception

My Setup:
mongo-java-driver 2.11.3
spring-data-mongodb 1.4.0.M1
spring-data-commons 1.7.0.M1
querydsl-mongodb 3.3.0
spring 4.0.0.RELEASE
java 1.7
MongoDB v2.4.8
User.java:
#Document(collection="user")
public class User {
public User(String username) {
this.username = username;
}
#Id
private ObjectId id;
public ObjectId getId() { return id; }
#Indexed(unique=true)
private String username;
public String getUsername() { return username; }
/* more fields */
}
Profile.java:
#Document(collection="userProfile")
public class Profile {
public Profile(User user) {
this.user = user;
}
#Id
private ObjectId id;
public ObjectId getId() { return id; }
#DBRef #Indexed(unique=true)
private User user;
public User getUser() { return user; }
/* more fields */
}
UserRepository:
public interface UserRepository extends MongoRepository<User, ObjectId>, QueryDslPredicateExecutor<User> {}
ProfileRepository:
public interface ProfileRepository extends MongoRepository<Profile, ObjectId>, QueryDslPredicateExecutor<Profile> {
#Query("{ user.$id: ?0 }")
Profile findByUserId(ObjectId userId);
}
generated QUser:
#Generated("com.mysema.query.codegen.EntitySerializer")
public class QUser extends EntityPathBase<User> {
private static final long serialVersionUID = 2145065918L;
private static final PathInits INITS = PathInits.DIRECT2;
public static final QUser user = new QUser("user");
public final org.bson.types.QObjectId id;
public final StringPath username = createString("username");
/* more fields */
public QUser(String variable) {
this(User.class, forVariable(variable), INITS);
}
public QUser(Path<? extends User> path) {
this(path.getType(), path.getMetadata(), path.getMetadata().isRoot() ? INITS : PathInits.DEFAULT);
}
public QUser(PathMetadata<?> metadata) {
this(metadata, metadata.isRoot() ? INITS : PathInits.DEFAULT);
}
public QUser(PathMetadata<?> metadata, PathInits inits) {
this(User.class, metadata, inits);
}
public QUser(Class<? extends User> type, PathMetadata<?> metadata, PathInits inits) {
super(type, metadata, inits);
this.id = inits.isInitialized("id") ? new org.bson.types.QObjectId(forProperty("id")) : null;
}
}
generated QProfile:
#Generated("com.mysema.query.codegen.EntitySerializer")
public class QProfile extends EntityPathBase<Profile> {
private static final long serialVersionUID = -1321832234L;
private static final PathInits INITS = PathInits.DIRECT2;
public static final QProfile profile = new QProfile("profile");
public final org.bson.types.QObjectId id;
public final QUser user;
/* more fields */
public QProfile(String variable) {
this(Profile.class, forVariable(variable), INITS);
}
public QProfile(Path<? extends Profile> path) {
this(path.getType(), path.getMetadata(), path.getMetadata().isRoot() ? INITS : PathInits.DEFAULT);
}
public QProfile(PathMetadata<?> metadata) {
this(metadata, metadata.isRoot() ? INITS : PathInits.DEFAULT);
}
public QProfile(PathMetadata<?> metadata, PathInits inits) {
this(Profile.class, metadata, inits);
}
public QProfile(Class<? extends Profile> type, PathMetadata<?> metadata, PathInits inits) {
super(type, metadata, inits);
this.id = inits.isInitialized("id") ? new org.bson.types.QObjectId(forProperty("id")) : null;
this.user = inits.isInitialized("user") ? new QUser(forProperty("user"), inits.get("user")) : null;
}
}
What works:
profileRepository.findByUserId(someUser.getId());
userRepository.findOne(QUser.user.username.eq("someUsername"));
What doesn't work:
profileRepository.findOne(QProfile.profile.user.eq(someUser));
profileRepository.findOne(QProfile.profile.user.id(someUser.getId()));
Misc:
This question ( QueryDsl MongoDb Relation ) looked pretty similar to mine, and in the comments some ticket ( https://github.com/mysema/querydsl/issues/583 ) was created. But this ticket refers to missing support for #Reference annotation, which's got nothing to do with the question itself?!
Should this work? Am I doing something wrong? Or am I using the wrong versions?
TRACE LOG:
URL: PATCH http://localhost:8080/users/52d6eb4d03640c2f5a5ee726
Called Java Code (in UserServiceImpl):
myproject.domain.security.User u = userRepo.findOne(id);
myproject.domain.security.Profile p = profileRepo.findOne(QProfile.profile.user.eq(u));
System.out.println(p.firstName);
And here's the Log:
/* some Spring Security stuff omitted */
2014-01-16 23:47:13,911 DEBUG o.s.s.w.access.intercept.FilterSecurityInterceptor: 215 - Authorization successful
2014-01-16 23:47:13,911 DEBUG o.s.s.w.access.intercept.FilterSecurityInterceptor: 227 - RunAsManager did not change Authentication object
2014-01-16 23:47:13,911 DEBUG org.springframework.security.web.FilterChainProxy: 323 - /users/52d6eb4d03640c2f5a5ee726 reached end of additional filter chain; proceeding with original chain
2014-01-16 23:47:13,917 TRACE org.springframework.web.servlet.DispatcherServlet:1013 - Bound request context to thread: SecurityContextHolderAwareRequestWrapper[ org.springframework.security.web.context.HttpSessionSecurityContextRepository$Servlet3SaveToSessionRequestWrapper#5c99a8b2]
2014-01-16 23:47:13,919 DEBUG org.springframework.web.servlet.DispatcherServlet: 843 - DispatcherServlet with name 'dispatcher' processing PATCH request for [/webapp/users/52d6eb4d03640c2f5a5ee726]
2014-01-16 23:47:13,921 TRACE org.springframework.web.servlet.DispatcherServlet:1098 - Testing handler map [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#21068197] in DispatcherServlet with name 'dispatcher'
2014-01-16 23:47:13,921 DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping: 222 - Looking up handler method for path /users/52d6eb4d03640c2f5a5ee726
2014-01-16 23:47:13,924 TRACE o.s.w.s.m.m.a.RequestMappingHandlerMapping: 266 - Found 1 matching mapping(s) for [/users/52d6eb4d03640c2f5a5ee726] : [{[/users/{id}],methods=[PATCH],params=[],headers=[],consumes=[],produces=[],custom=[]}]
2014-01-16 23:47:13,925 DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping: 229 - Returning handler method [org.springframework.http.ResponseEntity<java.lang.Void> myproject.web.security.UserController.patch(org.bson.types.ObjectId) throws org.springframework.data.crossstore.ChangeSetPersister$NotFoundException]
2014-01-16 23:47:13,925 DEBUG o.s.b.factory.support.DefaultListableBeanFactory: 249 - Returning cached instance of singleton bean 'userController'
2014-01-16 23:47:13,926 TRACE org.springframework.web.servlet.DispatcherServlet:1138 - Testing handler adapter [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#5d95b457]
2014-01-16 23:47:13,938 TRACE o.s.w.m.s.HandlerMethodArgumentResolverComposite: 90 - Testing if argument resolver [org.springframework.web.method.annotation.RequestParamMethodArgumentResolver#4ece93f2] supports [class org.bson.types.ObjectId]
2014-01-16 23:47:13,939 TRACE o.s.w.m.s.HandlerMethodArgumentResolverComposite: 90 - Testing if argument resolver [org.springframework.web.method.annotation.RequestParamMapMethodArgumentResolver#27cc2b23] supports [class org.bson.types.ObjectId]
2014-01-16 23:47:13,940 TRACE o.s.w.m.s.HandlerMethodArgumentResolverComposite: 90 - Testing if argument resolver [org.springframework.web.servlet.mvc.method.annotation.PathVariableMethodArgumentResolver#4d241b3e] supports [class org.bson.types.ObjectId]
2014-01-16 23:47:13,947 TRACE org.springframework.web.method.HandlerMethod: 130 - Invoking [UserController.patch] method with arguments [52d6eb4d03640c2f5a5ee726]
2014-01-16 23:47:13,961 DEBUG o.springframework.data.mongodb.core.MongoTemplate:1446 - findOne using query: { "id" : { "$oid" : "52d6eb4d03640c2f5a5ee726"}} fields: null for class: class myproject.domain.security.User in collection: user
2014-01-16 23:47:13,964 DEBUG org.springframework.data.mongodb.core.MongoDbUtils: 109 - Getting Mongo Database name=[dev]
2014-01-16 23:47:13,965 DEBUG o.springframework.data.mongodb.core.MongoTemplate:1859 - findOne using query: { "_id" : { "$oid" : "52d6eb4d03640c2f5a5ee726"}} in db.collection: dev.user
2014-01-16 23:47:14,121 TRACE o.s.w.c.s.AnnotationConfigWebApplicationContext: 331 - Publishing event in Root WebApplicationContext: org.springframework.data.mongodb.core.mapping.event.AfterLoadEvent[source={ "_id" : { "$oid" : "52d6eb4d03640c2f5a5ee726"} , "username" : "hansi42" , "password" : "$2a$10$b0lUEN/lQXIEl2GdusGigOKZrSmB1xnrBR9VK4pklqzpGD03CB5SC" , "locked" : false , "enabled" : true , "createdDate" : { "$date" : "2014-01-15T20:10:53.329Z"} , "lastModifiedDate" : { "$date" : "2014-01-15T20:10:53.329Z"} , "createdBy" : { "$ref" : "user" , "$id" : { "$oid" : "52d61b65fc144887e496963f"}} , "lastModifiedBy" : { "$ref" : "user" , "$id" : { "$oid" : "52d61b65fc144887e496963f"}} , "accountExpiresAt" : { "$date" : "2014-04-15T20:10:53.329Z"}}]
2014-01-16 23:47:14,123 DEBUG o.s.b.factory.support.DefaultListableBeanFactory: 249 - Returning cached instance of singleton bean 'org.springframework.data.mongodb.core.mapping.event.AuditingEventListener'
2014-01-16 23:47:14,123 DEBUG o.s.b.factory.support.DefaultListableBeanFactory: 249 - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalScheduledAnnotationProcessor'
2014-01-16 23:47:14,139 TRACE o.s.w.c.s.AnnotationConfigWebApplicationContext: 331 - Publishing event in Root WebApplicationContext: org.springframework.data.mongodb.core.mapping.event.AfterConvertEvent[source=myproject.domain.security.User#4db5bba0]
2014-01-16 23:47:14,141 DEBUG o.s.b.factory.support.DefaultListableBeanFactory: 249 - Returning cached instance of singleton bean 'org.springframework.data.mongodb.core.mapping.event.AuditingEventListener'
2014-01-16 23:47:14,142 DEBUG o.s.b.factory.support.DefaultListableBeanFactory: 249 - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalScheduledAnnotationProcessor'
2014-01-16 23:47:14,160 DEBUG org.springframework.data.mongodb.core.MongoDbUtils: 109 - Getting Mongo Database name=[dev]
2014-01-16 23:47:14,230 DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver: 134 - Resolving exception from handler [org.springframework.http.ResponseEntity<java.lang.Void> myproject.web.security.UserController.patch(org.bson.types.ObjectId) throws org.springframework.data.crossstore.ChangeSetPersister$NotFoundException]: java.lang.NullPointerException
2014-01-16 23:47:14,231 DEBUG o.s.w.s.m.a.ResponseStatusExceptionResolver: 134 - Resolving exception from handler [org.springframework.http.ResponseEntity<java.lang.Void> myproject.web.security.UserController.patch(org.bson.types.ObjectId) throws org.springframework.data.crossstore.ChangeSetPersister$NotFoundException]: java.lang.NullPointerException
2014-01-16 23:47:14,232 DEBUG o.s.w.s.m.support.DefaultHandlerExceptionResolver: 134 - Resolving exception from handler [org.springframework.http.ResponseEntity<java.lang.Void> myproject.web.security.UserController.patch(org.bson.types.ObjectId) throws org.springframework.data.crossstore.ChangeSetPersister$NotFoundException]: java.lang.NullPointerException
2014-01-16 23:47:14,232 TRACE org.springframework.web.servlet.DispatcherServlet:1023 - Cleared thread-bound request context: SecurityContextHolderAwareRequestWrapper[ org.springframework.security.web.context.HttpSessionSecurityContextRepository$Servlet3SaveToSessionRequestWrapper#5c99a8b2]
2014-01-16 23:47:14,241 DEBUG org.springframework.web.servlet.DispatcherServlet: 954 - Could not complete request
java.lang.NullPointerException: null
at myproject.services.security.UserServiceImpl.updateById(UserServiceImpl.java:59) ~[UserServiceImpl.class:na]
at myproject.web.security.UserController.patch(UserController.java:47) ~[UserController.class:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_45]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_45]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_45]
at java.lang.reflect.Method.invoke(Method.java:606) ~[na:1.7.0_45]
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214) ~[spring-web-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) ~[spring-web-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) ~[spring-webmvc-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:748) ~[spring-webmvc-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689) ~[spring-webmvc-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83) ~[spring-webmvc-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945) ~[spring-webmvc-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876) ~[spring-webmvc-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:931) [spring-webmvc-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:804) [spring-webmvc-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) [servlet-api.jar:na]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) [catalina.jar:7.0.42]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) [catalina.jar:7.0.42]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108) [spring-web-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108) [spring-web-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160) [spring-security-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344) [spring-web-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261) [spring-web-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) [catalina.jar:7.0.42]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) [catalina.jar:7.0.42]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) [catalina.jar:7.0.42]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) [catalina.jar:7.0.42]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) [catalina.jar:7.0.42]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) [catalina.jar:7.0.42]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) [catalina.jar:7.0.42]
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) [catalina.jar:7.0.42]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) [catalina.jar:7.0.42]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) [catalina.jar:7.0.42]
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023) [tomcat-coyote.jar:7.0.42]
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) [tomcat-coyote.jar:7.0.42]
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) [tomcat-coyote.jar:7.0.42]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [na:1.7.0_45]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [na:1.7.0_45]
at java.lang.Thread.run(Thread.java:744) [na:1.7.0_45]
2014-01-16 23:47:14,242 TRACE o.s.w.c.s.AnnotationConfigWebApplicationContext: 331 - Publishing event in WebApplicationContext for namespace 'dispatcher-servlet': ServletRequestHandledEvent: url=[/webapp/users/52d6eb4d03640c2f5a5ee726]; client=[0:0:0:0:0:0:0:1]; method=[PATCH]; servlet=[dispatcher]; session=[7AEFE0888849ACCA51C0E3E5F31FC0BD]; user=[hansi42]; time=[330ms]; status=[failed: java.lang.NullPointerException]
2014-01-16 23:47:14,243 TRACE o.s.w.c.s.AnnotationConfigWebApplicationContext: 331 - Publishing event in Root WebApplicationContext: ServletRequestHandledEvent: url=[/webapp/users/52d6eb4d03640c2f5a5ee726]; client=[0:0:0:0:0:0:0:1]; method=[PATCH]; servlet=[dispatcher]; session=[7AEFE0888849ACCA51C0E3E5F31FC0BD]; user=[hansi42]; time=[330ms]; status=[failed: java.lang.NullPointerException]
2014-01-16 23:47:14,244 DEBUG o.s.b.factory.support.DefaultListableBeanFactory: 249 - Returning cached instance of singleton bean 'org.springframework.data.mongodb.core.mapping.event.AuditingEventListener'
2014-01-16 23:47:14,244 DEBUG o.s.b.factory.support.DefaultListableBeanFactory: 249 - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalScheduledAnnotationProcessor'
2014-01-16 23:47:14,245 DEBUG o.s.s.web.context.SecurityContextPersistenceFilter: 97 - SecurityContextHolder now cleared, as request processing completed
Jan 16, 2014 11:47:14 PM org.apache.catalina.core.StandardWrapperValve invoke
Schwerwiegend: Servlet.service() for servlet [dispatcher] in context with path [/webapp] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at myproject.services.security.UserServiceImpl.updateById(UserServiceImpl.java:59)
at myproject.web.security.UserController.patch(UserController.java:47)
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.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214)
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:748)
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:945)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:931)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:804)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
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:108)
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:108)
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.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
The NullPointerExceptions happens when p.firstName is called, because p is null, which does not happen if I use profileRepository.findByUserId(someUser.getId()).firstname.

EntityManager null pointer exception

I am getting a null pointer exception when I try to query a result from DB.
Here's the error:
java.lang.NullPointerException
at main.java.utils.WebAppInfo.getAppName(WebAppInfo.java:14)
at main.java.views.adminView.IndexView.loadPageInfo(IndexView.java:21)
at main.java.controller.MainAction.welcome(MainAction.java:24)
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.invoke(InvocableHandlerMethod.java:219)
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:746)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:687)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:811)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1221)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
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.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1212)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:399)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:766)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:450)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:928)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:549)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:410)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
Here's the function where that error is coming from.
#Resource(name="applicationInfoService")
private static ApplicationInfoService applicationInfoService;
public static ApplicationInfo getAppName() {
ApplicationInfo applicationInfo = applicationInfoService.getAppNameResult();
return applicationInfo;
}
If i initiate application info service ( = new ApplicationInfoService()) I get a null pointer error to my Service class where query is made
#Service("applicationInfoService")
#Transactional
public class ApplicationInfoService {
private EntityManager entityManager;
#PersistenceContext
public void setEntityManager(EntityManager entityManager){
this.entityManager = entityManager;
}
public ApplicationInfo getAppNameResult() {
String sql = "FROM ApplicationInfo";
Query query = entityManager.createQuery(sql);
return (ApplicationInfo) query.getSingleResult();
}
}
Error goes to createQuery line and if i print out EntityManager it returns "null".
Why wont my Entitymanager get initialized. I am using allmost the same build up in my login system and it works over there. When i use multiple EntityManager classes in a project, do i need to configure them somehow? I am not sure how to fix this problem, since im new to spring, hibernate, JPA etc.
Spring does not allow to inject static fields, thats why you are getting NullPointerException.
I can suggest you an work-arrond. Add the bellow block of code in your WebAppInfo class:
#Resource(name="applicationInfoService")
public void setService(ApplicationInfoService service) {
WebAppInfo.applicationInfoService = service;
}
Don't forget remove #Resouce annotation from applicationInfoService.
Edit:
The above suggestion was only to fix the NullPointerException in your WebAppInfo class for the reason of not being initialized an static field!
But there are can be number of causes for your EntityManager being null. As you are saying it worked for you in other system. I suggest you to
recheck the path of your persistence.xml, after the deployment.
See the answer here.
And if these does not help you, please provide sufficient information of the exception trace and related code.
What is the point of injecting a value into a static field? It can only have one value per class loader and it sort of defeats the purpose of the IoC environment. Even though sazzadur's answer will get you past the NullPointerException its not going to save you from strange bugs if other classes do same thing.
Instead of mixing paradigms, I would consider dispatching with the WebAppInfo class, converting ApplicationInfoService to a singleton and injecting it wherever appropriate.

Resources