GWTP NullPointerException with GWT RemoteServiceServlet - java

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.

Related

Can #Resource annotation use normally without spring-framework?

I've known the difference between #Resource annotation and #Autowired annotation recently, but I don't know in what scene #Resource annotation will be used before spring-framework has been invented.
I've search google and stackoverflow for any hints and don't get any reasonable explanation. Then I've tried to create a Java Web Project(use J2EE1.4, jdk1.7, tomcat 7), and create a servlet to mock Spring's autowire behavior by using #Resource annotation, but we encounter a error.
Below the code I use:
public class TestServlet extends HttpServlet {
public void init() throws ServletException {
Student student=new Student("1");
}
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("111111111111");
}
}
public class TestServlet2 extends HttpServlet {
#Resource
Student student;
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println(student);
}
}
First, I visit the TestServlet to create Student java bean, and then I visit TestServlet2 to inject Student object to student property. But I encounter a error like below:
javax.naming.NamingException: Cannot create resource instance
at org.apache.naming.factory.ResourceEnvFactory.getObjectInstance(ResourceEnvFactory.java:115)
at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:321)
at org.apache.naming.NamingContext.lookup(NamingContext.java:848)
at org.apache.naming.NamingContext.lookup(NamingContext.java:159)
at org.apache.naming.NamingContext.lookup(NamingContext.java:836)
at org.apache.naming.NamingContext.lookup(NamingContext.java:173)
at org.apache.catalina.core.DefaultInstanceManager.lookupFieldResource(DefaultInstanceManager.java:538)
at org.apache.catalina.core.DefaultInstanceManager.processAnnotations(DefaultInstanceManager.java:440)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:133)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:114)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1133)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:853)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2549)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2538)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Thank you very much!#Powerlord Your advice is of great help, and solve my problem perfectly.This is my solution:
I create a file Context.xml in WebRoot/META-INF
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="student" auth="Container"
type="com.test.Student" factory="org.apache.naming.factory.BeanFactory" id="5">
</Resource>
</Context>
public class TestServlet2 extends HttpServlet {
#Resource(name="student")
Student student;
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
System.out.println(student.getId());
}
}

"IllegalStateException: Response already committed" in Struts2 Interceptor chain on WebLogic 10.3.x on Linux [duplicate]

I have some code for download file from web server.
Everything works alright, but in console I have this exception:
июн 26, 2015 2:08:42 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [default] in context with path [/TestTask] threw exception
java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
at org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:462)
at org.apache.struts2.dispatcher.DefaultDispatcherErrorHandler.handleErrorInDevMode(DefaultDispatcherErrorHandler.java:109)
at org.apache.struts2.dispatcher.DefaultDispatcherErrorHandler.handleError(DefaultDispatcherErrorHandler.java:57)
at org.apache.struts2.dispatcher.Dispatcher.sendError(Dispatcher.java:909)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:576)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:81)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:526)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:655)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Why and what it can be? And how i can fix this problem? I try find answer in the google, but I failed.
The code:
package actions;
import java.io.IOException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Action;
import org.apache.log4j.Logger;
import org.apache.struts.chain.contexts.ServletActionContext;
import service.CsvCreator;
import com.opensymphony.xwork2.ActionSupport;
public class DownloadCsvAction extends ActionSupport {
private static final long serialVersionUID = -4714537109287679996L;
private CsvCreator CSVcreator;
private static final Logger logger = Logger.getLogger(DownloadCsvAction.class);
public CsvCreator getCSVcreator() {
return CSVcreator;
}
public void setCSVcreator(CsvCreator cSVcreator) {
CSVcreator = cSVcreator;
}
#Override
public String execute() {
HttpServletResponse response = org.apache.struts2.ServletActionContext.getResponse();
response.setHeader("Content-Disposition", "attachment; filename=\"phone_records.csv\"");
response.setContentType("text/csv");
ServletOutputStream out;
try {
out = response.getOutputStream();
String tableHeader = "Caller, Event, Reciever, Timestamp\n";
out.write(tableHeader.getBytes("UTF-8"));
out.write(CSVcreator.getAllRecordsInString().getBytes("UTF-8"));
out.flush();
out.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
return SUCCESS;
}
}
And my struts.xml:
<action name="DownloadCsvAction" class="DownloadCsvAction">
<result name="success" type="dispatcher"/>
</action>
Why and what it can be?
Because response is already committed. You have closed response before it's used by the Struts2.
And how I can fix this problem?
When your action execution ends, return Action.NONE result code. This code tells the invoker to not execute any result because response might be already committed.
You can also rewrite the action implementation to use stream result type. In this way you have not to do with the response and let Struts2 do the rest. Example of using stream result is here.

Initializing filter with values from application.properties

I want to secure my REST API (jersey2) based on IP addresses, but without having the trouble of Spring Security and so on. I simply need to whitelist a few IPs that are granted full access rights.
To implement this, I thought of putting the IPs into the application.properties and enforcing the restriction using a Filter. This works perfectly fine, when using an embedded Jetty server, but fails when deploying the application as war on Tomcat.
I tried to read the properties both in the Filter constructor and in the init-method (only the constructor example shown below in the snippet). Nevertheless both lead to a NullPointerException when accessing the class field (String ips), which store the IPs. Also using the Enviroment variable does not seem to help.
Any help is appreciated. Thank you!
#Component("RestAuthFilter")
public class RestAuthFilter implements Filter {
private String ips;
public RestAuthFilter() {
try {
final Properties p;
final InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("application.properties");
p = new Properties();
p.load(input);
ips = p.getProperty("whitelist.rest.ips");
} catch(IOException e) {
ips = "127.0.0.1";
}
}
#Override
public void init(final FilterConfig config) throws ServletException {
}
#Override
public void doFilter(final ServletRequest req, final ServletResponse res,
final FilterChain chain) throws ServletException, IOException {
final List<String> allowedIPs = Arrays.asList(ips.split("[,]"));
if(!allowedIPs.contains(req.getRemoteAddr())) {
((HttpServletResponse) res).setStatus(HttpServletResponse.SC_FORBIDDEN, "Not allowed to use REST API!");
} else {
chain.doFilter(req, res);
}
}
#Override
public void destroy() {
}
}
Stacktrace:
java.lang.NullPointerException: null
at com.example.RestAuthFilter.doFilter(RestAuthFilter.java:44)
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:85)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:113)
at org.springframework.boot.context.web.ErrorPageFilter.access$000(ErrorPageFilter.java:59)
at org.springframework.boot.context.web.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:106)
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:313)
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:745)
Since you're using Spring Boot and your setup is pretty standard, I would stick to using PropertySource (via #Value or Environment) to load the IPs from application.properties. Having said that, and noticing your comment about using Environment ...
Concerning to the Environment variable I am refering to
org.springframework.core.env.Environment, which I included using DI,
something like #Autowired Environment env as class member
You can't inject it as a class member and have your initialization in the constructor, you'll run into scoping issue -- the Environment will not be set when the constructor is called. You need to inject the Environment via constructor not as a class member, for example:
#Component("RestAuthFilter")
public class RestAuthFilter implements Filter {
private final List<String> restClientIps;
#Autowired
public RestAuthFilter(Environment env) {
String restClientIpsProperty = env.getRequiredProperty("whitelist.rest.ips");
restClientIps = // parse/split from restClientIpsProperty
}
...
}

JSF and ManagedBean : NullPointerException [duplicate]

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.

(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

Categories

Resources