JSF and ManagedBean : NullPointerException [duplicate] - java

This question already has an answer here:
Caused by: javax.naming.NameNotFoundException - Name [Class/object] is not bound in this Context
(1 answer)
Closed 9 years ago.
I'm designing a JSF application with managed beans.
For the moment, I've only been trying to create a simple login page (username and password are hard-coded for the moment) :
<h:form class="form-signin">
<h2 class="form-signin-heading">Please sign in</h2><hr />
<input name="username" type="text" class="input-block-level" placeholder="Username" />
<input name="password" type="password" class="input-block-level" placeholder="Password" />
<h:commandButton action="#{userController.login}" class="btn btn-block btn-primary" type="submit" value="Sign in" />
</h:form>
Here is the controller (UserController.java) :
#ManagedBean(name="userController")
#ApplicationScoped
public class UserController {
#EJB
private UserService userService;
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
public UserController() {
}
public void login() throws IOException {
Boolean login = userService.login("admin", "p4ssw0rd");
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
if (login == true) {
externalContext.redirect("dashboard.xhtml");
} else {
externalContext.redirect("login.xhtml");
}
}
}
And this is the UserService.java file :
#Stateless
public class UserService {
#PersistenceContext
private EntityManager em;
public static String md5(String input) {
// Removed for clarity...
}
public Boolean login(String username, String password) {
//String hash = md5(password);
return Boolean.TRUE; // As you can see, nothing can fail for the moment
}
}
When I submit the login form, a NullPointerException shows up :
javax.faces.el.EvaluationException: java.lang.NullPointerException
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:409)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java: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:1008)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
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:722)
Caused by: java.lang.NullPointerException
at com.myname.myproject.managedbean.UserController.login(UserController.java:33)
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.apache.el.parser.AstValue.invoke(AstValue.java:278)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
... 24 more
In UserController.java, if I replace this line :
Boolean login = userService.login("admin", "p4ssw0rd");
By this one :
Boolean login = true; // Or false (I've tested twice)
Everything works OK, so it seems like Java fails to find the UserService...
Thanks for your help, I'm completely lost.

Did you check putting getters and setters in your managed bean called UserController?
If you did not, even if the code compiles correctly, dependency injection would not be held correctly.

I believe that the problem is the EJB. It should be annotated #LocalBean if it is no-interface bean or implement an interface otherwise. Try something like this:
#Stateless
public class UserService implements UserServiceLocal {
#Override
public boolean login () {
//dummy implementation
return true;
}
}
where UserServiceLocal is:
#Local
public interface UserServiceLocal {
public boolean login();
}
Usage:
#ManagedBean(name="userController")
#ApplicationScoped
public class UserController {
#EJB
private UserServiceLocal userService;
public void login() {
userService.login();
}
}

Regarding your question about why it should implement an interface, please see EJB's - when to use Remote and/or local interfaces?. An EJB (enterprise java bean) can have an interface (which can be annotated with #Remote, meaning that the bean who implements it runs in a distributed environment, or annotated with #Local meaning the bean runs inside the same JVM. In contrast, a no-interface bean is a bean that does not implements any interface. Therefore, you should instruct JVM to treat it as a bean instead of a POJO (plain old java object); this can be accomplished by adding #LocalBean annotation on the class that it is supposed to be your bean /EJB.

Related

NullPointerException in simple fileupload form using Spring MVC

