Servlet threw java.lang.NullPointerException - java

I am using netbeans 7.4 with hibernate 3.6.10 to develop a web application.
I have surfed the net and read quite a number of site, I believe the error is caused by wrong configuration between hibernate and my servlet. As I am new to jsp, servlet and hibernate, I cannot figure out what have I did wrongly. Hope you guys can solve this problem.
Here comes the code.
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/webasgdvd?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<mapping class="cart.hibernate.PaymentMethod" package="cart.hibernate" resource="cart/hibernate/PaymentMethod.hbm.xml"/>
</session-factory>
</hibernate-configuration>
PaymentMethod.java
package cart.hibernate;
public class PaymentMethod {
private int paymentMethodId;
private String paymentMethod;
public PaymentMethod(){
}
public PaymentMethod(String method){
this.paymentMethod = method;
}
public int getPaymentMethodId() {
return paymentMethodId;
}
public String getPaymentMethod(){
return paymentMethod;
}
public void setPaymentMethodId(int id) {
this.paymentMethodId = id;
}
public void setPaymentMethod(String method){
this.paymentMethod = method;
}
}
PaymentMethod.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="cart.hibernate.PaymentMethod" table="payment_method">
<meta attribute="class-description">
This class contains the payment method detail.
</meta>
<id name="paymentMethodId" type="int" column="payment_method_id">
<generator class="native"/>
</id>
<property name="PaymentMethod" column="payment_method" type="string"/>
</class>
</hibernate-mapping>
ManagePaymentMethod.java
package cart.hibernate;
import java.util.List;
import java.util.Iterator;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ManagePaymentMethod {
private static SessionFactory factory;
public Integer addPaymentMethod(String methodName) {
Session session = factory.openSession(); // Error occur here <--
Transaction tx = null;
Integer paymentMethodId = null;
try {
tx = session.beginTransaction();
PaymentMethod payMethod = new PaymentMethod(methodName);
paymentMethodId = (Integer) session.save(payMethod);
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return paymentMethodId;
}
}
addPaymentMethodServlet.java
package cart.hibernate;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class addPaymentMethodServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String method = request.getParameter("paymentMethod");
try {
ManagePaymentMethod manager = new ManagePaymentMethod();
Integer paymentMethodId = manager.addPaymentMethod(method);
// Receive from a jsp page and I have checked the value of method is correct
out.print("..."); // html page
} finally {
out.close();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}
}
When the servlet is called, exception is caught. The following is the error log
Nov 22, 2013 6:55:22 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [addPaymentMethodServlet] in context with path [/eShop] threw exception
java.lang.NullPointerException
at cart.hibernate.ManagePaymentMethod.addPaymentMethod(ManagePaymentMethod.java:93)
at cart.hibernate.addPaymentMethodServlet.processRequest(addPaymentMethodServlet.java:46)
at cart.hibernate.addPaymentMethodServlet.doPost(addPaymentMethodServlet.java:90)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
I have tested the addPaymentMethod() by executing a main() method in the ManagePaymentMethod.java. The addPaymentMethod() run correctly.
Moreover, the value that passed from jsp to addPaymentMethodServlet.java is correct.
If you have more details, please let me know.

in the line
Session session = factory.openSession();
facotory is null
You declared
private static SessionFactory factory;
And never initialized and using in addPaymentMethod method.

Related

Cannot upload my Web Applicartion in Jboss7 EAP7 EAP

