Example usage for org.hibernate Session disconnect

List of usage examples for org.hibernate Session disconnect

Introduction

In this page you can find the example usage for org.hibernate Session disconnect.

Prototype

Connection disconnect();

Source Link

Document

Disconnect the session from its underlying JDBC connection.

Usage

From source file:cyrille.hibernate.context.DisconnectedSessionOpenInviewFilter.java

License:Apache License

public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpSession httpSession = request.getSession(false);
    if (httpSession == null) {
        logger.debug("No http session found");
    } else {//www .j  av a2 s .  c  o m
        Session session = (Session) httpSession.getAttribute(Session.class.getName());
        if (session == null) {
            logger.debug("No Hibernate session found in http session");
        } else {
            // no need to reconnect the session, automatically done by Hibernate

            if (logger.isDebugEnabled()) {
                logger.debug("Bind " + session + " to ThreadLocalSessionContext");
            }
            ThreadLocalSessionContext.bind(session);
        }
    }

    try {
        // CHAIN
        chain.doFilter(request, response);

    } finally {
        // UNBIND HIBERNATE SESSION FROM HIBERNATE_THREAD_LOCAL_SESSION_CONTEXT, DISCONNECT AND BIND TO HTTP_SESSION

        Session session = ThreadLocalSessionContext.unbind(sessionFactory);
        if (session == null) {
            logger.debug("No Hibernate session unbound by ThreadLocalSessionContext");
        } else {
            if (session.isDirty()) {
                try {
                    logger.warn("Hibernate session is dirty !");
                    // TODO what is the policy ? Session will be disconnected and thus modifications will come back during reconnect
                    if (session.getTransaction().isActive()) {
                        logger.warn("Rollback active transaction for dirty session");
                        session.getTransaction().rollback();
                    }
                    logger.warn("Close dirty session");
                    session.close();
                } finally {
                    logger.warn("Remove Hibernate session from http session");
                    request.getSession().removeAttribute(Session.class.getName());

                }
            } else {
                logger.debug(
                        "Hibernate session unbound from ThreadLocalSessionContext, disconnected and bound to http session");

                try {
                    session.disconnect();
                    // force creation of the HttpSession even if it did not exist at the beginning of the filter
                    request.getSession().setAttribute(Session.class.getName(), session);
                } catch (RuntimeException e) {
                    logger.error(
                            "Exception disconnecting hibernate session. Remove Hibernate session from http session",
                            e);
                    request.getSession().removeAttribute(Session.class.getName());
                    throw e;
                }
            }

        }
    }
}

From source file:de.decidr.model.webservice.helper.DBAccess.java

License:Apache License

/**
 * @param dwfmID//www.ja  v  a  2 s . c  o  m
 * @param invokeNodeId
 * @return gets the relevatn DWDL and the relevant WSDL file for the proxy-service from the Database
 */
public DbDataBean getDBData(long dwfmID, long invokeNodeId) {

    DbDataBean dataBean = new DbDataBean();

    SessionFactory sf = new Configuration().configure().buildSessionFactory();

    // actial session
    Session se = sf.getCurrentSession();

    try {
        // save transaction to avoid NullPointerException on error handling.
        Transaction tr = null;

        try {
            // initialize new transaction
            tr = se.beginTransaction();

            execDeployedWorkflowModelQuery(dwfmID, dataBean, se);
            execFileQuery(getFileIDFromDwdl(dataBean, invokeNodeId), dataBean, se);
            execServerLoadViewQuery(ServerTypeEnum.Ode.toString(), dataBean, se);

            se.getTransaction().commit();

        } catch (Throwable e) {
            // if no transaction has been initialized try rollback

            if (tr != null) {
                tr.rollback();
                e.printStackTrace();
            }
        }
    } finally {
        // try to close session if this does not work 
        // at least try to close the transaction.
        try {
            if (se.isOpen()) {
                se.close();
            }
            if (!sf.isClosed()) {
                sf.close();
            }
        } catch (Throwable e) {
            se.disconnect();
        }
    }

    return dataBean;
}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

License:Open Source License

/**
 * @throws WGAPIException /* w w w . j  ava  2  s.c o  m*/
 * @see de.innovationgate.webgate.api.WGDatabaseCore#closeSession()
 */
