Calling session bean from servlet vs jsp->servlet grants different result - java

I'm having a problem trying to call a method of session bean, when calling firstly the servlet from a JSP, then the servlet calling the method of session bean to obtain some data it seems to get a NullPointerException. On the other hand if I just run the servlet on it's own it does the job and retrieves the data from session bean.
The following is the code of the servlet;
package web;
import java.io.IOException;
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import auction.ItemRegistrationSessionBeanRemote;
/**
* Servlet implementation class processItem
*/
#WebServlet("/processItem")
public class processItem extends HttpServlet {
private static final long serialVersionUID = 1L;
public ArrayList<String> categories = new ArrayList<String>();
#EJB ItemRegistrationSessionBeanRemote itemRegistrationSession;
/**
* #see HttpServlet#HttpServlet()
*/
public processItem() {
super();
}
#PostConstruct
public
void init() {
System.out.println("init()");
categories = itemRegistrationSession.getCategories();
System.out.println("init() categories = " + categories.toString());
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
#PostConstruct
public void obtainCategories() {
categories = itemRegistrationSession.getCategories();
}
#PostConstruct
public ArrayList<String> getCategories() {
return categories;
}
}
This is the part of JSP that calls the servlet:
<jsp:useBean id="obj" scope="page" class="web.processItem" />
<select name="affiliation" id="categories-dropdown">
<% obj.init(); %>
<c:forEach var="aff" items="${obj.getCategories()}"
<%System.out.println("categories = " + obj.getCategories()); %>
<option value="${aff}">${aff}</option>
</c:forEach>
</select>
This is the Session Bean:
package auction;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateful;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.sun.jersey.spi.resource.Singleton;
import entity.Category;
/**
* Session Bean implementation class ItemRegistrationSessionBean
*/
#Stateful #Singleton
public class ItemRegistrationSessionBean implements ItemRegistrationSessionBeanRemote {
#PersistenceContext(name = "MiniEbayEJB")
private EntityManager emgr;
/**
* Default constructor.
*/
public ItemRegistrationSessionBean() {
// TODO Auto-generated constructor stub
}
#Override
public ArrayList<String> getCategories() {
System.out.println("Hello from SessionBean getCategories");
ArrayList<String> categories = new ArrayList<String>();
List<Category> obtainedCategories = (List<Category>) emgr.createNamedQuery("Category.findAll", Category.class).getResultList();
for (int i = 0; i < obtainedCategories.size(); i++) {
categories.add(obtainedCategories.get(i).toString());
System.out.println("Current ArrayList of categories = " + categories);
}
return categories;
}
}
And here is the stack trace when calling from jsp->servlet->session bean:
2014-02-28T14:48:21.696+0000|WARNING: StandardWrapperValve[jsp]: PWC1406: Servlet.service() for servlet jsp threw exception
java.lang.NullPointerException
at web.processItem.init(processItem.java:35)
at org.apache.jsp.insert_jsp._jspService(insert_jsp.java:166)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:111)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:411)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:473)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:377)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:744)

You can't call the "servlet" instance from the JSP like you do.
What you actually do with:
<jsp:useBean id="obj" scope="page" class="web.processItem" />
is to create a "new" instance of web.processItem which is not container managed at all - hence it does not have your dependencies.
The servlet only call does work, because the container did create and manage the instance of processItem and you got your dependencies injected.

Related

Restful Web Service Error