I must to test this web app, but when I try to deploy on JBoss 7 EAP this is the error, maybe I forgot something?
This is the exception that the application throws:
Cannot upload deployment: {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"WebAppGuestbooks.war\".INSTALL" =>
"org.jboss.msc.service.StartException in service jboss.deployment.unit.\"WebAppGuestbooks.war\".INSTALL: WFLYSRV0153:
Failed to process phase INSTALL of deployment \"WebAppGuestbooks.war\" Caused by:
org.jboss.as.server.deployment.DeploymentUnitProcessingException: WFLYEE0041: Component class it.matteo.nesea.ejb.GuestDao for
component GuestDao has errors:
WFLYJPA0033: Can't find a persistence unit named null in deployment
\"WebAppGuestbooks.war\""},"WFLYCTL0180: Services with missing/unavailable dependencies" =>
["jboss.deployment.unit.\"WebAppGuestbooks.war\".weld.weldClassIntrospector is missing
[jboss.deployment.unit.\"WebAppGuestbooks.war\".beanmanager]","jboss.deployment.unit.\"WebAppGuestbooks.war\".batch.environment
is missing [jboss.deployment.unit.\"WebAppGuestbooks.war\".beanmanager]"]}
This is my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="GuestbookPU" transaction-type="JTA">
<class>it.matteo.nesea.dao.jpa</class>
<properties>
<property name="javax.persistence.jdbc.url" value="$objectdb/db/guests.odb"/>
<property name="javax.persistence.jdbc.user" value="admin"/>
<property name="javax.persistence.jdbc.password" value="admin"/>
</properties>
</persistence-unit>
</persistence>
this is the Ejb GuestDAO:
package it.matteo.nesea.ejb;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import it.matteo.nesea.dao.jpa.Guest;
#Stateless
public class GuestDao {
// Injected database connection:
#PersistenceContext private EntityManager em;
// Stores a new guest:
public void persist(Guest guest) {
em.persist(guest);
}
// Retrieves all the guests:
public List<Guest> getAllGuests() {
TypedQuery<Guest> query = em.createQuery(
"SELECT g FROM Guest g ORDER BY g.id", Guest.class);
return query.getResultList();
}
}
this is Jpa POJO Class Guest:
package it.matteo.nesea.dao.jpa;
import java.io.Serializable;
import java.sql.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Guest implements Serializable {
private static final long serialVersionUID = 1L;
// Persistent Fields:
#Id
#GeneratedValue
Long id;
private String name;
private Date signingDate;
// Constructors:
public Guest() {
}
public Guest(String name) {
this.name = name;
this.signingDate = new Date(System.currentTimeMillis());
}
// String Representation:
#Override
public String toString() {
return name + " (signed on " + signingDate + ")";
}
}
This is a Servlet GuestServlet:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import it.matteo.nesea.dao.jpa.Guest;
import it.matteo.nesea.ejb.GuestDao;
#WebServlet(name="GuestServlet", urlPatterns={"/guest"})
public class GuestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// Injected DAO EJB:
#EJB GuestDao guestDao;
#Override
protected void doGet(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Display the list of guests:
request.setAttribute("guests", guestDao.getAllGuests());
request.getRequestDispatcher("/guest.jsp").forward(request, response);
}
#Override
protected void doPost(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Handle a new guest:
String name = request.getParameter("name");
if (name != null)
guestDao.persist(new Guest(name));
// Display the list of guests:
doGet(request, response);
}
}
This is a JSP Page:
<%#page contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%#page import="java.util.*,it.matteo.nesea.dao.jpa.Guest"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JPA Guest Book Web Application</title>
</head>
<body>
<form method="POST" action="guest">
Name: <input type="text" name="name" />
<input type="submit" value="Add" />
</form>
<hr><ol> <%
#SuppressWarnings("unchecked")
List<Guest> guests = (List<Guest>)request.getAttribute("guests");
if (guests != null) {
for (Guest guest : guests) { %>
<li> <%= guest %> </li> <%
}
} %>
</ol></hr>
</body>
This is the path of Project
Your persistence.xml file is in the wrong place. The JPA uses a convention to find your persistence.xml so you have put the file in the right place.
According to the Oracle docs:
The JAR file or directory whose META-INF directory contains persistence.xml is called the root of the persistence unit.
If you package the persistent unit as a set of classes in an EJB JAR file, persistence.xml should be put in the EJB JAR’s META-INF directory.
If you package the persistence unit as a set of classes in a WAR file, persistence.xml should be located in the WAR file’s WEB-INF/classes/META-INF directory.
In your case when the persistence.xml file is in src/META-INF/ (if you use MAVEN the path is src/resources/META-INF) its going to be packaged in your war in the WEB-INF/classes/META-INF folder, funcioning as the root of the persistence unit.

Got Exception in thread "main" org.hibernate.HibernateException: hibernate.cgf.xml not found while running hibernate application

