WebSocket Error during Handshake Unexpected code 200 - java

I have been using Glassfish 4 as my server.
I am opening a WebSocket connect using this statement:
webSocket = new WebSocket(link);
Where:
link = 'ws://localhost:8080/CollabEdit/Document/file333B1CDF85-DDDC-E411-8299-F82FA8BE8622';
And in the Server File:
#ServerEndpoint(value="/file333B1CDF85-DDDC-E411-8299-F82FA8BE8622", encoders = {MessageEncoder.class}, decoders = {MessageDecoder.class})
Actually, I have been using URL mapping as well, this "file333B1CDF85-DDDC-E411-8299-F82FA8BE8622" is actually is for the user, but at the back end, the control is in the "main.jsp" file.
During the execution, the error generated is:
WebSocket connection to 'ws://localhost:8080/CollabEdit/Document/file333B1CDF85-DDDC-E411-8299-F82FA8BE8622' failed: Error during WebSocket handshake: Unexpected response code: 200
StackTrace of Exception in the GlassFish server:
SEVERE: WebModule[/CollabEdit]Exception starting filter WebSocket filter
java.lang.InstantiationException
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:135)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:5297)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:5909)
at com.sun.enterprise.web.WebModule.start(WebModule.java:691)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:1041)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:1024)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:747)
at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2278)
at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1924)
at com.sun.enterprise.web.WebApplication.start(WebApplication.java:139)
at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122)
at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:291)
at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:352)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:497)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:527)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:523)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:356)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:522)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:546)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1423)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1500(CommandRunnerImpl.java:108)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1762)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1674)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
at org.glassfish.grizzly.http.server.StaticHttpHandler.service(StaticHttpHandler.java:297)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:246)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:744)
Caused by: javax.servlet.ServletException: Web socket server initialization failed.
at org.glassfish.tyrus.servlet.TyrusServletFilter.init(TyrusServletFilter.java:135)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:275)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:131)
... 46 more
Caused by: javax.websocket.DeploymentException: Decoder for type: class com.CollabEdit.Message has not been registered.
Decoder for type: class com.CollabEdit.Message has not been registered.
at org.glassfish.tyrus.core.ErrorCollector.composeComprehensiveException(ErrorCollector.java:83)
at org.glassfish.tyrus.server.TyrusServerContainer.start(TyrusServerContainer.java:144)
at org.glassfish.tyrus.servlet.TyrusServletFilter.init(TyrusServletFilter.java:133)
... 48 more
Message.java:
package com.CollabEdit;
import java.io.IOException;
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 java.io.StringWriter;
import javax.json.Json;
import javax.json.JsonObject;
public class Message {
private JsonObject json;
public Message(JsonObject json) {
this.json = json;
}
public JsonObject getJson() {
return json;
}
public void setJson(JsonObject json) {
this.json = json;
}
#Override
public String toString(){
StringWriter writer = new StringWriter();
Json.createWriter(writer).write(json);
return writer.toString();
}
}
MessageDecoder.java:
package com.CollabEdit;
import java.io.StringReader;
import javax.json.Json;
import javax.json.JsonException;
import javax.json.JsonObject;
import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;
/**
* Decodes a client-sent string into a Message class
*/
public class MessageDecoder implements Decoder.Text<Message>
{
/**
* Transform the input string into a Message
*/
#Override
public Message decode(String string) throws DecodeException {
JsonObject json = Json.createReader(new StringReader(string)).readObject();
return new Message(json);
}
/**
* Checks whether the input can be turned into a valid Message object
* in this case, if we can read it as a Json object, we can.
*/
#Override
public boolean willDecode(String string) {
try{
Json.createReader(new StringReader(string)).read();
return true;
}catch (JsonException ex){
ex.printStackTrace();
return false;
}
}
/**
* The following two methods are placeholders as we don't need to do anything
* special for init or destroy.
*/
#Override
public void init(EndpointConfig config) {
System.out.println("init");
}
#Override
public void destroy() {
System.out.println("destroy");
}
}

Related

NullPointerException when calling EJB method