public void closeSession() throws WGAPIException {
    try {

        Session session = getSessionStatus().getSession();
        if (session != null) {
            Transaction trans = session.getTransaction();
            if (trans != null && trans.isActive()) {
                trans.rollback();
            }
        }
    } catch (Throwable e) {
        WGFactory.getLogger().error("Exception rolling back transaction on session close", e);
    }

    try {
        // set session closed flag on dbupdate if present
        if (_db.isSessionOpen()) {
            String user = _db.getSessionContext().getUser();
            DBUpdate update = (DBUpdate) _dbUpdatesByUser.get(user);
            if (update != null) {
                update.setSessionClosed(true);
            }
        }
    } catch (Throwable e) {
        WGFactory.getLogger().error("Setting session closed flag transaction on session close", e);
    }

    try {
        SessionStatus sessionStatus = (SessionStatus) _sessionStatus.get();
        if (sessionStatus != null) {
            Session session = sessionStatus.getSession();
            if (session != null) {
                session.disconnect();
                session.close();
            }

        }

        _sessionStatus.remove();
    } catch (HibernateException e) {
        throw new WGBackendException("Error closing hibernate session", e);
    }
}

From source file:de.sub.goobi.helper.servletfilter.HibernateSessionFilter2.java

License:Open Source License

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest myRequest = (HttpServletRequest) request;
    HibernateSessionLong hsl = null;//from w  w w  .jav a2 s.c  o m
    Session session = null;

    /*
     * die Hibernate-Session connecten
     */
    // das Managed Bean aus der Session holen
    hsl = (HibernateSessionLong) myRequest.getSession().getAttribute("HibernateSessionLong");
    // wenn das Managed Bean bereits in der Http-Session war,
    // dann daraus die Hibernate-Session ermitteln
    if (hsl != null) {
        session = hsl.getSession();
    }
    if (session != null && !session.isConnected()) {
        //TODO: check why is it empty
    }

    try {
        chain.doFilter(request, response);
    } catch (Exception e) {
        throw new ServletException(new GUIExceptionWrapper("Unexpected Error.", e));
    } finally {

        /*
         * die Hibernate-Session von der Datenbank trennen
         */
        // das Managed Bean aus der Session holen
        hsl = (HibernateSessionLong) myRequest.getSession().getAttribute("HibernateSessionLong");
        // wenn das Managed Bean bereits in der Http-Session war,
        // dann daraus die Hibernate-Session ermitteln
        if (hsl != null) {
            session = hsl.getSession();
            // gibt es eine Hibernate-Session und ist diese mit der DB
            // verbunden, dann wird diese jetzt getrennt
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }
    }
}

From source file:de.tudarmstadt.ukp.lmf.transform.LMFDBUtils.java

License:Apache License

public static void dropTables(final DBConfig dbConfig) {
    System.out.println("DROP TABLES");
    Configuration cfg = HibernateConnect.getConfiguration(dbConfig);
    cfg.setProperty("hibernate.hbm2ddl.auto", "none");
    SessionFactory sf = cfg.buildSessionFactory(
            new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry());
    Session session = sf.openSession();
    Transaction tx = session.beginTransaction();
    try {//from  w  w  w.j a v  a 2s  . c o m
        // Create a set of all tables.
        Set<String> dropSQL = new TreeSet<String>();
        Iterator<Table> iter = cfg.getTableMappings();
        while (iter.hasNext())
            dropSQL.add("DROP TABLE " + iter.next().getName());

        // Try to delete them repeatedly until no tables are left or 
        // there have been too many repetitions.
        int remainingLoops = dropSQL.size();
        while (!dropSQL.isEmpty() && remainingLoops >= 0) {
            Iterator<String> sqlIter = dropSQL.iterator();
            while (sqlIter.hasNext()) {
                try {
                    String sql = sqlIter.next();
                    session.createSQLQuery(sql).executeUpdate();
                    sqlIter.remove();
                    System.out.println(sql);
                } catch (HibernateException e) {
                }
            }
            remainingLoops--;
        }
    } finally {
        tx.commit();
        session.disconnect();
        session.close();
    }
}

From source file:de.tudarmstadt.ukp.lmf.transform.LMFDBUtils.java

License:Apache License

public static void truncateTables(final DBConfig dbConfig) {
    System.out.println("TRUNCATE TABLES");
    Configuration cfg = HibernateConnect.getConfiguration(dbConfig);
    SessionFactory sf = cfg.buildSessionFactory(
            new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry());
    Session session = sf.openSession();
    try {/*from   ww  w . j a v  a 2 s . c  o  m*/
        session.createSQLQuery("SET FOREIGN_KEY_CHECKS=0").executeUpdate();
        Iterator<Table> iter = cfg.getTableMappings();
        while (iter.hasNext())
            session.createSQLQuery("TRUNCATE TABLE " + iter.next().getName()).executeUpdate();
    } finally {
        session.createSQLQuery("SET FOREIGN_KEY_CHECKS=1").executeUpdate();
        session.disconnect();
        session.close();
    }
}