My Hibernate Application needs to retrieve the data stored in MySQL database.But i was successful in saving data into DB, but failed in retrieving.
Error Log
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.HibernateException: hibernate.cgf.xml not found
at org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:173)
at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:2035)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2016)
at mypack.DataInsertion.getInfo(DataInsertion.java:39)
at mypack.DataInsertion.main(DataInsertion.java:12)
hibernate.cfg.xml (Configuration file)
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Related to the connection START -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibdb</property>
<property name="connection.user">root</property>
<property name="connection.password">admin</property>
<!-- Related to the connection END -->
<!-- Related to the hibernate properties START -->
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Related to the hibernate properties END -->
<!-- List of XML mapping files -->
<mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
user.hbm.xml (Mapping file)
<?xml version="1.0"?> <!-- Mapping File to POJO Class -->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="mypack.DataProvider" table="user_info">
<id name="user_id" column="id">
<generator class="assigned"/>
</id>
<property name="user_name" column = "name" />
<property name="user_address" column = "address" />
</class>
</hibernate-mapping>
DataProvider.java (POJO Class)
package mypack; //POJO Class
public class DataProvider {
private int user_id;
private String user_name;
private String user_address;
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_address() {
return user_address;
}
public void setUser_address(String user_address) {
this.user_address = user_address;
}
}
DataInsertion.java (Implementation Logic)
package mypack;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class DataInsertion {
public static void main(String[] args) {
//new DataInsertion().insertInfo();
new DataInsertion().getInfo();
}
public void insertInfo()
{
Configuration con = new Configuration(); //interation with hib
con.configure("hibernate.cfg.xml"); //registering to xml
SessionFactory SF = con.buildSessionFactory(); //creating session
Session session = SF.openSession(); //opening new session
DataProvider provider = new DataProvider();
provider.setUser_id(1);
provider.setUser_name("Goutham");
provider.setUser_address("Hunsur");
Transaction TR = session.beginTransaction();
session.save(provider);
System.out.println("Object saved successfully");
TR.commit(); //saving transaction
session.close();
SF.close();
}
public void getInfo()
{
Configuration con = new Configuration();
con.configure("hibernate.cgf.xml");
SessionFactory SF = con.buildSessionFactory();
Session session = SF.openSession();
Object obj = session.load(DataProvider.class,new Integer(1)); //We are binding data into obj from DataProvider class
DataProvider dp = (DataProvider) obj; //Typecasting into DataProvider
System.out.println("Name:"+dp.getUser_name());
System.out.println("Address:"+dp.getUser_address());
session.close();
SF.close();
}
}
Please Advise me,
Thanks.
you have wrong file name with typo hibernate.cgf.xml should be hibernate.cfg.xml
You have given wrong name hibernate.cgf.xml in getInfo method. That is why you are facing issue

Working with Hibernate 3 and Struts 2. The cgf file is not getting read. Is it because of the JARS?