I am very new to JavaEE. I've lookup a lot of questions about NullPinterException with EJB injection in this site and others, but have no success yet. I can't find the solution for my problem.
I created DynamicWebProject in Eclipse with JPA, JAX-RS, Glassfish Web Extensions facets.
Here is the sctructure of my project (web.xml file is under the glassfish-web.xml file):
I try to call getemployees webservice which deployed to localhost Glassfish server and try to get information about all employees from my database (also at localhost).
Here is the code of my GetEmployees class.
package bean;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import com.google.gson.Gson;
import ejb.EmployeeEJB;
#ApplicationScoped
#ManagedBean
#Path("/getemployees")
public class GetEmployees {
#Inject
EmployeeEJB employeeEJB;
#GET
#Produces("application/json; charset=utf-8")
public Response getAllEmployees() throws Exception {
Gson gson = new Gson();
String jsonString = null;
try {
jsonString = gson.toJson(employeeEJB.getAll());
} catch (Exception e) {
e.printStackTrace();
}
return Response.status(200).entity(jsonString).build();
}
}
I created Managed and Session beans. I made Managed bean from my GetEmployees RESTful webservice class. Is it correct?
EmployeeEJB is the session bean:
package ejb;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import entity.Employee;
#LocalBean
#Stateless
public class EmployeeEJB {
#PersistenceContext
EntityManager em;
public void saveEmployee(Employee employee) {
em.merge(employee);
}
public void deleteEmployee(Employee employee) {
em.remove(employee);
}
public List<Employee> getAll() {
Query query = em.createQuery("SELECT emp FROM Employee emp", Employee.class);
List<Employee> emp = (List<Employee>) query.getResultList();
return emp;
}
}
Here is my persistence.xml file. JDBC connection pool and JDBC resource created in Glassfish admin console. Connection to database is Ok.
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="FirstDynamicWebProject">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/second_attempt_hibernate</jta-data-source>
<class>entity.Docstatus</class>
<class>entity.Doctype</class>
<class>entity.Document</class>
<class>entity.Employee</class>
<class>entity.Mailorder</class>
<class>entity.Mailorderstatus</class>
</persistence-unit>
</persistence>
NullPointerException occur when I try to call an employeeEJB.getAll() method in GetEmployees class:
2017-04-10T00:59:07.063+0500|Severe: java.lang.NullPointerException
at bean.GetEmployees.getAllEmployees(GetEmployees.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)
I think the injection of EmployeeEJB is not correct, but have no ideas how to win it.
I guess the problem is that you are using the wrong package for #ApplicationScoped. And you don't need the #ManagedBean there I think.
You are using:
import javax.faces.bean.ApplicationScoped;
Try the following:
import javax.enterprise.context.ApplicationScoped;
See also:
Why are there different bean management annotations

HTTP Status 500 - Internal Server Error in JSP using GlassFish Server

I am full beginner in JSP and Java. When I try to open a web application developed in Java, this error shows up when I try to register an account in the system. The interface of the system displayed correctly. However, everytime I try to key in some data it pops up the error.
Error Screenshot
The Netbeans had connected to Oracle database and the database is start. I have no idea what causing this, I checked the GlassFish Server Logs and still could not find out the problem. Below are the GlassFish server logs:
Warning: StandardWrapperValve[CreateServlet]: Servlet.service() for servlet CreateServlet threw exception
java.lang.NullPointerException
at g.RegisterUser.register(RegisterUser.java:14)
at g.CreateServlet.doGet(CreateServlet.java:37)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)
The problem start at CreateServlet.java. Here are the code in CreateServlet.java
package g;
import java.io.IOException;
import java.io.PrintWriter;
import java.rmi.Naming;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CreateServlet extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String username=request.getParameter("username");
String password=request.getParameter("password");
String repassword=request.getParameter("repassword");
String amoun=request.getParameter("amount");
double amount=Double.parseDouble(amoun);
String adderess=request.getParameter("adderess");
String ph=request.getParameter("phone");
double phone=Double.parseDouble(ph);
//double mname=Double.parseDouble(num);
//String country=request.getParameter("country");
int status=RegisterUser.register(username, password, repassword, amount, adderess,phone);
if(status>0){
out.print("WELCOME! YOUR ACCOUNT HAS OPENED");
RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
rd.include(request, response);
}
else{
out.print("Sorry,Registration failed. please try later");
RequestDispatcher rd=request.getRequestDispatcher("MyHtml.html");
rd.include(request, response);
}
out.close();
}
}
The RegisterUser class code:
package g;
import java.sql.*;
public class RegisterUser {
static int status=0;
//int accountno=1;
public static int register(String username,String password,String repassword,double amount,String adderess,double phone){
//public static int register(String email,String password,String gender,String country,String name){
Connection con=GetCon.getCon();
PreparedStatement ps;
try {
ps = con.prepareStatement("Insert into NEWACCOUNT values(?,?,?,?,?,?,?)");
int nextvalue1=GetCon.getPrimaryKey();
ps.setInt(1,nextvalue1);
ps.setString(2,username);
ps.setString(3,password);
ps.setString(4,repassword);
ps.setDouble(5,amount);
ps.setString(6,adderess);
ps.setDouble(7,phone);
status=ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return status;
}
}
And here is the MyListener.java code, here had the java.lang.NullPointerException at line 13 as well.
package g;
import javax.servlet.*;
import java.sql.*;
public class MyListener implements ServletContextListener{
public void contextInitialized(ServletContextEvent arg0) {
int status=0;
Connection con=null;
try{
con=GetCon.getCon();
PreparedStatement ps1=con.prepareStatement("Select * from NEWACCOUNT");
try{
status=ps1.executeUpdate();
}
catch(Exception e)
{e.printStackTrace();
status=2;
System.out.println("my staus is 1111111"+status);
}
if(status==0)
{System.out.println("your table name already exist"+status);}
else if(status==2)
{System.out.println("else if part table does not exist new table has created"+status);
PreparedStatement ps3=con.prepareStatement("CREATE SEQUENCE javatpointnewaccount MINVALUE 1 MAXVALUE 999999999999 INCREMENT BY 1 START WITH 1 NOCACHE NOORDER NOCYCLE");
ps3.executeUpdate();
PreparedStatement ps=con.prepareStatement("CREATE TABLE NEWACCOUNT(ACCOUNTNO NUMBER,USERNAME VARCHAR2(4000),PASSWORD VARCHAR2(4000),REPASSWORD VARCHAR2(4000),AMOUNT NUMBER,ADDERESS VARCHAR2(4000),PHONE NUMBER,PRIMARY KEY (ACCOUNTNO))");
ps.executeUpdate();
}
else{System.out.println("else part "+status);
}}
catch(Exception e){e.printStackTrace();}
}
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("project undeployed");
}
}
Thank you for reading this and appreciate if anyone could help.