I use Javax Restfull web service. I can return String from mobile app. but I cant return Model class.
I want to return Employee model. I give a error;
Full Error:
SEVERE: Servlet.service() for servlet [Jersey REST Service] in context with path [/CafeSiparis] threw exception [Servlet execution threw an exception] with root cause
java.lang.AbstractMethodError
at org.codehaus.jackson.map.AnnotationIntrospector$Pair.findSerializer(AnnotationIntrospector.java:1148)
at org.codehaus.jackson.map.ser.BasicSerializerFactory.findSerializerFromAnnotation(BasicSerializerFactory.java:362)
at org.codehaus.jackson.map.ser.BeanSerializerFactory.createSerializer(BeanSerializerFactory.java:252)
at org.codehaus.jackson.map.ser.StdSerializerProvider._createUntypedSerializer(StdSerializerProvider.java:782)
at org.codehaus.jackson.map.ser.StdSerializerProvider._createAndCacheUntypedSerializer(StdSerializerProvider.java:735)
at org.codehaus.jackson.map.ser.StdSerializerProvider.findValueSerializer(StdSerializerProvider.java:344)
at org.codehaus.jackson.map.ser.StdSerializerProvider.findTypedValueSerializer(StdSerializerProvider.java:420)
at org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:601)
at org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:256)
at org.codehaus.jackson.map.ObjectMapper.writeValue(ObjectMapper.java:1604)
at org.codehaus.jackson.jaxrs.JacksonJsonProvider.writeTo(JacksonJsonProvider.java:527)
at com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy.writeTo(JacksonProviderProxy.java:160)
at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:306)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1437)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
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 controls.SimpleCORSFilter.doFilter(SimpleCORSFilter.java:31)
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:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
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.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2440)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2429)
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)
My class:
Employee Model:
package model;
/**
*
* #author cengizhan
*/
public class Employee {
private String name;
private String surname;
private int id;
public Employee(int id, String name, String surname){
this.id = id;
this.name=name;
this.surname =surname;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the surname
*/
public String getSurname() {
return surname;
}
/**
* #param surname the surname to set
*/
public void setSurname(String surname) {
this.surname = surname;
}
/**
* #return the id
*/
public int getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(int id) {
this.id = id;
}
}
Web Service Class:
package ws;
import helper.UrunHelper;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import model.Employee;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
#Path("/WSLogin")
public class WSLogin implements Serializable {
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/returnModel")
public Employee returnModel() {
Employee emp = new Employee(1, "Jack", "Jason");
return emp;
}
}
SimpleCORSFilter:
package controls;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author cengizhan
*/
public class SimpleCORSFilter implements Filter {
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {
}
public void destroy() {
}
}
Web.xml:
<!-- Web Service -->
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>ws</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<!-- /Web Service -->
Thank you :)
Looks like you are mixing dependency versions.. try using jersey-server-1.8 and jersey-json-1.8 (and adjust their dependencies versions)
Maven could help you out on this..
EDIT: Try using the following jars

Error java.lang.InstantiationException