This is my `DAO
package com.sheeba;
import com.sheeba.LeavePojo;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.transform.Transformers;
import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
public class LeaveDAO {
#SessionTarget
Session session;
#TransactionTarget
Transaction trans;
List<LeavePojo> myList = new ArrayList<LeavePojo>();
// LeavePojo pojoObj=new LeavePojo();
public String saveToDb(LeavePojo pojoObj) {
try {
System.out.println("inside saveToDb method-before query");
System.out.println("bank id" + pojoObj.getBank_id());
// Serializable isSaved =session.save(pojoObj);
System.out.println("session" + session);
session.saveOrUpdate(pojoObj);
// System.out.println("llllllllllllllllllllllll"+session.save(pojoObj).getClass().getName());
} catch (Exception e) {
e.printStackTrace();
}
return "SUCCESS";
}
public List<LeavePojo> retrieveData() {
myList = session.createQuery("from LeavePojo").list();
return myList;
}
/*public String fetchBankId()
{
try{
System.out.println("inside fetch bank id -- before query");
String hql = "SELECT l.bank_id FROM LeavePojo l";
Query query = session.createQuery(hql);
System.out.println("deeeeeeeeeeeeeeeeeeeeeee"+query.list());
List results = query.list();
System.out.println("RESSSSSSSSSSSUUUUUUUUUUUUUULLLLLLLLLTttasssss"+results);
}catch (Exception e) {
e.printStackTrace();
}
return"success";
}*/}
service
package com.sheeba;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.sheeba.*;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.ParentPackage;
#ParentPackage("hibernate-default")
#InterceptorRef("basicStackHibernate")
public class LeaveService implements ModelDriven {
LeavePojo modobj = new LeavePojo();
LeaveDAO leaveDAO=new LeaveDAO();
//private LeaveDAO leaveDAO; // this is the dependency injection
public LeaveDAO getLeaveDAO() {
return leaveDAO;
}
public void setLeaveDAO(LeaveDAO leaveDAO) {
this.leaveDAO = leaveDAO;
}
public List<LeavePojo> myList = new ArrayList<LeavePojo>();
public List<LeavePojo> getMyList() {
return myList;
}
public void setMyList(List<LeavePojo> myList) {
this.myList = myList;
}
public List<LeavePojo> saveDetailsService(LeavePojo modobj) {
System.out.println("inside savedetails service");
leaveDAO.saveToDb(modobj);
myList = leaveDAO.retrieveData();
return myList;
}
#Override
public Object getModel() {
return modobj;
}
}
This is action
package com.sheeba;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.sun.org.apache.bcel.internal.generic.NEW;
public class LeaveAction extends ActionSupport implements ModelDriven<LeavePojo> {
LeaveService ls=new LeaveService();
LeavePojo pojo =new LeavePojo();
public List<LeavePojo> myList = new ArrayList<LeavePojo>();
public List<LeavePojo> getMyList() {
return myList;
}
public void setMyList(List<LeavePojo> myList) {
this.myList = myList;
}
private String bank_id;
private String emp_name;
private String leaves_applied;
public String getBank_id() {
return bank_id;
}
public void setBank_id(String bank_id) {
this.bank_id = bank_id;
}
public String getEmp_name() {
return emp_name;
}
public void setEmp_name(String emp_name) {
this.emp_name = emp_name;
}
public String getLeaves_applied() {
return leaves_applied;
}
public void setLeaves_applied(String leaves_applied) {
this.leaves_applied = leaves_applied;
}
public String getServiceLasyer(){
try{
System.out.println(pojo.getBank_id()+"is bank id");
myList=ls.saveDetailsService(pojo);
}catch(Exception e){
e.printStackTrace();
}
return SUCCESS;
}
#Override
public LeavePojo getModel() {
// TODO Auto-generated method stub
return pojo;
}
}
Have used these jars here /AAAAANEWPROJECT/WebContent/WEB-INF/lib/hibernate3.jar
/AAAAANEWPROJECT/WebContent/WEB-INF/lib/hibernate-annotations-3.2.1.ga.jar
/AAAAANEWPROJECT/WebContent/WEB-INF/lib/hibernate-core.jar
/AAAAANEWPROJECT/WebContent/WEB-INF/lib/struts2-fullhibernatecore-plugin-2.2.2-GA.jar. for hibernate.
struts:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="false" />
<package name="default" extends="struts-default,hibernate-default">
<action name="saveAction" class="com.sheeba.LeaveAction" method="getServiceLasyer">
<result name="success">/index.jsp</result>
</action>
</package>
</struts>
hib.config
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://10.112.178.78:1433;databaseName=Test_DB</property>
<property name="hibernate.connection.username">TestUser1</property>
<property name="connection.password">Test123</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="show_sql">true</property>
<mapping resource="LeavePojo.hbm.xml"/>
</session-factory>
</hibernate-configuration>
hib.mapping:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping SYSTEM
"hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.sheeba.LeavePojo" table="LeavePojo">
<id name="bank_id" type="string" column="BANK_ID">
</id>
<property name="emp_name" column="EMP_NAME" type="string" />
<property name="leaves_applied" column="LEAVES_APPLIED" type="string" />
</class>
</hibernate-mapping>
I am not able to get the output. 404 error comes. Is there any problem with the jar?
I got it resolved! I downloaded from the sourceforge DTD and added it to my root directory which is SRC folder.
And, edited the hibernate.cfg.xml to be as below:
<!DOCTYPE hibernate-configuration SYSTEM
"hibernate-configuration-3.0.dtd">
by this way the application doesnt have to hit the URL but it points and finds the DTD in the src folder. this you can do when you are using your system online.
IT worked for me after hell a lot of researches!!

openSession(), getCurrentSession(), beginTransaction(), lazy load

I have a simple java web application that receive some information from database and display that information in web browser. Hibernate is used to interact with database in servlets and jsp files. All work as I want, but I don't understand some things.
Database is simple - 2 tables: Question and Answer. Relationship between tables is one-to-many: one Question can have many Answers.
This is code of java classes Question and Answer:
Question.java
package app;
import java.util.Set;
public class Question {
Long id = null;
String text = "";
Set<Answer> answers = null;
public Question() {
}
public void setId(Long id) {
this.id = id;
}
public void setText(String text) {
this.text = text;
}
public void setAnswers(Set<Answer> answers) {
this.answers = answers;
}
public Long getId() {
return id;
}
public String getText() {
return text;
}
public Set<Answer> getAnswers() {
return answers;
}
}
Answer.java
package app;
public class Answer {
Long id = null;
String text = "";
Question question = null;
public Answer() {
}
public void setId(Long id) {
this.id = id;
}
public void setText(String text) {
this.text = text;
}
public void setQuestion(Question question) {
this.question = question;
}
public Long getId() {
return id;
}
public String getText() {
return text;
}
public Question getQuestion() {
return question;
}
}
And this is configuration of Hibernate:
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://localhost;databaseName=Test</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping resource="question.hbm.xml"/>
<mapping resource="answer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
question.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="app">
<class name="app.Question" table="Question">
<id column="id" name="id" type="java.lang.Long">
<generator class="native"/>
</id>
<property column="text" name="text" not-null="true" type="java.lang.String"/>
<set name="answers">
<key column="question_id"/>
<one-to-many class="app.Answer"/>
</set>
</class>
</hibernate-mapping>
answer.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="app">
<class name="app.Answer" table="Answer">
<id column="id" name="id" type="java.lang.Long">
<generator class="native"/>
</id>
<property column="text" name="text" not-null="true" type="java.lang.String"/>
<many-to-one class="app.Question" column="question_id" name="question" not-null="true"/>
</class>
</hibernate-mapping>
So in Question there is a collection of Answers. Because of this there would be a lazy load of Answers. I want to use Hibernate objects in my jsp files, so I use this technique: the filter is used to create a session, and this session is used in both servlet and coresponding jsp file.
This is code of that my filter:
HibernateFilter.java
package app;
import java.io.IOException;
import javax.servlet.*;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateFilter implements Filter {
private SessionFactory sessionFactory;
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
try {
sessionFactory.getCurrentSession().beginTransaction();
chain.doFilter(request, response);
sessionFactory.getCurrentSession().getTransaction().commit();
} catch (Exception ex) {
sessionFactory.getCurrentSession().getTransaction().rollback();
ex.printStackTrace();
}
}
public void init(FilterConfig filterConfig) throws ServletException {
sessionFactory = new Configuration().configure().buildSessionFactory();
}
public void destroy() {
}
}
There are two servlets and two coresponding jsp files in my application - first ones display question with ID = 1, second ones display all questions. This is code of this servlets, coresponding jsp files and configuration of tomcat:
GetOneQuestion.java
package app;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class GetOneQuestion extends HttpServlet {
#Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
try {
Session session = new Configuration().configure()
.buildSessionFactory().getCurrentSession();
session.beginTransaction();
Question question = (Question)session.load(Question.class, 1L);
//session.getTransaction().commit();
request.setAttribute("oneQuestion", question);
} catch (Exception ex) {
ex.printStackTrace();
request.setAttribute("oneQuestion", null);
}
RequestDispatcher view = request.getRequestDispatcher("/oneQuestion.jsp");
view.forward(request, response);
}
}
oneQuestion.jsp
<%#page import="app.Answer"%>
<%#page import="app.Question"%>
<html>
<body>
<%
Question question = (Question)request.getAttribute("oneQuestion");
out.print("<br>" + question.getText() + "<br><br>");
%>
</body>
</html>
GetAllQuestion.java
package app;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.List;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
public class GetAllQuestion extends HttpServlet {
#Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
try {
Session session = new Configuration().configure()
.buildSessionFactory().getCurrentSession();
session.beginTransaction();
Query query = session.createQuery("from Question");
List all = query.list();
request.setAttribute("allQuestion", all);
} catch (Exception ex) {
ex.printStackTrace();
request.setAttribute("allQuestion", null);
}
RequestDispatcher view = request.getRequestDispatcher("/allQuestion.jsp");
view.forward(request, response);
}
}
allQuestion.jsp
<%#page import="app.Answer"%>
<%#page import="app.Question"%>
<%#page import="java.util.List"%>
<html>
<body>
<%
List all = (List)request.getAttribute("allQuestion");
for (Object object : all) {
Question question = (Question)object;
out.print("<br>Question " + question.getId());
for (Answer answer : question.getAnswers()) {
out.print("<br>" + answer.getText() + "<br>");
}
}
%>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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/web-app_3_1.xsd">
<filter>
<filter-name>HibernateFilter</filter-name>
<filter-class>app.HibernateFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>getAllQuestion</servlet-name>
<servlet-class>app.GetAllQuestion</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getAllQuestion</servlet-name>
<url-pattern>/getAllQuestion</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>getOneQuestion</servlet-name>
<servlet-class>app.GetOneQuestion</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getOneQuestion</servlet-name>
<url-pattern>/getOneQuestion</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Question
1) Why I need to call "session.beginTransaction()" method in servlets even if I already call "session.beginTransaction()" in filter? If I call one servler from another I also have to call this method in second servlet? Or I have to call this method before every interaction with database?
2) I don't call "sessionFactory.getCurrentSession().openSession()" or "sessionFactory.getCurrentSession().getCurrentSession()" in filter but I call "sessionFactory.getCurrentSession().getCurrentSession()" in servlet and still obtain session which seem to be create in filter. How this can be?
3) If I uncomment line "session.getTransaction().commit();" in GetOneQuestion class from jsp file I receive LazyInitializationException: "could not initialize proxy - no Session" even if there is no lazy load in this jsp file because I don't use any Answer object there. What cause this Exception? Session must be open for any interaction with Hibernate object even if there is no lazy load?
You need to configure a session factory one time (!) on the application startup, not in an every servlet.
You need to close session in the filter after a transaction commit.
You don't need create a transaction in the servlet (or you don't need create a transaction in the filter).
You can store a session factory in the static field of the application initializer class and get current session from it in servlets.
About your questions
Because you do a mistake. You create a new session factory in the servlet.
You obtain a new session (because of your incorrect session factory creation). In the normal situation getCurrentSession() return a session bound to the current thread by ThreadLocal(Not always, It depends of configuration).
You have LazyInitializationException with question.getAnswers().

NPE after upgrading JAX-WS version 2.2.1 to 2.2.8

The application was using JAX-WS version 2.2.1 where I found issue in dealing with CustomException. Unable to generate the classes due to com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions. So I changed the version of JAX WS to JAX-WS 2.2.8, the above issue got solved(the classes for CustomExceptions got created). But now I am getting the following error while trying to consume the service:
Dec 20, 2013 2:42:42 AM com.sun.xml.ws.server.sei.TieHandler createResponse
SEVERE: null
java.lang.NullPointerException
at server.service.SampleServiceEndpoint.getItems(SampleServiceEndpoint.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.sun.xml.ws.api.server.InstanceResolver$1.invoke(InstanceResolver.java:250)
at com.sun.xml.ws.server.InvokerTube$2.invoke(InvokerTube.java:149)
at com.sun.xml.ws.server.sei.SEIInvokerTube.processRequest(SEIInvokerTube.java:88)
at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1136)
at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:1050)
at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:1019)
at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:877)
at com.sun.xml.ws.server.WSEndpointImpl$2.process(WSEndpointImpl.java:420)
at com.sun.xml.ws.transport.http.HttpAdapter$HttpToolkit.handle(HttpAdapter.java:687)
at com.sun.xml.ws.transport.http.HttpAdapter.handle(HttpAdapter.java:266)
at com.sun.xml.ws.transport.http.servlet.ServletAdapter.invokeAsync(ServletAdapter.java:225)
at com.sun.xml.ws.transport.http.servlet.WSServletDelegate.doGet(WSServletDelegate.java:161)
at com.sun.xml.ws.transport.http.servlet.WSServletDelegate.doPost(WSServletDelegate.java:197)
at com.sun.xml.ws.transport.http.servlet.WSServlet.doPost(WSServlet.java:81)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
Following is my Custom exception class and Fault bean.
public class ConcurrencyException extends Exception {
private ConcurrencyInfoBean faultInfo;
public ConcurrencyException(String message, ConcurrencyInfoBean faultInfo) {
super(message);
this.faultInfo = faultInfo;
}
public ConcurrencyException(String message, ConcurrencyInfoBean faultInfo, Throwable cause) {
super(message, cause);
this.faultInfo = faultInfo;
}
public ConcurrencyInfoBean getFaultInfo() {
return faultInfo;
}
}
public class ConcurrencyInfoBean {
protected String message;
public ConcurrencyInfoBean() {}
public String getMessage() {
return message;
}
public void setMessage(String value) {
this.message = value;
}
}
For which following classes where generated:
package client.service.jaxws;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name="ConcurrencyException", propOrder={"faultInfo", "message"})
public class ConcurrencyException
{
protected ConcurrencyInfoBean faultInfo;
protected String message;
public ConcurrencyInfoBean getFaultInfo()
{
return this.faultInfo;
}
public void setFaultInfo(ConcurrencyInfoBean paramConcurrencyInfoBean)
{
this.faultInfo = paramConcurrencyInfoBean;
}
public String getMessage()
{
return this.message;
}
public void setMessage(String paramString)
{
this.message = paramString;
}
}
package client.service.jaxws;
import javax.xml.ws.WebFault;
#WebFault(name="ConcurrencyException", targetNamespace="http://service.server/")
public class ConcurrencyException_Exception extends Exception
{
private ConcurrencyException faultInfo;
public ConcurrencyException_Exception(String paramString, ConcurrencyException paramConcurrencyException)
{
super(paramString);
this.faultInfo = paramConcurrencyException;
}
public ConcurrencyException_Exception(String paramString, ConcurrencyException paramConcurrencyException, Throwable paramThrowable)
{
super(paramString, paramThrowable);
this.faultInfo = paramConcurrencyException;
}
public ConcurrencyException getFaultInfo()
{
return this.faultInfo;
}
}
package client.service.jaxws;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name="concurrencyInfoBean", propOrder={"message"})
public class ConcurrencyInfoBean
{
protected String message;
public String getMessage()
{
return this.message;
}
public void setMessage(String paramString)
{
this.message = paramString;
}
}
After which I am getting a NPE in Web Service endpoint class:
#MTOM
#WebService(name = "sampleService")
#SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL, parameterStyle=ParameterStyle.WRAPPED)
public class SampleServiceEndpoint extends SpringBeanAutowiringSupport {
#Autowired
LookupService lookupService;
#Autowired
PersistenceService persistenceService;
#WebMethod
public List<Items> getItems() {
return lookupService.getItems(); // Throws NPE
}
#WebMethod
public long updateItem(#WebParam(name = "item") Item item) throws ConcurrencyException{
return persistenceService.updateItem(item);
}
#XmlMimeType("application/octet-stream")
#WebMethod
public DataHandler downloadFaxFile(String filename){
return new DataHandler(new FileDataSource(filename));
}
}
The request details captured using Fiddler: (Please note the version mentioned for User-Agent: JAX-WS RI 2.2.4-b01, but actually I am using 2.2.8 in server.)
POST http://172.16.1.17:8080/sample-server/sampleService HTTP/1.1
Accept: text/xml, multipart/related
Content-Type: multipart/related;start="<rootpart*c42f6a20-3467-47db-9f42-2fd710e98a91#example.jaxws.sun.com>";type="application/xop+xml";boundary="uuid:c42f6a20-3467-47db-9f42-2fd710e98a91";start-info="text/xml"
SOAPAction: "http://service.server/sampleService/getItemsRequest"
User-Agent: JAX-WS RI 2.2.4-b01
Host: 172.16.1.17:8080
Connection: keep-alive
Content-Length: 461
Connection: close
--uuid:c42f6a20-3467-47db-9f42-2fd710e98a91
Content-Id: <rootpart*c42f6a20-3467-47db-9f42-2fd710e98a91#example.jaxws.sun.com>
Content-Type: application/xop+xml;charset=utf-8;type="text/xml"
Content-Transfer-Encoding: binary
<?xml version="1.0" ?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><ns2:getItems xmlns:ns2="http://service.server/"></ns2:getItems></S:Body></S:Envelope>
--uuid:c42f6a20-3467-47db-9f42-2fd710e98a91--
The response captured using Fiddler:
HTTP/1.1 500 Internal Server Error
Server: Apache-Coyote/1.1
Content-Type: multipart/related; start="<rootpart*fd6818ff-12f2-490b-b0fe-7d99e1196491#example.jaxws.sun.com>"; type="application/xop+xml"; boundary="uuid:fd6818ff-12f2-490b-b0fe-7d99e1196491"; start-info="text/xml"
Transfer-Encoding: chunked
Date: Sat, 21 Dec 2013 08:30:25 GMT
Connection: close
154
--uuid:fd6818ff-12f2-490b-b0fe-7d99e1196491
Content-Id: <rootpart*fd6818ff-12f2-490b-b0fe-7d99e1196491#example.jaxws.sun.com>
Content-Type: application/xop+xml;charset=utf-8;type="text/xml"
Content-Transfer-Encoding: binary
<?xml version='1.0' encoding='UTF-8'?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body>
b5
<S:Fault xmlns:ns4="http://www.w3.org/2003/05/soap-envelope"><faultcode>S:Server</faultcode><faultstring>java.lang.NullPointerException</faultstring></S:Fault></S:Body></S:Envelope>
2f
--uuid:fd6818ff-12f2-490b-b0fe-7d99e1196491--
0
Spring config files:
1. applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="server"/>
<import resource="datasource.xml"/>
<import resource="services.xml"/>
</beans>
services.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<bean id="lookupService" class="server.service.LookupServiceImpl">
<property name="statusDAO" ref="statusDAO"/>
<property name="utilDAO" ref="utilDAO"/>
<property name="logDAO" ref="logDAO"/>
<property name="faxHistoryDAO" ref="faxHistoryDAO"/>
</bean>
<bean id="persistenceService" class="server.service.PersistenceServiceImpl">
<property name="logDAO" ref="logDAO"/>
<property name="faxHistoryDAO" ref="faxHistoryDAO"/>
</bean>
<bean id="adminService" class="server.service.AdminServiceImpl">
<property name="userDAO" ref="userDAO"/>
</bean>
<bean id="reportService" class="server.service.ReportServiceImpl">
<property name="reportDAO" ref="reportDAO"/>
</bean>
The environment details:
jdk1.7.0_21, tomcat 7, windows 7
I could avoid the NPE by modifying my Webservice endpoint class but not so sure whether the following solution is best or not, but it works for me:
#MTOM
#WebService(name = "sampleService")
#SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL, parameterStyle=ParameterStyle.WRAPPED)
public class SampleServiceEndpoint extends SpringBeanAutowiringSupport {
#Autowired
LookupService lookupService;
#Autowired
PersistenceService persistenceService;
#WebMethod(exclude=true)
private void initLookupService(){
if(lookupService == null)
processInjectionBasedOnCurrentContext(this);
}
#WebMethod(exclude=true)
private void initPersistenceService(){
if(persistenceService == null)
processInjectionBasedOnCurrentContext(this);
}
#WebMethod
public List<Items> getItems() {
initLookupService();
return lookupService.getItems();
}
#WebMethod
public long updateItem(#WebParam(name = "item") Item item) throws ConcurrencyException{
initPersistenceService()
return persistenceService.updateItem(item);
}
#XmlMimeType("application/octet-stream")
#WebMethod
public DataHandler downloadFaxFile(String filename){
return new DataHandler(new FileDataSource(filename));
}
}

Categories