Using Qualifiers with Jersey 2.0 and CDI

I am reading through Beginning J2EE 7 - Antonio Gonclaves and going through the source code, I have encountered an exception "org.glassfish.hk2.api.UnsatisfiedDependencyException" which I'm finding hard to solve. Without any qualifiers the application works fine. I'm using Netbeans 7.3.1 and Glassfish 4.0. Below is my source code and exception log
These are my service classes which I'm using #Qualifiers to differentiate
#Stateless
#ISBNAlt
public class ISBNGenerator implements INumberGenerator{
#Override
public String generateNumberr() {
return "ISBN generated";
}
}
Second service class
#Stateless
#ISBNDef
public class ISSNGenerator implements INumberGenerator{
#Override
public String generateNumberr() {
return "Working version 2";
}
}
The resource class
#ManagedBean
#RequestScoped
#Path("/test")
public class TestClass {
#Inject #ISBNAlt
private INumberGenerator ng;
#Produces(MediaType.TEXT_PLAIN)
#GET
public String getValue()
{
return ng.generateNumberr();
}
}
and i use this class for adding resource classes
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
/**
*
* #author naphlin
*/
#ApplicationPath("webresource")
public class ApplicationConfig extends Application{
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<Class<?>>();
// following code can be used to customize Jersey 2.0 JSON provider:
try {
Class jsonProvider = Class.forName("org.glassfish.jersey.jackson.JacksonFeature");
// Class jsonProvider = Class.forName("org.glassfish.jersey.moxy.json.MoxyJsonFeature");
// Class jsonProvider = Class.forName("org.glassfish.jersey.jettison.JettisonFeature");
resources.add(jsonProvider);
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
addRestResourceClasses(resources);
return resources;
}
/**
* Do not modify addRestResourceClasses() method.
* It is automatically re-generated by NetBeans REST support to populate
* given list with all resources defined in the project.
*/
private void addRestResourceClasses(Set<Class<?>> resources) {
resources.add(helpers.TestClass.class);
}
}
After deploying my application and invoking the REST endpoint, i get this exception
Info: Initiating Jersey application, version Jersey: 2.0 2013-05-03 14:50:15...
Warning: StandardWrapperValve[config.ApplicationConfig]: Servlet.service() for servlet config.ApplicationConfig threw exception
org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=INumberGenerator,parent=TestClass,qualifiers={#annotations.ISBNAlt()}),position=-1,optional=false,self=false,unqualified=null,1495563497)
at org.jvnet.hk2.internal.ThreeThirtyResolver.resolve(ThreeThirtyResolver.java:74)
at org.jvnet.hk2.internal.ClazzCreator.resolve(ClazzCreator.java:191)
at org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:214)
at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:311)
at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:448)
at org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:157)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2204)
at org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:579)
at org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:566)
at org.glassfish.jersey.internal.inject.Injections.getOrCreate(Injections.java:172)
at org.glassfish.jersey.server.model.MethodHandler$ClassBasedMethodHandler.getInstance(MethodHandler.java:185)
at org.glassfish.jersey.server.internal.routing.PushMethodHandlerRouter.apply(PushMethodHandlerRouter.java:105)
at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:118)
at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:121)
at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:121)
at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:121)
at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:102)
at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:62)
at org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:215)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:198)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:946)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:323)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:372)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:335)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:218)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:745)
Any
Works on my machine ;o) No, actually I reproduced your code quickly with JBoss Forge. You can run the following JBoss Forge script if you want :
$ project-new --named testrest
$ rest-setup
$ cdi-setup
$ cdi-new-qualifier --named ISBNAlt --targetPackage org.testrest.util
$ cdi-new-qualifier --named ISBNDef --targetPackage org.testrest.util
$ java-new-interface --named INumberGenerator2 --targetPackage org.testrest.service
$ ejb-new-bean --named ISBNGenerator
$ ejb-new-bean --named ISSNGenerator
$ faces-setup
I deployed it on WildFly, and it's working fine. BTW, as simplification, you don't need #ManagedBean and #RequestScoped on your REST endpoint. Try to get rid of it and re-deploy on GlassFish. You can also give it a try on WildFly first.

