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.
Related
I am new to JAVA EE, and I am working by myself on a project. Now, I want to deploy sending email function on a button click. In detail, I want my customer to submit their information and when they click on submit button, an email of receipt should be sent to their email. I will show my coding below.
First of all, here are my source files that are related to what I am doing.
EmailUtility.java
package com.jason;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EmailUtility {
public static void sendEmail(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message) throws AddressException,
MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(message);
// sends the e-mail
Transport.send(msg);
}
}
And here is my PaymentServlet.java
package com.jason;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.servlet.ServletContext;
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 javax.servlet.http.HttpSession;
import com.jason.storeServlet.Command;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.Authenticator;
/**
* Servlet implementation class paymentServlet
*/
#WebServlet("/paymentServlet")
public class paymentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
int quantity;
String color;
double size;
double price;
String productId;
double totalPrice;
double tax;
DecimalFormat decimalFormat = new DecimalFormat("#.##");
public enum Command {Buy,Submit,Confirm}
private String host;
private String port;
private String user;
private String pass;
public void init() {
ServletContext context = getServletContext();
host = context.getInitParameter("host");
port = context.getInitParameter("port");
user = context.getInitParameter("user");
pass = context.getInitParameter("pass");
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String action = request.getParameter("action");
Command command = Command.valueOf(action);
System.out.println(action);
System.out.println("get");
switch(command) {
case Buy:
this.buynow(request, response);
break;
case Submit:
this.submit(request, response);
break;
case Confirm:
this.confirm(request, response);
break;
default:
break;
}
}
private void confirm(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
HttpSession session = request.getSession();
response.sendRedirect(request.getContextPath() + "/receipt.jsp");
session.setAttribute("date", date());
Email(request, response);
}
private String date(){
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy");
return sdf.format(new Date());
}
protected void Email(HttpServletRequest request, HttpServletResponse response){
String recipient = "some email";
String subject = "Receipt for your order";
String content = "We thank you for your purchase.";
String resultMessage = "";
try {
EmailUtility.sendEmail(host, port, user, pass, recipient, subject,
content);
resultMessage = "The e-mail was sent successfully";
} catch (Exception ex) {
ex.printStackTrace();
resultMessage = "There were an error: " + ex.getMessage();
}
}
}
And here is web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>host</param-name>
<param-value>smtp.gmail.com</param-value>
</context-param>
<context-param>
<param-name>port</param-name>
<param-value>587</param-value>
</context-param>
<context-param>
<param-name>user</param-name>
<param-value>some email</param-value>
</context-param>
<context-param>
<param-name>pass</param-name>
<param-value>some password</param-value>
</context-param>
</web-app>
So the way it should work is that when a customer clicks on Confirm button it should deploy the confirm method which calls email method.
Here is the error I am getting:
org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [com.jason.paymentServlet] in context with path [/Practice4_Shopping] threw exception [Servlet execution threw an exception] with root cause
java.lang.ClassNotFoundException: javax.mail.Authenticator
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1269)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1104)
at com.jason.paymentServlet.Email(paymentServlet.java:256)
at com.jason.paymentServlet.confirm(paymentServlet.java:239)
at com.jason.paymentServlet.doGet(paymentServlet.java:84)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:475)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:651)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:498)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:796)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1374)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
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");
}
}
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
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.
I create a singleton class and calling a method inside it. I use spring mvc SimpleJdbcTemplate for retrieving data from database, but I get NullPointerException. Code I wrote is:
package in.dewsolutions.jc.utils;
import in.dewsolutions.jc.dao.ReportsDAO;
import in.dewsolutions.jc.dto.ReportsView;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
public class SingletonFilterData {
private static final Logger logger = Logger.getLogger(SingletonFilterData.class);
#Autowired
private SimpleJdbcTemplate simpleJdbcTemplate;
#Autowired
public void setDataSource(DataSource dataSource) {
this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
}
private SingletonFilterData() // private defaul constructor
{
}
private static SingletonFilterData reference = null;
public static SingletonFilterData getInstance() {
if (reference == null) {
synchronized (SingletonFilterData.class) {
if (reference == null) {
reference = new SingletonFilterData();
}
}
}
return reference;
}
public List<ReportsView> findManuFacturer() {
// TODO Auto-generated method stub
List<ReportsView> manufacturer = new ArrayList<ReportsView>();
ReportsView rv = new ReportsView();
rv.setProductName("None");
rv.setProductId(0);
manufacturer.add(rv);
String query = "SELECT * FROM manufacturer ORDER BY name";
ParameterizedRowMapper<ReportsView> mapper = new ParameterizedRowMapper<ReportsView>() {
public ReportsView mapRow(ResultSet rs, int rowNum)
throws SQLException {
ReportsView reportsView = new ReportsView();
reportsView.setProductName(rs.getString("name"));
reportsView.setProductId(rs.getLong("id_manufacturer"));
return reportsView;
}
};
manufacturer.addAll(simpleJdbcTemplate.query(query, mapper));
return manufacturer;
}
The exception I get is:
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.displaytag.filter.ResponseOverrideFilter.doFilter(ResponseOverrideFilter.java:125)
root cause
java.lang.NullPointerException
in.dewsolutions.jc.utils.SingletonFilterData.findManuFacturer(SingletonFilterData.java:77)
in.dewsolutions.jc.controller.ReportsController.filterQuantity(ReportsController.java:169)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:597)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.displaytag.filter.ResponseOverrideFilter.doFilter(ResponseOverrideFilter.java:125)
note The full stack trace of the root cause is available in the Apache Tomcat/6.0.29 logs.
How can I remove the Exception?
Using new SingletonFilterData() doesn't invoke the autowiring, so simpleJdbcTemplate remains null.
Instead of implementing getInstance(), you can configure Spring so that SingletonFilterData is a singleton and injected into ReportsController.