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

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.

Related

I want to pass variables to another page using the session storage and it give me java.lang.IllegalStateException

I'm pretty new to programming and i encountered this problem i have search internet and couldn't find the answer i was looking for. Hope you can help me here. Thanks!
I'm trying to pass 2 variables which is the name and custid.
(i'm using mysql workbench as my database).
I'm guessing my error is something to do with.
String email=request.getParameter("email");
String password=request.getParameter("password");
here's my code:
#WebServlet("/login")
public class loginServlet extends HttpServlet{
#Resource(name="jdbc/eg3752")
private DataSource usercatalogue;
#Override
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
String email=request.getParameter("email");
String password=request.getParameter("password");
Connection connection=null;
Statement statement=null;
ResultSet resultset=null;
String login="SELECT * FROM customer where email='"+email+"'";
try
{
connection=usercatalogue.getConnection();
statement=connection.createStatement();
resultset=statement.executeQuery(login);
while(resultset.next())
{
// check if password is same in the database
if(password.equals(resultset.getString("password")))
{
HttpSession session =request.getSession();
session.setAttribute("name", resultset.getString("fullname"));
session.setAttribute("custid", resultset.getString("customerId"));
response.sendRedirect(this.getServletContext().getContextPath()+"/search.html");
}
else
{
response.sendRedirect(this.getServletContext().getContextPath() + "/login.html");
}
}
}
catch(Exception e)
{
e.printStackTrace();
System.err.println(e.getMessage());
}
}
}
and this is the error on the GlassFish Server 4
Severe: java.lang.IllegalStateException
at org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:518)
at com.aleksi.loginServlet.doPost(loginServlet.java:58)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
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: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)
You did not include the "caused by" sections of the stack trace, which are the important part.
An IllegalStateException on a sendRedirect() has to do with the HTTP protocol and occurs when the response to the client has already been committed. This will usually happen when either the response buffer has reached max size or someone has called flush() explicitly or written something to the output stream and caused the response to be committed.
After calling sendRedirect() add return; and then try.

NullPointerException - Attempting to return JSON from Web Service