I'm trying to create a project with glassfish JSF and JPA, but I'm having trouble with the persistence unit in the persistence.xml file.
The error is the following:
GlassFish 3.1 at localhost
2014-05-06T12:47:52.326-0300|INFO: Initializing Mojarra 2.1.6
(SNAPSHOT 20111206) for context '/K19-Integracao-JSF-JPA'
2014-05-06T12:47:52.649-0300|SEVERE:
WebModule[/K19-Integracao-JSF-JPA]PWC1270: Exception starting filter
br.com.k19.filters.JPAFilter java.lang.InstantiationException at
org.apache.catalina.core.ApplicationFilterConfig.(ApplicationFilterConfig.java:124)
at
org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4685)
at
org.apache.catalina.core.StandardContext.start(StandardContext.java:5377)
at com.sun.enterprise.web.WebModule.start(WebModule.java:498) at
org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:917)
at
org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:901)
at
org.apache.catalina.core.StandardHost.addChild(StandardHost.java:733)
at
com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2018)
at
com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1669)
at
com.sun.enterprise.web.WebApplication.start(WebApplication.java:109)
at org.glassfish.internal.data.EngineRef.start(EngineRef.java:130)
at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:269)
at
org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:301)
at
com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:461)
at
com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:240)
at
org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:389)
at
com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:348)
at
com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:363)
at
com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1085)
at
com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:95)
at
com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1291)
at
com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1259)
at
com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:461)
at
com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:212)
at
com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:179)
at
com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117)
at
com.sun.enterprise.v3.services.impl.ContainerMapper$Hk2DispatcherCallable.call(ContainerMapper.java:354)
at
com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at
com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:849)
at
com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:746)
at
com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1045)
at
com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:228)
at
com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at
com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at
com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at
com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at
com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at
com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71) at
com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at
com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:744) Caused by:
javax.persistence.PersistenceException: No Persistence provider for
EntityManager named k19pu at
javax.persistence.Persistence.createEntityManagerFactory(Unknown
Source) at
javax.persistence.Persistence.createEntityManagerFactory(Unknown
Source) at br.com.k19.filters.JPAFilter.init(JPAFilter.java:57) at
org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:264)
at
org.apache.catalina.core.ApplicationFilterConfig.(ApplicationFilterConfig.java:120)
... 41 more
2014-05-06T12:47:52.662-0300|INFO: WEB0671: Loading application
[K19-Integracao-JSF-JPA] at [/K19-Integracao-JSF-JPA]
2014-05-06T12:47:52.693-0300|INFO: K19-Integracao-JSF-JPA was
successfully deployed in 774 milliseconds.
2014-05-06T12:47:53.049-0300|SEVERE: Error Rendering
View[/carros.xhtml] javax.el.ELException: /carros.xhtml #24,58
rendered="#{not empty carroBean.carros}":
java.lang.NullPointerException at
com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:114)
at
javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at
javax.faces.component.UIComponentBase.isRendered(UIComponentBase.java:413)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1751)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at
com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:402)
at
com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594) at
org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1542)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at
org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at
org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at
org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at
com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at
com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at
com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:849)
at
com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:746)
at
com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1045)
at
com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:228)
at
com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at
com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at
com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at
com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at
com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at
com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71) at
com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at
com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:744) Caused by:
java.lang.NullPointerException at
br.com.k19.modelo.CarroRepository.buscaTodos(CarroRepository.java:21)
at br.com.k19.controle.CarroBean.getCarros(CarroBean.java:30) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606) at
javax.el.BeanELResolver.getValue(BeanELResolver.java:363) at
com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at
com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at com.sun.el.parser.AstValue.getValue(AstValue.java:138) at
com.sun.el.parser.AstValue.getValue(AstValue.java:183) at
com.sun.el.parser.AstEmpty.getValue(AstEmpty.java:66) at
com.sun.el.parser.AstNot.getValue(AstNot.java:63) at
com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:224)
at
com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
... 35 more
2014-05-06T12:47:53.053-0300|WARNING: StandardWrapperValve[Faces
Servlet]: PWC1406: Servlet.service() for servlet Faces Servlet threw
exception java.lang.NullPointerException at
br.com.k19.modelo.CarroRepository.buscaTodos(CarroRepository.java:21)
at br.com.k19.controle.CarroBean.getCarros(CarroBean.java:30) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606) at
javax.el.BeanELResolver.getValue(BeanELResolver.java:363) at
com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at
com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at com.sun.el.parser.AstValue.getValue(AstValue.java:138) at
com.sun.el.parser.AstValue.getValue(AstValue.java:183) at
com.sun.el.parser.AstEmpty.getValue(AstEmpty.java:66) at
com.sun.el.parser.AstNot.getValue(AstNot.java:63) at
com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:224)
at
com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at
javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at
javax.faces.component.UIComponentBase.isRendered(UIComponentBase.java:413)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1751)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at
com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:402)
at
com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594) at
org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1542)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at
org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at
org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at
org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at
com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at
com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at
com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:849)
at
com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:746)
at
com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1045)
at
com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:228)
at
com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at
com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at
com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at
com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at
com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at
com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71) at
com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at
com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:744)
And the classes I am using are as follows:
package br.com.k19.modelo;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class CarroRepository {
private EntityManager manager;
public CarroRepository(EntityManager manager) {
this.manager = manager;
}
public void adiciona(Carro carro) {
this.manager.persist(carro);
}
public List<Carro> buscaTodos() {
Query query = this.manager.createQuery("select x from Carro x");
return query.getResultList();
}
}
package br.com.k19.modelo;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Carro implements Serializable {
/**
*
*/
private static final long serialVersionUID = 4209908627808946183L;
#Id #GeneratedValue
private Long id;
private String marca;
private String modelo;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public String getModelo() {
return modelo;
}
public void setModelo(String modelo) {
this.modelo = modelo;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
package br.com.k19.filters;
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
#WebFilter(servletNames={"Faces Servlet"})
public class JPAFilter implements Filter {
private EntityManagerFactory factory;
#Override
public void destroy() {
this.factory.close();
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// Chegada
EntityManager manager = factory.createEntityManager();
request.setAttribute("EntityManager", manager);
manager.getTransaction().begin();
// Chegada
// Faces Servelet
chain.doFilter(request, response);
// Faces Servelet
// Saída
try {
manager.getTransaction().commit();
} catch(Exception e) {
manager.getTransaction().rollback();
} finally {
manager.close();
}
// Saída
}
#Override
public void init(FilterConfig filterConfig) throws ServletException {
this.factory = Persistence.createEntityManagerFactory("K19-PU");
}
}
package br.com.k19.controle;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import br.com.k19.modelo.Carro;
import br.com.k19.modelo.CarroRepository;
#ManagedBean
public class CarroBean {
private Carro carro = new Carro();
public void adicionaCarro() {
EntityManager manager = this.getEntityManager();
CarroRepository repository = new CarroRepository(manager);
repository.adiciona(carro);
carro = new Carro();
}
public List<Carro> getCarros() {
EntityManager manager = this.getEntityManager();
CarroRepository repository = new CarroRepository(manager);
return repository.buscaTodos();
}
private EntityManager getEntityManager() {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
HttpServletRequest request = (HttpServletRequest) ec.getRequest();
EntityManager manager = (EntityManager) request.getAttribute("EntityManager");
return manager;
}
public Carro getCarro() {
return carro;
}
public void setCarro(Carro carro) {
this.carro = carro;
}
}
And the file carro.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<title>K19 treinamentos</title>
</h:head>
<h:body>
<h:form>
<h:panelGrid columns="2">
<h:outputLabel value="Marca: " for="campo-marca" />
<h:inputText value="#{carroBean.carro.marca}" id="campo-marca" />
<h:outputLabel value="Modelo: " for="campo-modelo" />
<h:inputText value="#{carroBean.carro.modelo}" id="campo-modelo" />
<h:commandButton action="#{carroBean.adicionaCarro}" value="Adicionar" />
</h:panelGrid>
</h:form>
<h:panelGroup rendered="#{not empty carroBean.carros}" >
<h1>Lista de Carros</h1>
<ul>
<ui:repeat value="#{carroBean.carros}" var="carro">
<li> <h:outputText value="#{carro.marca} #{carro.modelo}" /> </li>
</ui:repeat>
</ul>
</h:panelGroup>
</h:body>
</html>
My persistence.xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="K19-PU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<property name="hibernate.hbm2ddl.auto" value="create" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="admin" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/K19DB"/>
</properties>
</persistence-unit>
</persistence>
My persistence.xml in this folder: ~/workspace/K19-Integracao-JSF-JPA/src/META-INF/persistence.xml
I put the mysql connector jar in the glassfish directory:
/opt/glassfish3/glassfish/lib/mysql-connector-java-5.1.30-bin.jar
I'm sorry for posting so much, is that I'm already crazy with this error.
I already searched a lot on the internet and can not resolve the problem, please can someone help me?
I think should always look at the root cause of exception. In your case
Caused by: javax.persistence.PersistenceException:
No Persistence provider for EntityManager named k19pu at javax.persistence.Persistence.createEntityManagerFactory
Your persistence.xml is not valid that's why EntityManagerFactory can't be get created.
due this you are also getting NLP at CarroRepository#buscaTodos method
Caused by: java.lang.NullPointerException at br.com.k19.modelo.CarroRepository.buscaTodos
So Please correct your Persistence.xml and make sure same PU. hope this will solve your problem
Here's the problem:
2014-05-06T12:47:53.049-0300|SEVERE: Error Rendering View[/carros.xhtml] javax.el.ELException: /carros.xhtml #24,58 rendered="#{not empty carroBean.carros}": java.lang.NullPointerException
...
Caused by: java.lang.NullPointerException at br.com.k19.modelo.CarroRepository.buscaTodos(CarroRepository.java:21) at br.com.k19.controle.CarroBean.getCarros(CarroBean.java:30)
Looking until CarroRepository#buscaTodos, line 21 of CarroRepository.java: file, we get this line:
Query query = this.manager.createQuery("select x from Carro x");
The NullPointerException means that EntityManager manager is null.
You have to check why the EntityManagerFactory cannot create a new instance of EntityManager in your JPAFilter servlet filter.

Error while calling a method which passes request and response For storing a file to MYSQL databases

i am developing a project KNOWLEDGE based community sharing system.
in which users can login and share their resources to other Users....
I'm getting a problem in uploading a file to mysql database....
PS..my Instructor strictly Says to use MVC architecture So, i have to use the same..
So i have created only one Servlet named Controller.java.
here i will redirect to other java programs for calculations...
Here is the code for Controller.java
package com.kbcss.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.kbcss.command.LoginCommand;
import com.kbcss.command.Commands;
import com.kbcss.command.ResourceCommand;
import com.kbcss.command.UserCommand;
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
public Controller() {super();}
#SuppressWarnings("rawtypes")
private Map commands = new HashMap();
#SuppressWarnings("unchecked")
public void init(ServletConfig config) throws ServletException{
super.init();
System.out.println("i am in init");
this.commands.put("login", new LoginCommand());
this.commands.put("user", new UserCommand());
this.commands.put("resource", new ResourceCommand());
System.out.println("i am about to exit init");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("i am in doget");
processCommand(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("i am in dopost");
processCommand(request, response);
}
private void processCommand(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("i am in processCommand");
String formAction = request.getParameter("form_action");
System.out.println("i am in processCommand state 2");
Commands command = (Commands) commands.get(formAction);
command.execute(request, response);
System.out.println("i am about to exit processCommand");
}
}
and here is the code for saving the resources to MY database table.... Named ResourceCommand .java
package com.kbcss.command;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.sql.DataSource;
import com.oreilly.servlet.MultipartRequest;
public class ResourceCommand extends HttpServlet implements Commands{
private static final long serialVersionUID = 1L;
public void execute(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
//
// JNDI to connect to database
//
Connection conn = null;
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/tia");
conn = ds.getConnection();
//
// Save file(s) temporarily to filesystem
//
MultipartRequest multi = new MultipartRequest(request, "F:", 10*1024*1024);
Enumeration files = multi.getFileNames();
String filename = "";
File f = null;
while(files.hasMoreElements()) {
String name = (String)files.nextElement();
filename = multi.getFilesystemName(name);
String type = multi.getContentType(name);
f = multi.getFile(name);
}
//
// Insert file into database
//
InputStream is = new FileInputStream(f);
String sql = "INSERT INTO resource (`title`, `cat`, `user`, `filename`, `file`, `like`) VALUES (?, ?, ?, ?, ?, ?)"
;
PreparedStatement stmt = conn.prepareStatement(sql);
// Set some Title
stmt.setString(1, "some thing");
// Set some category
stmt.setString(2, ".net");
// Set some user
stmt.setString(3, "sri");
// Set Filename
stmt.setString(4, f.getName());
// Set the data
stmt.setBinaryStream(5, is, (int) f.length());
// Set Likes
stmt.setInt(6, 2);
stmt.executeUpdate();
is.close();
//
// Release connection
//
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) { ; }
stmt = null;
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) { ; }
conn = null;
}
} catch(Exception e) {
System.out.println(e);
}
}
}
And here is the jSP file where i will upload from....
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>UPLOAD FILE page</title></head>
<body>
<form method="post" action="Controller" enctype="multipart/form-data">
<input type="hidden" name="form_action" value="resource" />
<b>File to upload to database:</b>
<input type="file" name="attachment" size="36">
<input type="submit" value="Upload">
</form>
</body></html>
And this is the error i'm getting :(
INFO: Reloading Context with name [/KBCSS] is completed
i am in init
i am about to exit init
i am in dopost
i am in processCommand
i am in processCommand state 2
Oct 10, 2013 11:29:59 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Controller] in context with path [/KBCSS] threw exception
java.lang.NullPointerException
at com.kbcss.controller.Controller.processCommand(Controller.java:69)
at com.kbcss.controller.Controller.doPost(Controller.java:53)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
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:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
and by the way..i have created a Command.java interface here it is.
package com.kbcss.command;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public interface Commands {
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
}
Can any one guide me PLZZZZZZZZZZZZZZZZZZZZ
i'm stuck for a day and Half and have no clue what i'm doing...
This is what happens if u ask an electrical engineering student to do a Java Project !!!!
GREAT GREAT thanks from My side.....
Chances are that commands.get(formAction); is returning null, so command is also null. When you call command.execute(request, response);, you're trying to access something within a null object. That's going to get you a NullPointerException.
Use your print statements to determine what the exact value of formAction is when you get the exception. Then verify that you're putting a key for that string into commands (if it isn't "login", "user", or "resource", since you're already entering those).
One other thing that may be causing the problem is that you need to add class-types to your Map. Change it to:
private Map<String,Command> commands = new HashMap<String,Command>();
After you do that, you shouldn't have to suppress the warning on the Map.