I am trying to implement simple fileupload using Spring 4.2.3 and HTML form.
I have controller class which handles whole action, simple wrapper class for file, validator and simple view with form in HTML & Thymeleaf.
Almost everything is running fine, mapping works properly and view is appearing. But when I select file from disk and press upload button I have NullPointerException. Can anyone have a look and give some tips please? I have to mention that I am novice in Spring.
Controller:
#Controller
public class FileUploadController {
private static String UPLOAD_LOCATION = "C:/Temp/";
#Autowired
FileValidator fileValidator;
#InitBinder("file")
protected void initBinderFileBucket(WebDataBinder binder) {
binder.setValidator(fileValidator);
}
#RequestMapping(value = "/upload", method = RequestMethod.GET)
public String getSingleUploadPage(ModelMap model) {
FileBucket fileModel = new FileBucket();
model.addAttribute("fileBucket", fileModel);
return "views/fileUploader";
}
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String singleFileUpload(#Valid FileBucket file, BindingResult result, ModelMap model)
throws IOException {
if (result.hasErrors()) {
System.out.println("File Uploader validation error");
return "views/fileUploader";
} else {
System.out.println("Fetching file"); //prints out in console
MultipartFile multipartFile = file.getFile();
System.out.println(multipartFile.getName()); //NullPointer here
return "views/success";
}
}
}
File wrapper:
public class FileBucket {
private MultipartFile file;
//getters & setters + soon other stuff
}
Validator:
#Component
public class FileValidator implements Validator {
public boolean supports(Class<?> clazz) {
return FileBucket.class.isAssignableFrom(clazz);
}
public void validate(Object obj, Errors errors) {
FileBucket file = (FileBucket) obj;
if(file.getFile()!=null){
if (file.getFile().getSize() == 0) {
errors.rejectValue("file", "missingfile");
}
}
}
}
View:
<!DOCTYPE html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:th="http://www.thymeleaf.org"
layout:decorator="templates/baseTemplate">
<head>
<title>Upload Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div layout:fragment="contentPanel" class="form-container">
<h1>Simple upload</h1>
<form method="POST" enctype="multipart/form-data" action="upload" >
<input type="file" name="file" /> <br />
<input type="submit" value="Upload" />
</form>
</div>
Demo
</body>
</html>
Stacktrace:
INFO: Starting ProtocolHandler ["http-bio-8080"]
Fetching file
kwi 23, 2016 12:39:36 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [spring] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at web.controllers.FileUploadController.singleFileUpload(FileUploadController.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
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.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
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:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
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.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
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:745)
Okay I found out what's causing the problem.
After correcting name in #InitBinder to match argument in controller it was necessary to rename bean responsible for multipart resolving.
From:
#Bean public CommonsMultipartResolver commonsMultipartResolver() {
return new CommonsMultipartResolver();
}
To:
#Bean public CommonsMultipartResolver multipartResolver() {
return new CommonsMultipartResolver();
}
Otherwise it doesn't work.

File upload in Spring MVC gives NullPointerException

I have a simple JSP form as follows:
<p>Please select a file and <i>click</i> <i>Upload file</i> to upload the file to the server:</p>
<c:url value="/upload/display" var="displayUploadedFileURL" />
<form:form action="${displayUploadedFileURL}" method="post" modelAttribute="upload" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload file" /> <form:errors path="file" />
<input type="Reset" value="Reset">
</form:form>
Which is for a user to upload a file to the server. The controller's method is as follows:
#Controller
#RequestMapping("/upload")
public class UploadController {
#Autowired
private UploadValidator uploadValidator;
#RequestMapping(value="/display", method=RequestMethod.POST)
public String displayUploadedFile(#ModelAttribute("upload") Upload upload,
BindingResult bindingResult,
Model model) {
// Validate Upload.
uploadValidator.validate(upload, bindingResult);
if (bindingResult.hasErrors()) {
return ("view/upload/select");
}
else {
String fileName = upload.getFile().getOriginalFilename();
System.out.println("Here: " + upload.getFile().getOriginalFilename());
model.addAttribute("fileName", fileName);
return ("view/upload/display");
}
}
...
But when I select a file and use the Upload file button I get the following:
Your page request has caused a NullPointerException: error:
library.validator.UploadValidator.validate(UploadValidator.java:29)
library.controller.upload.UploadController.displayUploadedFile(UploadController.java:45)
The validator concerned is very simple:
package library.validator;
import library.model.Upload;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
#Component
public class UploadValidator implements Validator {
private static final Logger logger = Logger.getLogger(UploadValidator.class);
public UploadValidator() {
}
#Override
public boolean supports(Class cls) {
return Upload.class.isAssignableFrom(cls);
}
#Override
public void validate(Object target, Errors errors) {
logger.info(UploadValidator.class.getName() + ".validate() method called.");
Upload upload = (Upload) target;
if (upload.getFile().getSize() == 0) {
errors.rejectValue("file", "file.required");
}
}
}
I have all the relevant .jar files in the application's .lib folder, and I'mincluding the following:
<bean id="uploadValidator" class="library.validator.UploadValidator" />
<!-- Spring multipartResolver. -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
In the DispatcherServlet.
The Upload object type is as follows:
import org.springframework.web.multipart.MultipartFile;
public class Upload {
private MultipartFile file;
And appropriate getter and setter.
So why is my code not working?
Stacktrace for current problem, i.e. allowing for changes to controller method in answer below, is:
org.springframework.util.Assert.notNull(Assert.java:112)
org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.resolveName(RequestParamMethodArgumentResolver.java:171)
org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:89)
org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:79)
org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:157)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:124)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)
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:961)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:744)
Configuring the multipartResolver bean is important thing, but also you should check that your .xml config file with this bean is imported in your general applicationContext.xml, if you have some. I had same problem and this did the thing.
This has now been solved. The problem was that the following was incorrectly defined in the DispatcherServlet:
<!-- Spring multipartResolver. -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