Please be patient as this is my first time learning about how to use web services.
I am trying to build a simple system that when given a parameter (String id), the web service returns a JSON object. I am somewhat following this codebase as a guide https://o7planning.org/en/11207/simple-crud-example-with-java-restful-web-service
Problem: When I run the service and go the URL http://localhost:8080/RESTfulServiceLIT_war_exploded/users/{id}, I receive a NullPointer exception in the glassfish log. It should simply display the JSON object relative to the user object returned from the id.
Here is the UserDAO class code
import java.util.*;
public class UserDAO {
private static final Map<String, User> userMap = new HashMap<String, User>();
static {
initUsers();
}
private static void initUsers() {
User u1 = new User("K1", "Student 1", "Student");
User u2 = new User("K2", "Student 2", "Student");
User u3 = new User("K3", "Student 3", "Student");
User u4 = new User("S1", "Staff 1", "Staff");
User u5 = new User("S2", "Staff 2", "Staff");
User u6 = new User("S3", "Staff 3", "Staff");
userMap.put(u1.getId(), u1);
userMap.put(u2.getId(), u2);
userMap.put(u3.getId(), u3);
userMap.put(u4.getId(), u4);
userMap.put(u5.getId(), u5);
userMap.put(u6.getId(), u6);
}
public static User getUser(String id) {
return userMap.get(id);
}
public static List<User> getAllUsers() {
Collection<User> c = userMap.values();
List<User> list = new ArrayList<User>();
list.addAll(c);
return list;
}
List<User> list;
}
Here is the Main class that has the rest service
import javax.print.attribute.standard.Media;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.MediaType;
// The Java class will be hosted at the URI path "/helloworld"
#Path("/users")
public class Main {
#GET
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
#Path("/{id}")
public User getUser(#PathParam("id") String id) {
return UserDAO.getUser(id);
}
// #GET
// #Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
// #Path{"/all"}
// public List<User> getUsers_JSON(){
// List<User> listOfUsers = UserDAO.getAllUsers();
// return listOfUsers;
// }
}
Here is the server log
[2018-05-22T20:09:17.937+0100] [glassfish 4.1] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=35 _ThreadName=http-listener-1(3)] [timeMillis: 1527016157937] [levelValue: 900] [[
StandardWrapperValve[MyApplication]: Servlet.service() for servlet MyApplication threw exception
java.lang.NullPointerException
at org.eclipse.persistence.jaxb.rs.MOXyJsonProvider.writeTo(MOXyJsonProvider.java:944)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(WriterInterceptorExecutor.java:265)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:250)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:106)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:86)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1130)
at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:683)
at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:424)
at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:414)
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:312)
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:292)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1139)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:460)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:386)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:334)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
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:748)
]]
User class
public class User {
private String id;
private String name;
private String type;
User(){}
User(String id, String name, String type){
this.setId(id);
this.setName(name);
this.setType(type);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
The URL:
http://localhost:8080/RESTfulServiceLIT_war_exploded/users/{id}
is a path specification used by Jersey to state how you can access data. If you simply typed that string into your web browser, then you will get a NullPointerException.
What happens when you type:
http://localhost:8080/RESTfulServiceLIT_war_exploded/users/K1
?
I resolved the same issue today. Issue came when you called bean method in rest api.
so create beans.xml file in WEB-INF folder
include the following
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
bean-discovery-mode="all">
</beans>

Why do i get an EJB java.rmi.MarshalException: CORBA MARSHAL exception?

I'm trying to add items using a JSP page which has a couple of images too. I declared the variables to retrieve images as strings so i can get the URL and store the url in the database.
I'm using EJB and JPA for database purposes.
my code for the servlet
ItemDetails id;
ItemBeanRemote ib;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id");
String name = request.getParameter("name");
double price = Double.valueOf(request.getParameter("price"));
String imgurl = request.getParameter("imgurl");
String imgurl2 = request.getParameter("imgurl2");
String location = request.getParameter("loc");
id = new ItemDetails(id, name, price, imgurl, imgurl2, location);
ib.addItem(id);
response.sendRedirect("View.jsp");
}
#Override
public void init() {
try {
Context initial = new InitialContext();
ib = (ItemBeanRemote) initial.lookup("itembean");
} catch (Exception ex) {
System.err.println("Caught an exception:");
ex.printStackTrace();
}
//ejb class that has the code to the addItem method
#Override
public void addEvent(ItemDetails details) {
try {
tblItem utt = new tblItem(details.getItemID(),details.getItemName(),
details.getPrice(),details.getImgUrl(),details.getImgUrl2(),details.getLocation());
em.persist(utt);
} catch (Exception ex) {
throw new EJBException(ex);
}
//item details is a class is a POJO with getters and setters
//tblItem is the java class that was created using an entity manager which has auto generated code from JPA.
And the exception
javax.ejb.EJBException: java.rmi.MarshalException: CORBA MARSHAL 1330446343 No; nested exception is:
org.omg.CORBA.MARSHAL: ----------BEGIN server-side stack trace----------
org.omg.CORBA.MARSHAL: FINE: 00810007: Underflow in BufferManagerReadStream after last fragment in message vmcid: OMG minor code: 7 completed: No
at com.sun.proxy.$Proxy154.endOfStream(Unknown Source)
at com.sun.corba.ee.impl.encoding.BufferManagerReadStream.underflow(BufferManagerReadStream.java:122)
at com.sun.corba.ee.impl.encoding.CDRInputStream_1_1.grow(CDRInputStream_1_1.java:111)
at com.sun.corba.ee.impl.encoding.CDRInputStream_1_2.alignAndCheck(CDRInputStream_1_2.java:126)
at com.sun.corba.ee.impl.encoding.CDRInputStream_1_0.read_long(CDRInputStream_1_0.java:433)
at com.sun.corba.ee.impl.encoding.CDRInputStream_1_0.readValueTag(CDRInputStream_1_0.java:1672)
at com.sun.corba.ee.impl.encoding.CDRInputStream_1_0.read_value(CDRInputStream_1_0.java:918)
at com.sun.corba.ee.impl.encoding.CDRInputObject.read_value(CDRInputObject.java:518)
at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl$14.read(DynamicMethodMarshallerImpl.java:383)
at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl.readArguments(DynamicMethodMarshallerImpl.java:450)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:171)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatchToServant(ServerRequestDispatcherImpl.java:528)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatch(ServerRequestDispatcherImpl.java:199)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequestRequest(MessageMediatorImpl.java:1549)
at com.sun.corba.ee.impl.protocol.SharedCDRClientRequestDispatcherImpl.marshalingComplete(SharedCDRClientRequestDispatcherImpl.java:119)
at com.sun.corba.ee.impl.protocol.ClientDelegateImpl.invoke(ClientDelegateImpl.java:258)
at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.privateInvoke(StubInvocationHandlerImpl.java:198)
at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.invoke(StubInvocationHandlerImpl.java:150)
at com.sun.corba.ee.impl.presentation.rmi.codegen.CodegenStubBase.invoke(CodegenStubBase.java:226)
at com.olympics2016.beans.__EventBeanRemote_Remote_DynamicStub.addEvent(com/olympics2016/beans/__EventBeanRemote_Remote_DynamicStub.java)
at com.olympics2016.beans._EventBeanRemote_Wrapper.addEvent(com/olympics2016/beans/_EventBeanRemote_Wrapper.java)
at com.olympics2016.servlets.AddEventServlet.doPost(AddEventServlet.java:42)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
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:415)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
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:201)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
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:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
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:565)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:745)
----------END server-side stack trace---------- vmcid: OMG minor code: 7 completed: No
Marshal Exception can occur due to one of the reasons as below :
1) when remote method call is done and no marshaling is done of Java Object and thus the argument or return value will not reach to remote method or to server.
2) If the protocol we are using in RMI is of different versions at sender and receivers side.