com.google.common.cache.Cache class not found error

I am using Guava 14.0 jar and following is my code
package org.user.module.test;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.Cache;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class test
*/
#WebServlet("/test")
public class test extends HttpServlet {
private static final long serialVersionUID = 1L;
Cache<String, Integer> map;
public test() {
super();
// TODO Auto-generated constructor stub
}
public void init() throws ServletException
{
map=CacheBuilder.newBuilder().
maximumSize(100).
expireAfterAccess(10, TimeUnit.MINUTES).
build();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
String p=request.getParameter("v");
Integer a=map.getIfPresent(p);
if(a==null){
map.put(p, 1);
out.println("Putting The Integer:"+a);
}
else{
map.put(p,a++);
out.println("A is already present and the value is:"+a);
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
Error:
SEVERE: Allocate exception for servlet org.user.module.test.test
java.lang.ClassNotFoundException: com.google.common.cache.Cache at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1701)
at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1546)
at java.lang.Class.getDeclaredFields0(Native Method) at
java.lang.Class.privateGetDeclaredFields(Class.java:2317) at
java.lang.Class.getDeclaredFields(Class.java:1762) at
org.apache.catalina.core.DefaultInstanceManager.populateAnnotationsCache(DefaultInstanceManager.java:276)
at
org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:143)
at
org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:125)
at
org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1136)
at
org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:857)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)
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:987)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
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)
downloaded jar from here Downlaod Link
Link to my project folder(Project name:test2) LINK
Obvious answer is that;
The Google guava jar is not found from the classpath dictated by the application server. The jar should be present in either WEB-INF/classes or WEB-INF/lib. Apache Tomcat also loads common classes from $CATALINA_HOME/lib folder.