GWTP NullPointerException with GWT RemoteServiceServlet

I am getting an NPE when I deploy to Tomcat (this doesn't happen every time, only sometimes when I re-deploy). The error is a NullPointerException when the RemoteServiceServlet tries to loadSerializationPolicy(..). I noticed that the issue was with the servlet.log method call, when the loadSerializationPolicy fails to find the serialization policy file (which seems like another problem? Perhaps its not and the serialization will just skip it, idk), so it tries to log it but falls over with an NPE.
So as explained here: https://github.com/ArcBees/GWTP/issues/289#issuecomment-21675896 the issue is that RemoteServiceServlet cannot find the logger? I tried the proposed solution which was to create a new DispatchServiceImpl in my project that replaces the standard GWTP service implementation and implement ServletConfigAware with a ServletConfig object and overriding getServletConfig() and setServletConfig(...). This did not resolve the issue for me however. This doesn't happen when I use Chrome browser only Firefox and IE (that I have tested). I assume Chrome isn't failing to find the policy file? Or isn't performing an unnecessary check?
java.lang.NullPointerException
at javax.servlet.GenericServlet.getServletName(GenericServlet.java:238)
at javax.servlet.GenericServlet.log(GenericServlet.java:190)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.loadSerializationPolicy(RemoteServiceServlet.java:103)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.doGetSerializationPolicy(RemoteServiceServlet.java:293)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.getSerializationPolicy(RemoteServiceServlet.java:157)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamReader.prepareToRead(ServerSerializationStreamReader.java:491)
at com.google.gwt.user.server.rpc.RPC.decodeRequest(RPC.java:240)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:206)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at com.gwtplatform.dispatch.server.spring.DispatchServiceImpl.handleRequest(DispatchServiceImpl.java:68)
at org.springframework.web.context.support.HttpRequestHandlerServlet.service(HttpRequestHandlerServlet.java:68)
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.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java: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(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Now this issue doesn't take place in Dev Mode. Only on random occasions that I redeploy to Tomcat. If anyone has any useful advice or have ran into this issue before, I would be really grateful for the help!
Here are some classes that might help with identifying the issue:
DispatchServiceImpl.java (replacing the standard GWTP DispatchServiceImpl)
#Component("dispatch")
public class DispatchServiceImpl extends AbstractDispatchServiceImpl implements HttpRequestHandler,
ServletContextAware, ServletConfigAware {
private static final long serialVersionUID = 136176741488585959L;
private ServletContext servletContext;
private ServletConfig servletConfig;
#Autowired(required = false)
protected String securityCookieName;
#Autowired
public DispatchServiceImpl(final Logger logger, final Dispatch dispatch,
RequestProvider requestProvider) {
super(logger, dispatch, requestProvider);
}
#Override
public String getSecurityCookieName() {
return securityCookieName;
}
public void setSecurityCookieName(String securityCookieName) {
this.securityCookieName = securityCookieName;
}
#Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
#Override
public void setServletContext(ServletContext arg0) {
this.servletContext = arg0;
}
#Override
public ServletContext getServletContext() {
return servletContext;
}
#Override
public void setServletConfig(ServletConfig servletConfig) {
this.servletConfig = servletConfig;
}
#Override
public ServletConfig getServletConfig() {
return servletConfig;
}
}
ServerModule.java
/**
* Module which binds the handlers and configurations.
*/
#Configuration
#Import({
DefaultModule.class,
PropertyModule.class,
ConfigLoader.class
})
#ComponentScan({
"nz.co.doltech.ims",
"nz.co.doltech.ims.framework.extensions.platform.dispatch.server.spring"
})
#ImportResource("classpath:META-INF/properties.xml")
#EnableAspectJAutoProxy
#EnableTransactionManagement
public class ServerModule extends HandlerModule {
... snip ...
}
Well I did the obvious and Overrode getServletName and now it works fine. Strange that ServletConfigAware didn't help with this issue though.