Is it necessary to add an EJB module as a library in a Web module to inject session beans

I created a new Java EE 6 Enterprise-Application in Netbeans 7.4. with Glassfish 4.0 application server. So I have three Projects:
EAR
EJB
WAR
when I inject session bean from the EJB module into the managed bean of Web(WAR) module, it generates the following error
WARNING: /login.xhtml #16,131 value="#{loginBean.username}": Target Unreachable, identifier 'loginBean' resolved to null
javax.el.PropertyNotFoundException: /login.xhtml #16,131 value="#{loginBean.username}": Target Unreachable, identifier 'loginBean' resolved to null
at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:100)
at org.primefaces.renderkit.InputRenderer.findImplicitConverter(InputRenderer.java:170)
at org.primefaces.renderkit.InputRenderer.findConverter(InputRenderer.java:190)
at org.primefaces.renderkit.InputRenderer.getConvertedValue(InputRenderer.java:196)
at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1046)
at javax.faces.component.UIInput.validate(UIInput.java:976)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1249)
at javax.faces.component.UIInput.processValidators(UIInput.java:712)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
at javax.faces.component.UIForm.processValidators(UIForm.java:253)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
at org.primefaces.component.layout.Layout.processValidators(Layout.java:246)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1195)
at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at filters.AuthFilter.doFilter(AuthFilter.java:44)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:744)
Caused by: javax.el.PropertyNotFoundException: Target Unreachable, identifier 'loginBean' resolved to null
at com.sun.el.parser.AstValue.getTarget(AstValue.java:174)
at com.sun.el.parser.AstValue.getType(AstValue.java:86)
at com.sun.el.ValueExpressionImpl.getType(ValueExpressionImpl.java:201)
at org.jboss.weld.el.WeldValueExpression.getType(WeldValueExpression.java:93)
at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:98)
... 51 more
And during deployment the Glassfish server also generates the following error
SEVERE: Exception while loading the app
SEVERE: Undeployment failed for context /ZTE-WMS-war
SEVERE: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: java.lang.RuntimeException: java.lang.NoClassDefFoundError: Lcom/wms/sessions/UseraccountManager;
I wrote the managed bean class(LoginBean) as follows
package com.wms.managedbeans;
import com.wms.sessions.UseraccountManager;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.http.HttpSession;
//#Named("loginBean")
#ManagedBean(name="loginBean")
#RequestScoped
public class LoginBean implements Serializable {
private static final long serialVersionUID = 1L;
private String password;
private String message, username;
#EJB
private UseraccountManager uam;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String uname) {
this.username = uname;
}
public String getUser() {
System.out.println(Util.getUserId());
return Util.getUserId();
}
public String getUserType(){
HttpSession session = Util.getSession();
if ( session != null )
return (String) session.getAttribute("userType");
else
return null;
}
public String login() {
String userType = uam.validateUser(username, password);
HttpSession session = Util.getSession();
if (userType.equals("unknown")){
FacesContext.getCurrentInstance().addMessage(
null,
new FacesMessage(FacesMessage.SEVERITY_WARN,
"Invalid Login!",
"Please Try Again!"));
// invalidate session, and redirect to other pages
//message = "Invalid Login. Please Try Again!";
return "login";
}
else{
// get Http Session and store username
session.setAttribute("username", username);
session.setAttribute("userType",userType);
if (userType.equals("administrator"))
return "admin/adminHome?faces-redirect=true";
else if(userType.equals("warehouseman"))
return "WM/wmHome?faces-redirect=true";
else if(userType.equals("employee"))
return "emp/empHome?faces-redirect=true";
else
return "man/manHome?faces-redirect=true";
}
}
public String logout() {
HttpSession session = Util.getSession();
session.invalidate();
return "/login?faces-redirect=true";
}
}
When I added the "EJB jar" into the WEB(WAR) module as a library it works perfectly.
Now my question is, is it mandatory to add the EJB jar as a library in-order to inject session beans into managed beans. if there is any other way(s) please help me

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