Cannot get session id from managed bean

I have this managed bean:
package com.DX_57.SR_57;
/** include default packages for Beans */
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
// or import javax.faces.bean.SessionScoped;
import javax.inject.Named;
/** include package for SHA-256 encryption */
import java.security.NoSuchAlgorithmException;
/** include SQL Packages */
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import javax.annotation.Resource;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
// or import javax.faces.bean.ManagedBean;
import org.DX_57.osgi.CL_27.api.CryptoSHA;
import org.glassfish.osgicdi.OSGiService;
import org.DX_57.osgi.SH_27.api.SessionHandle;
#Named("loginController")
#SessionScoped
public class userCheck implements Serializable {
private String user = null;
private String password = null;
private String error_Message = null;
private String error_Database = null;
public userCheck(){
}
/** Call the Oracle JDBC Connection driver */
#Resource(name="jdbc/Oracle")
private DataSource ds;
/** Call OSGI Bundle SH_27 SessionHandle Library */
/** Use transient in order to disable serialization when calling OSGI Bundle */
#Inject #OSGiService(dynamic=true) transient SessionHandle SH;
public String OSGISHCheckUserDB(String CheckUser) throws SQLException{
return SH.CheckUserDB(CheckUser);
}
public String OSGISHSessionRegister(String User) throws SQLException{
return SH.SessionRegister(User);
}
/** Call OSGI Bundle CL_27 Crypto Library */
/** Use transient in order to disable serialization when calling OSGI Bundle */
#Inject #OSGiService(dynamic=true) transient CryptoSHA CL;
public String OSGICLShaEncryptHash(String CString) throws NoSuchAlgorithmException{
return CL.ShaEncryptHash(CString);
}
/** get the content of the variables from the JSF Login page */
public void setUser(String newValue) {
user = newValue;
}
public String getUser(){
return user;
}
public void setPassword(String newValue) {
password = newValue;
}
public String getPassword(){
return password;
}
public String geterror_Database(){
return error_Database;
}
public String geterror_Message(){
return error_Message;
}
/** get user session id */
FacesContext fCtx = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fCtx.getExternalContext().getSession(false);
String sessionId = session.getId();
/** get user IP address */
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();
String remoteHost = request.getRemoteAddr();
/** compare the user and the password */
public String userCompare() throws NoSuchAlgorithmException, SQLException {
String hash_passwd = null;
String passwdQuery = null;
/** check the password into Oracle using the username */
passwdQuery = OSGISHCheckUserDB(user);
/** convert the plain password in SHA-256 hash */
// hash_passwd = string_hash(password);
/** compare the encrypted passwords */
if (password.equals(passwdQuery)){
/** insert into users session table the time when the user login */
// SessionRegister(user);
/* success */
return "0";
} else {
/* failer */
return "1";
}
}
}
I can successfully compile it with Netbeans. When I deploy it on Glassfish and I open it I get this error stack:
[#|2012-02-04T18:29:36.554+0200|INFO|glassfish3.1.1|org.glassfish.osgijavaeebase|_ThreadID=64;_ThreadName=Thread-2;|deployed bundle com.DX_57.SR_57 [296] at file:/tmp/osgiapp4499752333201324876/|#]
[#|2012-02-04T18:29:48.047+0200|SEVERE|glassfish3.1.1|javax.enterprise.resource.webcontainer.jsf.application|_ThreadID=143;_ThreadName=Thread-2;|Error Rendering View[/home.xhtml]
com.sun.faces.mgbean.ManagedBeanCreationException: Cant instantiate class: com.DX_57.SR_57.userCheck.
at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:193)
at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:102)
at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:244)
at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:116)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at com.sun.el.parser.AstIdentifier.getValue(AstIdentifier.java:99)
at com.sun.el.parser.AstValue.getValue(AstValue.java:158)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:219)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
at javax.faces.component.UIOutput.getValue(UIOutput.java:169)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getValue(HtmlBasicInputRenderer.java:205)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:355)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:164)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1763)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1756)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:401)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1539)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:330)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.NullPointerException
at com.DX_57.SR_57.userCheck.<init>(userCheck.java:103)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at java.lang.Class.newInstance0(Class.java:372)
at java.lang.Class.newInstance(Class.java:325)
at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:188)
... 54 more
|#]
The problem is in these lines:
/** get user session id */
FacesContext fCtx = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fCtx.getExternalContext().getSession(false);
String sessionId = session.getId();
Can you give me some advice how to fix them?
The culprit is here:
...getExternalContext().getSession(false);
Read the javadoc what the boolean argument does.
If the create parameter is true, create (if necessary) and return a session instance associated with the current request. If the create parameter is false return any existing session instance associated with the current request, or return null if there is no such session.

Categories

Resources