(persistence) Entity Manager can not be created

I am having this problem and its 2 days I can not figure out why is happening.
I want to verify login. My code:
public String Verify(String name, String password) {
String admin="";
Query q = emf
.createEntityManager()
.createQuery(
"SELECT u FROM user u where u.name = :name and u.password=:password");
q.setParameter("name", name);
q.setParameter("password", password);
User u = (User) q.getSingleResult();
if (u.getAdmin().equalsIgnoreCase("yes")) {
admin = "yes";
} else {
admin = "no";
}
return admin;
}
I am getting this error then:
java.lang.NullPointerException
at db.DbProcessor.Verify(DbProcessor.java:19)
at controller.VerifikoServlet.doGet(VerifikoServlet.java:25)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Line 19 is ".createEntityManager()"
I fixed the problem writing this for initializing the Entity Factory Manager:
private static EntityManagerFactory factory = Persistence
.createEntityManagerFactory("PROJECT_NAME");
EntityManager em = factory.createEntityManager();
The problem is that you have not initialized your EntityManagerFactory. As I can see, you are running in Servlet environment.
Look at this link, it may be useful for you to read that: http://weblogs.java.net/blog/ss141213/archive/2005/12/dont_use_persis_1.html
If the persistence layers are loaded are not this thing we can verify by simply adding the below code :
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public class JpaUtil {
private static final EntityManagerFactory emf;
static {
try {
factory = Persistence.createEntityManagerFactory("MyPu");
} catch (Throwable ex) {
logger.error("Initial SessionFactory creation failed", ex);
throw new ExceptionInInitializerError(ex);
}
}
...
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Please not this is a common stuff to get the entity Manager Factory Object. But here what is important is the Exception Handling inside that i.e. ExceptionInInitializerError ...
This will clearly tell if there is any problem related to your Entity classes like the missing TemporalType for a Date type variable or like that.
So if suppose you are using a NamedQuery in your entity class but even though since the persistence will not be able to load it because of any missing type or required property (like TemoralType for Date type) in your entity class.
so Make sure you handle the Exception mentioned

ContextNotActiveException with CDI

I am trying to set up CDI (for #ConversationScoped) within an app using JSF/Primefaces and deployed on Jetty. I am receiving this exception with (what I believe is) a very basic ConversationScoped bean. Have combed through all relevant search results I can find and come up with nothing, so will appreciate any advice.
#Named
#ConversationScoped
public class RegisterBean implements Serializable {
...
private #Inject Conversation conversation;
...
public String doSubmitBasicInfo() {
conversation.begin();
if(accountType == null)
return null;
if(accountType.equals("seller_account"))
return "register_seller_1?faces-redirect=true";
else if(accountType.equals("buyer_account"))
return "register_buyer_1?faces-redirect=true";
return null;
}
...
The relevant portion of the JSF page is:
<div style="text-align:center;" class="noBorder autoMargin">
<p:commandButton type="submit" action="#{registerBean.doSubmitBasicInfo}" ajax="false" value="Submit" styleClass="autoMargin"></p:commandButton>
</div>
The exception is:
javax.enterprise.context.ContextNotActiveException: Conversation Context not active when method called on conversation Conversation with id: 1
at org.jboss.weld.context.conversation.ConversationImpl.verifyConversationContextActive(ConversationImpl.java:197)
at org.jboss.weld.context.conversation.ConversationImpl.getLastUsed(ConversationImpl.java:154)
at org.jboss.weld.context.AbstractConversationContext.isExpired(AbstractConversationContext.java:337)
at org.jboss.weld.context.AbstractConversationContext.invalidate(AbstractConversationContext.java:285)
at org.jboss.weld.jsf.WeldPhaseListener.deactivateConversations(WeldPhaseListener.java:146)
at org.jboss.weld.jsf.WeldPhaseListener.afterPhase(WeldPhaseListener.java:91)
at com.sun.faces.lifecycle.Phase.handleAfterPhase(Phase.java:189)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:107)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:598)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:486)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:524)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:233)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1065)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:413)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:192)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:999)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:250)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:149)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:111)
at org.eclipse.jetty.server.Server.handle(Server.java:350)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:454)
at org.eclipse.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:890)
at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:944)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:630)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:230)
at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:77)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:606)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:46)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:603)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:538)
at java.lang.Thread.run(Thread.java:722)

Categories

Resources