I am a getting a java.lang.NullPointerException when using the remove(T entity) method for JPA

kindly help me out with this NullPointerException error i am getting while trying to use the remove(T entity) method in JPA
Here is my code
ControllerServlet
}else if (userPath.equals("/confirm_delete")){
String userid = request.getParameter("userToDelete");
int usrId = Integer.valueOf(userid);
SystemusersFacade usertoDelete = new SystemusersFacade();
Systemusers user = new Systemusers();
user = systemusersFacade.find(usrId);
usertoDelete.remove(user);
userPath ="/view_users";
SystemusersFacade extends AbstractFacade that contains the remove(T entity) method)
remove(T entity) method
public void remove(T entity) {
System.out.println(entity);
getEntityManager().remove(getEntityManager().merge(entity));
}
Below is the NullPointerException i am getting
Info: theBankingGuide was successfully deployed in 13,022 milliseconds.
Info: WebModule[null] ServletContext.log():ControllerServlet:
Info: entity.Systemusers[ userId=1 ]
Warning: StandardWrapperValve[ControllerServlet]: Servlet.service() for servlet ControllerServlet threw exception
java.lang.NullPointerException
at session.AbstractFacade.remove(AbstractFacade.java:35)
at controller.ControllerServlet.doPost(ControllerServlet.java:212)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
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 org.glassfish.tyrus.servlet.TyrusServletFilter.doFilter(TyrusServletFilter.java:295)
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:415)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
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:201)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
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:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
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:565)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:745)
I am sure that the entity is not passed as a null because when i use a System.out.Print, it gives me a value as you see in the log above
Info: entity.Systemusers[ userId=1 ]
I have also checked the debugger and the entity variable exits with the following parameters
entity Systemusers #1232
Static
_persistence_cacheKey HardCacheWeakIdentityMap$ReferenceCacheKey #1280
_persistence_fetchGroup null
_persistence_href null
_persistence_listener AttributeChangeListener #1281
_persistence_primaryKey Integer ObjectFieldVariable _persistence_primaryKey
_persistence_relationshipInfo null
_persistence_session null
_persistence_shouldRefreshFetchGroup boolean false
adsCollection IndirectList size = 0
mmtransinfoCollection IndirectList size = 0
securitiesinfoCollection IndirectList size = 0
systemUsersTime Date 02-Jan-2015 20:09:52
userEmail String jonahkayizzi#gmail.com
userId Integer 1
userName String "Jonah"
userPassword String "0xgl#kylZ"
userType String "Manager"
I also tried creating my custome delete function in the SystemusersFacade and i got the same error.
Please help out
EDIT
package session;
import entity.Systemusers;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* #author Jonah
*/
#Stateless
public class SystemusersFacade extends AbstractFacade<Systemusers> {
#PersistenceContext(unitName = "theBankingGuidePU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public SystemusersFacade() {
super(Systemusers.class);
}
}
package session;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void remove(T entity) {
System.out.println(entity);
getEntityManager().remove(getEntityManager().merge(entity));
}
}
SystemusersFacade usertoDelete = new SystemusersFacade() is your problem (ignoring strange name, maybe a copy/paste error). Since you instantiate it using new, you are bypassing container management so the annotations are not processed. You need to inject the bean into the class that uses it. Use something like this
#EJB
private SystemusersFacade systemusersFacade;
...
String userid = request.getParameter("userToDelete");
int usrId = Integer.valueOf(userid);
Systemusers user = systemusersFacade.find(usrId);
systemusersFacade.remove(user);

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

Categories

Resources