Hi All,
Iam getting null pointer exception when i call Session.getSession() from my DAOs when i deploy as webapplication.
I got stuck here from last two days. Here is my Peristance.java file which is extended Filter.
Can any one guide me where iam going wrong.
========= Persistance.java ======================
import java.io.*;
import java.util.*;
import javax.servlet.*;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.HibernateException;
import org.hibernate.StaleObjectStateException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.naming.InitialContext;
import javax.transaction.UserTransaction;
public class Persistence implements Filter
{
private static final long serialVersionUID=1L;
private static Log logger;
public static final String HIBERNATE_FACTORY_JNDI_PARAM = "hibernateFactory";
public static final String HIBERNATE_FACTORY_JNDI_DEFAULT = "java:/SessionFactory";
protected static ThreadLocal hibernateHolder = new ThreadLocal();
protected static ThreadLocal txHolder = new ThreadLocal();
protected static SessionFactory factory;
private static boolean CMPMode = true;
public static final String JNDI_HIBERNATE_FACTORY = "SessionFactory";
public static final String JNDI_JTA_TRANSACTION = "java:comp/UserTransaction";
public static final String ROLLBACK = "rollback";
public static final String STALEDATA = "staledata";
public boolean isCMPMode() {
return CMPMode;
}
public void init(FilterConfig filterConfig) throws ServletException {
// Initialize session factory
try {
InitialContext ctx = new InitialContext();
factory = (SessionFactory) ctx.lookup(JNDI_HIBERNATE_FACTORY);
CMPMode = true;
} catch (Exception e) {
// do nothing
}
if (!CMPMode) {
logger.debugLog("Persistence: Init Session: Could not bind to Hibernate Factory through JNDI");
try {
factory = new Configuration().configure().buildSessionFactory();
logger.debugLog("Persistence: Init Session: Hibernate Factory built manually");
} catch (HibernateException ex) {
throw new ServletException(ex);
}
}
}
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (CMPMode)
doFilterCMP(request, response, chain);
else
doFilterHibernate(request, response, chain);
}
private void doFilterCMP(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
UserTransaction tx = null;
try {
tx = (UserTransaction) new InitialContext().lookup(JNDI_JTA_TRANSACTION);
logger.debugLog("=========== ["+Thread.currentThread().hashCode()+"]: dofilter: tx=" + tx);
tx.begin();
try {
// use the Hibernate Factory
//SessionFactory factory = (SessionFactory) new InitialContext().lookup(JNDI_HIBERNATE_FACTORY);
Session sess = factory.openSession();
logger.debugLog("=========== dofilter: sess=" + sess);
hibernateHolder.set(sess);
txHolder.set(tx);
logger.debugLog("=========== dofilter: tx and hib holders set");
chain.doFilter(request, response);
logger.debugLog("=========== dofilter: Returned from chain.dofilter");
String roll = (String) request.getAttribute(ROLLBACK);
if ("true".equals(roll)) {
logger.debugLog("ROLLBACK set to true in request attribute");
request.removeAttribute(ROLLBACK);
rollback();
}
logger.debugLog("Persistence: Commiting");
logger.debugLog("=========== dofilter: About to commit");
tx.commit();
logger.debugLog("=========== dofilter: Committed");
} catch (Exception e) {
logger.debugLog("Persistence: Caught exception during filter chain: " + e);
e.printStackTrace();
} finally {
//hsession.close();
}
} catch (Exception eo) {
eo.printStackTrace();
logger.debugLog("Persistence: Caught exception in tx try: " + eo);
try {
logger.debugLog("Persistence: Rolling back");
tx.rollback();
} catch (Exception rbe) {
logger.debugLog("Persistence: Caught exception while rolling back!!!! " + rbe);
}
}
}
private void doFilterHibernate(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
boolean error = false;
logger.debugLog("Entering doFilter " + Thread.currentThread().hashCode());
if (hibernateHolder.get() != null)
throw new IllegalStateException(
"A session is already associated with this thread! "
+ "Someone must have called getSession() outside of the context "
+ "of a servlet request." + Thread.currentThread().hashCode());
try {
Session sess = factory.openSession();
hibernateHolder.set(sess);
txHolder.set(sess.beginTransaction());
chain.doFilter(request, response);
String roll = (String)request.getAttribute(ROLLBACK);
if ("true".equals(roll)) {
logger.debugLog("ROLLBACK set to true in request attribute");
request.removeAttribute(ROLLBACK);
rollback();
// set error flag to prevent commit
error = true;
}
} catch (Exception ex) {
// if an exception occurs rollback
logger.debugLog("Exception encountered setting error to true and rolling back the transaction");
ex.printStackTrace();
rollback();
// set error flag to prevent commit
error = true;
} finally {
logger.debugLog("closing tx" + Thread.currentThread().hashCode());
Session sess = (Session)hibernateHolder.get();
Transaction tx = (Transaction)txHolder.get();
if (sess != null) {
hibernateHolder.set(null);
try {
if (tx != null && !error) {
logger.debugLog("commiting transaction");
tx.commit();
}
}
catch (HibernateException ex3) {
if (ex3 instanceof StaleObjectStateException) {
logger.debugLog("StaleObjectStateException - set STALEDATA attribute to true");
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpSession session = httpRequest.getSession();
session.setAttribute(STALEDATA, "true");
}
ex3.printStackTrace();
try {
if (!tx.wasCommitted()) {
rollback();
}
} catch (HibernateException ex4) {
ex4.printStackTrace();
throw new ServletException(ex4);
}
} finally {
try {
logger.debugLog("closing Session " + Thread.currentThread().hashCode());
sess.close();
} catch (HibernateException ex5) {
ex5.printStackTrace();
throw new ServletException(ex5);
}
}
}
logger.debugLog("Successfully closed");
}
}
public static Session getSession() throws HibernateException {
Session sess = (Session)hibernateHolder.get();
if (sess == null) {
throw new HibernateException("Session has not been opened -- the session object is NULL");
} else {
//logger.debugLog("Getting session " + Thread.currentThread().hashCode());
}
return sess;
}
public static SessionFactory getSessionFactory() {
logger.debugLog("========== In Persistence.getSessionFactory: sf=" + factory);
return factory;
}
public static void commit() throws PersistenceException {
if (CMPMode)
commitCMP();
else
commitHibernate();
}
private static void commitCMP() throws PersistenceException {
try {
logger.debugLog("Persistence: commiting transaction");
UserTransaction tx = (UserTransaction) txHolder.get();
tx.commit();
} catch (Exception e) {
logger.debugLog("Persistence: Cannot commit transaction: rolling back");
rollback();
throw new UpdateException("Persistence: Unable to commit transaction", e);
}
}
private static void commitHibernate() throws PersistenceException {
try {
Session sess = (Session)hibernateHolder.get();
Transaction tx = (Transaction)txHolder.get();
if (sess != null && tx != null) {
try {
logger.debugLog("Persistence: commiting transaction");
tx.commit();
} catch (HibernateException e) {
e.printStackTrace();
try {
if (!tx.wasCommitted())
rollback();
} catch (HibernateException e2) {
e2.printStackTrace();
throw new UpdateException("Persistence: Unable to commit transaction", e2);
}
throw new UpdateException("Persistence: Unable to commit transaction", e);
}
}
} catch (Exception ex) {
throw new UpdateException("Persistence: Unable to commit transaction", ex);
}
}
public static void rollback() {
if (CMPMode)
rollbackCMP();
else
rollbackHibernate();
}
private static void rollbackCMP() {
UserTransaction tx = (UserTransaction) txHolder.get();
txHolder.set(null);
if (tx != null) {
try {
tx.rollback();
logger.debugLog("Rollback successful");
} catch (Exception ex) {
logger.debugLog("Persitence: Ate exception thrown during rollback: " + ex);
// Probably don't need to do anything - this is likely being
// called because of another exception, and we don't want to
// mask it with yet another exception.
}
}
}
private static void rollbackHibernate() {
Transaction tx = (Transaction)txHolder.get();
txHolder.set(null);
if (tx != null) {
try {
tx.rollback();
logger.debugLog("Rollback successful");
} catch (HibernateException ex) {
logger.debugLog("Persitence: Ate exception thrown during rollback: " + ex);
// Probably don't need to do anything - this is likely being
// called because of another exception, and we don't want to
// mask it with yet another exception.
}
}
}
/**
Close the factory
*/
public void destroy() {
if (CMPMode) {
try {
factory.close();
} catch (HibernateException ex) {
throw new RuntimeException(ex);
}
}
}
public static void applicationModeInit(SessionFactory sf, Log log)
throws Exception {
// Initialize hibernate
try {
logger = log;
logger.debugLog("Init Session " + Thread.currentThread().hashCode());
factory = sf;
} catch (Exception ex) {
throw new ServletException(ex);
}
}
public static void openSession() throws PersistenceException {
Session sess = (Session)hibernateHolder.get();
if (sess == null) {
logger.debugLog("Opening Session " + Thread.currentThread().hashCode());
try {
sess = factory.openSession();
hibernateHolder.set(sess);
} catch (HibernateException e) {
throw new PersistenceException("Unable to open session", e);
}
} else {
// session already exists
throw new PersistenceException("Session already exists");
}
}
public static void beginTransaction() throws PersistenceException {
Session sess = (Session)hibernateHolder.get();
Transaction tx = (Transaction)txHolder.get();
if (sess == null) {
throw new PersistenceException("Need to call openSession() prior to calling beginTransaction");
} else if (tx == null) {
// creates a new transaction for the current session
try {
if (sess.isConnected()) {
logger.debugLog("beginTransaction: session is connected: disconnect");
sess.disconnect();
logger.debugLog("beginTransaction: disconnect successful");
} else {
logger.debugLog("beginTransaction: no connectione exists");
}
logger.debugLog("beginTransaction: calling reconnect");
sess.reconnect();
logger.debugLog("beginTransaction: reconnect successful");
txHolder.set(sess.beginTransaction());
} catch (HibernateException e) {
throw new PersistenceException("Unable to begin transaction", e);
}
} else {
throw new PersistenceException("Attempting to begin a transaction without ending the previous transaction");
}
return;
}
/**
Invoke this method to end a transaction.
**/
public static void endTransaction() throws PersistenceException {
Session sess = (Session)hibernateHolder.get();
Transaction tx = (Transaction)txHolder.get();
try {
if (sess == null) {
// throw exception
throw new PersistenceException("Attempting to end a transaction when the session is null");
} else if (tx == null) {
throw new PersistenceException("Attempting to end a transaction when there transaction is null");
// throw exception
} else {
commit();
txHolder.set(null);
}
} finally {
try {
if (sess.isConnected()) {
logger.debugLog("endTransaction: connection exists - disconecting");
sess.disconnect();
} else {
logger.debugLog("endTransaction: no connectione exists");
}
logger.debugLog("endTransaction: calling reconnect");
sess.reconnect();
logger.debugLog("endTransaction: reconnect successful");
} catch (Exception e){
throw new PersistenceException("Unable to re-establish a jdbc connection: " + e);
}
}
}
public static void closeSession() throws PersistenceException {
Session sess = (Session)hibernateHolder.get();
Transaction tx = (Transaction)txHolder.get();
if (sess == null) {
throw new PersistenceException("Attempting to close a session that is already null");
}
if (tx != null) {
throw new PersistenceException("Attempting to close a session prior to calling endTransaction()");
}
try {
sess.close();
hibernateHolder.set(null);
} catch (HibernateException e) {
throw new PersistenceException("Unable to close session", e);
}
}
}
|