From source file:edu.ku.brc.dbsupport.HibernateUtil.java

License:Open Source License

/**
 * Disconnect and return Session from current Thread.
 *
 * @return Session the disconnected Session
 *//*  w w  w  .ja  v a2  s.  c om*/
public static Session disconnectSession() {
    if (useThreadLocal) {
        Transaction tx = (Transaction) threadTransaction.get();
        if (tx != null && (!tx.wasCommitted() || !tx.wasRolledBack()))
            throw new IllegalStateException("Disconnecting Session but Transaction still open!"); //$NON-NLS-1$
        Session session = getCurrentSession();
        threadSession.set(null);
        if (session.isConnected() && session.isOpen()) {
            //log.debug("Disconnecting Session from this thread.");
            session.disconnect();
        }
        return session;
    }

    // else
    log.error("Using CMT/JTA, intercepted not supported disconnect call."); //$NON-NLS-1$
    return null;
}

From source file:fr.gael.dhus.database.dao.ActionRecordReaderDao.java

License:Open Source License

/**
 * Returns the result of a SQL query./*  ww w.j  a v a 2 s  .  c  o m*/
 * 
 * @param sql
 *           The sql string.
 * @param periodicity
 *           A list of two Date or null if not applicable.
 * @return ReturnValue A list of Object[]. Each object tab contains the
 *         result of a row of the SELECT. The list is used for multiple row
 *         results.
 */
@SuppressWarnings("unchecked")
private List<Object[]> getReturnValue(final String sql, final Date start, final Date end) {
    boolean newSession = false;
    Session session;

    try {
        session = getSessionFactory().getCurrentSession();
    } catch (HibernateException e) {
        session = getSessionFactory().openSession();
        newSession = true;
    }
    SQLQuery query = session.createSQLQuery(sql);
    if (start != null)
        query.setDate(0, start);
    if (end != null)
        query.setDate(1, end);
    List<Object[]> result = query.list();

    if (newSession)
        session.disconnect();
    return result;
}

From source file:fr.gael.dhus.database.dao.ActionRecordReaderDao.java

License:Open Source License

/**
 * Returns the result of a SQL query./*from   w  ww.  ja  v a2s.  c o  m*/
 * 
 * @param sql
 *           The sql string.
 * @param periodicity
 *           A list of two Date or null if not applicable.
 * @return number of elements returned by the passed query. Is something is
 *    wrong with the query result, 0 is returned
 */
private int getCountValue(final String sql, final Date start, final Date end) {
    boolean newSession = false;
    Session session;
    try {
        session = getSessionFactory().getCurrentSession();
    } catch (HibernateException e) {
        session = getSessionFactory().openSession();
        newSession = true;
    }

    SQLQuery query = session.createSQLQuery(sql);
    if (start != null)
        query.setDate(0, start);
    if (end != null)
        query.setDate(1, end);
    BigInteger result = (BigInteger) query.uniqueResult();

    if (newSession)
        session.disconnect();

    return result.intValue();
}

From source file:fr.gael.dhus.database.dao.interfaces.HibernateDao.java

License:Open Source License

/**
 * <p>Returns a List of <b>T</b> entities, where HQL clauses can be
 * specified.</p>//w  w  w .  j a va  2 s . com
 * 
 * Note: This method is useful in read only. It can be use to delete or 
 * create <b>T</b> entities, but caution with <code>top</code> and 
 * <code>skip</code> arguments.
 * 
 * @param clauses query clauses (WHERE, ORDER BY, GROUP BY), if null no
 * clauses are apply.
 * @param skip number of entities to skip.
 * @param n  number of entities max returned.
 * @return a list of <b>T</b> entities.
 */
@SuppressWarnings("unchecked")
public List<T> scroll(final String clauses, final int skip, final int n) {
    StringBuilder hql = new StringBuilder();
    hql.append("FROM ").append(entityClass.getName());
    if (clauses != null)
        hql.append(" ").append(clauses);

    Session session;
    boolean newSession = false;
    try {
        session = getSessionFactory().getCurrentSession();
    } catch (HibernateException e) {
        session = getSessionFactory().openSession();
        newSession = true;
    }

    Query query = session.createQuery(hql.toString());
    if (skip > 0)
        query.setFirstResult(skip);
    if (n > 0) {
        query.setMaxResults(n);
        query.setFetchSize(n);
    }

    logger.info("Execution of HQL: " + hql.toString());
    long start = System.currentTimeMillis();

    List<T> result = (List<T>) query.list();
    logger.info("HQL executed in " + (System.currentTimeMillis() - start) + "ms.");

    if (newSession) {
        session.disconnect();
    }

    return result;
}