Example usage for org.hibernate Transaction setTimeout

List of usage examples for org.hibernate Transaction setTimeout

Introduction

In this page you can find the example usage for org.hibernate Transaction setTimeout.

Prototype

void setTimeout(int seconds);

Source Link

Document

Set the transaction timeout for any transaction started by a subsequent call to #begin on this instance.

Usage

From source file:edu.upenn.cis.ppod.services.PPodEntitiesResourceHibernate.java

License:Apache License

public Counts countHqlQuery(final String query, Integer timeoutSeconds) {
    final String METHOD = "countHqlQuery(...)";
    final long inTime = new Date().getTime();

    timeoutSeconds = Math.min(timeoutSeconds, 60);

    Transaction trx = null;
    try {/*from  w w w . jav  a2 s  .c  om*/
        // not beginTransaction so we can
        // now set the timeout
        trx = session.getTransaction();
        trx.setTimeout(timeoutSeconds);
        trx.begin();

        final Counts counts = count(query);
        trx.commit();
        return counts;

    } catch (final Throwable t) {
        if (trx != null && trx.isActive()) {
            try {
                trx.rollback();
            } catch (final Throwable rbEx) {
                logger.error("caught exception while rolling back", rbEx);
            }
        }
        final long endTime = new Date().getTime();

        if (endTime - inTime >= (timeoutSeconds * 1000) - 500) {
            logger.error("caught timeout exception, returning flagged Counts", t);
            final Counts counts = new Counts();
            counts.setTimedOut(true);
            counts.setOtuSetCount(-1);
            counts.setStandardMatrixCount(-1);
            counts.setDnaMatrixCount(-1);
            counts.setTreeSetCount(-1);
            return counts;
        }
        final String exceptionUuid = UUID.randomUUID().toString();
        logger.error(METHOD + ": " + exceptionUuid, t);
        throw new IllegalStateException(t.getMessage() + ": error id [" + exceptionUuid + "]", t);
    } finally {
        session.close();
        logger.info("{}: response time: {} milliseconds", METHOD, Long.valueOf(new Date().getTime() - inTime));
    }
}

From source file:edu.upenn.cis.ppod.services.PPodEntitiesResourceHibernate.java

License:Apache License

public PPodEntities getEntitiesByHqlQuery(final String query) {
    final String METHOD = "getEntitiesByHqlQuery(...)";
    final long inTime = new Date().getTime();
    Transaction trx = null;

    final DbStudy2DocStudy dbStudy2DocStudy = new DbStudy2DocStudy();

    final int TIMEOUT_SECONDS = 60;

    try {/*www .  ja v a2s  . c o  m*/
        // not beginTransaction so we can
        // now set the timeout
        trx = session.getTransaction();
        trx.setTimeout(TIMEOUT_SECONDS);
        trx.begin();

        @SuppressWarnings("unchecked")
        final List<Object> queryResults = session.createQuery(query).setReadOnly(true).list();
        final PPodEntities entities = new PPodEntities();

        final List<Object> flattenedAndDenulledResults = newArrayList();

        for (final Object queryResult : queryResults) {
            if (queryResult instanceof Object[]) {
                final Object[] queryResultObjectArray = (Object[]) queryResult;
                for (final Object o : queryResultObjectArray) {
                    if (o != null) {
                        flattenedAndDenulledResults.add(o);
                    }
                }
            } else {
                flattenedAndDenulledResults.add(queryResult);
            }
        }

        for (final Object queryResult : flattenedAndDenulledResults) {
            if (queryResult instanceof OtuSet) {
                final OtuSet otuSet = (OtuSet) queryResult;
                handleOtuSet(entities, otuSet, dbStudy2DocStudy);
            } else if (queryResult instanceof StandardMatrix) {
                final StandardMatrix dbMatrix = (StandardMatrix) queryResult;

                // Note that otu set may have already been added in any
                // of
                // the other if clauses so we must make check before
                // adding

                final OtuSet dbOtuSet = dbMatrix.getParent();

                final PPodOtuSet docOtuSet = handleOtuSet(entities, dbOtuSet, dbStudy2DocStudy);

                // Let's not add in the same matrix twice
                if (find(docOtuSet.getStandardMatrices(),
                        compose(equalTo(dbMatrix.getPPodId()), IHasPPodId.getPPodId), null) == null) {
                    final PPodStandardMatrix docMatrix = dbStudy2DocStudy
                            .dbStandardMatrix2DocStandardMatrix(dbMatrix);
                    docOtuSet.getStandardMatrices().add(docMatrix);
                }

            } else if (queryResult instanceof DnaMatrix) {
                final DnaMatrix dbMatrix = (DnaMatrix) queryResult;

                // Note that otu set may have already been added in any
                // of
                // the other if clauses so we must make check before
                // adding

                final OtuSet dbOtuSet = dbMatrix.getParent();

                final PPodOtuSet docOtuSet = handleOtuSet(entities, dbOtuSet, dbStudy2DocStudy);

                // Let's not add in the same matrix twice
                if (find(docOtuSet.getDnaMatrices(),
                        compose(equalTo(dbMatrix.getPPodId()), IHasPPodId.getPPodId), null) == null) {
                    final PPodDnaMatrix docMatrix = dbStudy2DocStudy.dbDnaMatrix2DocDnaMatrix(dbMatrix);
                    docOtuSet.getDnaMatrices().add(docMatrix);
                }
            } else if (queryResult instanceof ProteinMatrix) {
                final ProteinMatrix dbMatrix = (ProteinMatrix) queryResult;

                // Note that otu set may have already been added in any
                // of
                // the other if clauses so we must make check before
                // adding

                final OtuSet dbOtuSet = dbMatrix.getParent();

                final PPodOtuSet docOtuSet = handleOtuSet(entities, dbOtuSet, dbStudy2DocStudy);

                // Let's not add in the same matrix twice
                if (find(docOtuSet.getProteinMatrices(),
                        compose(equalTo(dbMatrix.getPPodId()), IHasPPodId.getPPodId), null) == null) {
                    final PPodProteinMatrix docMatrix = dbStudy2DocStudy
                            .dbProteinMatrix2DocProteinMatrix(dbMatrix);
                    docOtuSet.getProteinMatrices().add(docMatrix);
                }
            } else if (queryResult instanceof TreeSet) {
                final TreeSet dbTreeSet = (TreeSet) queryResult;

                // Note that otu set may have already been added in any
                // of
                // the other if clauses so we must make check before
                // adding

                final OtuSet dbOtuSet = dbTreeSet.getParent();

                final PPodOtuSet docOtuSet = handleOtuSet(entities, dbOtuSet, dbStudy2DocStudy);

                // Let's not add in the same tree set twice
                if (find(docOtuSet.getTreeSets(), compose(equalTo(dbTreeSet.getPPodId()), IHasPPodId.getPPodId),
                        null) == null) {
                    final PPodTreeSet docTreeSet = dbStudy2DocStudy.dbTreeSet2DocTreeSet(dbTreeSet);
                    docOtuSet.getTreeSets().add(docTreeSet);
                }
                // } else if (queryResult instanceof Otu) {
                // final Otu otu = (Otu) queryResult;
                // entities.getOtus().add(
                // dbStudy2DocStudy.dbOtu2DocOtu(otu));
            } else {
                throw new IllegalArgumentException("unsupported entity type [" + queryResult.getClass()
                        + "], result: [" + queryResult.toString() + "]");
            }
        }
        trx.commit();
        return entities;
    } catch (final Throwable t) {
        if (trx != null && trx.isActive()) {
            try {
                trx.rollback();
            } catch (final Throwable rbEx) {
                logger.error("caught exception while rolling back", rbEx);
            }
        }
        logger.error(METHOD, t);
        final long endTime = new Date().getTime();

        if (endTime - inTime >= (TIMEOUT_SECONDS * 1000) - 500) {
            logger.error(
                    "caught timeout exception, swalling exception and throwing one that indicates a timeout");
            throw new IllegalStateException("query was taking longer than " + TIMEOUT_SECONDS + " seconds");
        }
        throw new IllegalStateException(t);
    } finally {
        session.close();
        logger.info("{}: response time: {} milliseconds", METHOD, Long.valueOf(new Date().getTime() - inTime));
    }
}

From source file:org.beangle.commons.orm.hibernate.HibernateTransactionManager.java

License:Open Source License

@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
    HibernateTransactionObject txObject = (HibernateTransactionObject) transaction;

    if (txObject.hasConnectionHolder() && !txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
        throw new IllegalTransactionStateException(
                "Pre-bound JDBC Connection found! HibernateTransactionManager does not support "
                        + "running within DataSourceTransactionManager if told to manage the DataSource itself. "
                        + "It is recommended to use a single HibernateTransactionManager for all transactions "
                        + "on a single DataSource, no matter whether Hibernate or JDBC access.");
    }/* w w w.j  av  a  2  s  .  c  o m*/

    Session session = null;

    try {
        if (txObject.getSessionHolder() == null
                || txObject.getSessionHolder().isSynchronizedWithTransaction()) {
            Interceptor entityInterceptor = getEntityInterceptor();
            Session newSession = (entityInterceptor != null ? getSessionFactory().openSession(entityInterceptor)
                    : getSessionFactory().openSession());
            if (logger.isDebugEnabled()) {
                logger.debug("Opened new Session [" + SessionUtils.toString(newSession)
                        + "] for Hibernate transaction");
            }
            txObject.setSession(newSession);
        }

        session = txObject.getSessionHolder().getSession();

        if (this.prepareConnection && isSameConnectionForEntireSession(session)) {
            // We're allowed to change the transaction settings of the JDBC Connection.
            if (logger.isDebugEnabled()) {
                logger.debug("Preparing JDBC Connection of Hibernate Session [" + SessionUtils.toString(session)
                        + "]");
            }
            @SuppressWarnings("deprecation")
            Connection con = session.connection();
            Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
            txObject.setPreviousIsolationLevel(previousIsolationLevel);
        } else {
            // Not allowed to change the transaction settings of the JDBC Connection.
            if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
                // We should set a specific isolation level but are not allowed to...
                throw new InvalidIsolationLevelException(
                        "HibernateTransactionManager is not allowed to support custom isolation levels: "
                                + "make sure that its 'prepareConnection' flag is on (the default) and that the "
                                + "Hibernate connection release mode is set to 'on_close' (BeangleTransactionFactory's default). "
                                + "Make sure that your SessionFactoryBean actually uses BeangleTransactionFactory: Your "
                                + "Hibernate properties should *not* include a 'hibernate.transaction.factory_class' property!");
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Not preparing JDBC Connection of Hibernate Session ["
                        + SessionUtils.toString(session) + "]");
            }
        }

        if (definition.isReadOnly() && txObject.isNewSession()) {
            // Just set to NEVER in case of a new Session for this transaction.
            session.setFlushMode(FlushMode.MANUAL);
        }

        if (!definition.isReadOnly() && !txObject.isNewSession()) {
            // We need AUTO or COMMIT for a non-read-only transaction.
            FlushMode flushMode = session.getFlushMode();
            if (flushMode.lessThan(FlushMode.COMMIT)) {
                session.setFlushMode(FlushMode.AUTO);
                txObject.getSessionHolder().setPreviousFlushMode(flushMode);
            }
        }

        Transaction hibTx;

        // Register transaction timeout.
        int timeout = determineTimeout(definition);
        if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
            // Use Hibernate's own transaction timeout mechanism on Hibernate 3.1+
            // Applies to all statements, also to inserts, updates and deletes!
            hibTx = session.getTransaction();
            hibTx.setTimeout(timeout);
            hibTx.begin();
        } else {
            // Open a plain Hibernate transaction without specified timeout.
            hibTx = session.beginTransaction();
        }

        // Add the Hibernate transaction to the session holder.
        txObject.getSessionHolder().setTransaction(hibTx);

        // Register the Hibernate Session's JDBC Connection for the DataSource, if set.
        if (getDataSource() != null) {
            @SuppressWarnings("deprecation")
            Connection con = session.connection();
            ConnectionHolder conHolder = new ConnectionHolder(con);
            if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
                conHolder.setTimeoutInSeconds(timeout);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Exposing Hibernate transaction as JDBC transaction [" + con + "]");
            }
            TransactionSynchronizationManager.bindResource(getDataSource(), conHolder);
            txObject.setConnectionHolder(conHolder);
        }

        // Bind the session holder to the thread.
        if (txObject.isNewSessionHolder()) {
            TransactionSynchronizationManager.bindResource(getSessionFactory(), txObject.getSessionHolder());
        }
        txObject.getSessionHolder().setSynchronizedWithTransaction(true);
    }

    catch (Exception ex) {
        if (txObject.isNewSession()) {
            try {
                if (session.getTransaction().isActive()) {
                    session.getTransaction().rollback();
                }
            } catch (Throwable ex2) {
                logger.debug("Could not rollback Session after failed transaction begin", ex);
            } finally {
                SessionUtils.closeSession(session);
            }
        }
        throw new CannotCreateTransactionException("Could not open Hibernate Session for transaction", ex);
    }
}

From source file:org.beangle.orm.hibernate.HibernateTransactionManager.java

License:Open Source License

@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
    HibernateTransactionObject txObject = (HibernateTransactionObject) transaction;

    if (txObject.hasConnectionHolder() && !txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
        throw new IllegalTransactionStateException(
                "Pre-bound JDBC Connection found! HibernateTransactionManager does not support "
                        + "running within DataSourceTransactionManager if told to manage the DataSource itself. "
                        + "It is recommended to use a single HibernateTransactionManager for all transactions "
                        + "on a single DataSource, no matter whether Hibernate or JDBC access.");
    }/*from w w  w .j a va2  s  .c om*/

    Session session = null;
    try {
        if (txObject.getSessionHolder() == null
                || txObject.getSessionHolder().isSynchronizedWithTransaction()) {
            Session newSession = getSessionFactory().openSession();
            txObject.setSession(newSession);
        }

        session = txObject.getSessionHolder().getSession();

        if (this.prepareConnection && isSameConnectionForEntireSession(session)) {
            // We're allowed to change the transaction settings of the JDBC Connection.
            Connection con = ((SessionImplementor) session).connection();
            Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
            txObject.setPreviousIsolationLevel(previousIsolationLevel);
        } else {
            // Not allowed to change the transaction settings of the JDBC Connection.
            if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
                // We should set a specific isolation level but are not allowed to...
                throw new InvalidIsolationLevelException(
                        "HibernateTransactionManager is not allowed to support custom isolation levels: "
                                + "make sure that its 'prepareConnection' flag is on (the default) and that the "
                                + "Hibernate connection release mode is set to 'on_close' (BeangleTransactionFactory's default). "
                                + "Make sure that your SessionFactoryBean actually uses BeangleTransactionFactory: Your "
                                + "Hibernate properties should *not* include a 'hibernate.transaction.factory_class' property!");
            }
        }

        if (definition.isReadOnly() && txObject.isNewSession()) {
            // Just set to NEVER in case of a new Session for this transaction.
            session.setFlushMode(FlushMode.MANUAL);
        }

        if (!definition.isReadOnly() && !txObject.isNewSession()) {
            // We need AUTO or COMMIT for a non-read-only transaction.
            FlushMode flushMode = session.getFlushMode();
            if (FlushMode.isManualFlushMode(session.getFlushMode())) {
                session.setFlushMode(FlushMode.AUTO);
                txObject.getSessionHolder().setPreviousFlushMode(flushMode);
            }
        }

        Transaction hibTx;

        // Register transaction timeout.
        int timeout = determineTimeout(definition);
        if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
            // Use Hibernate's own transaction timeout mechanism on Hibernate 3.1+
            // Applies to all statements, also to inserts, updates and deletes!
            hibTx = session.getTransaction();
            hibTx.setTimeout(timeout);
            hibTx.begin();
        } else {
            // Open a plain Hibernate transaction without specified timeout.
            hibTx = session.beginTransaction();
        }

        // Add the Hibernate transaction to the session holder.
        txObject.getSessionHolder().setTransaction(hibTx);

        // Register the Hibernate Session's JDBC Connection for the DataSource, if set.
        if (getDataSource() != null) {
            Connection con = ((SessionImplementor) session).connection();
            ConnectionHolder conHolder = new ConnectionHolder(con);
            if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
                conHolder.setTimeoutInSeconds(timeout);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Exposing Hibernate transaction as JDBC transaction [" + con + "]");
            }
            TransactionSynchronizationManager.bindResource(getDataSource(), conHolder);
            txObject.setConnectionHolder(conHolder);
        }

        // Bind the session holder to the thread.
        if (txObject.isNewSessionHolder()) {
            TransactionSynchronizationManager.bindResource(getSessionFactory(), txObject.getSessionHolder());
        }
        txObject.getSessionHolder().setSynchronizedWithTransaction(true);
    }

    catch (Exception ex) {
        if (txObject.isNewSession()) {
            try {
                if (session.getTransaction().isActive())
                    session.getTransaction().rollback();
            } catch (Throwable ex2) {
                logger.debug("Could not rollback Session after failed transaction begin", ex);
            } finally {
                SessionUtils.closeSession(session);
            }
        }
        throw new CannotCreateTransactionException("Could not open Hibernate Session for transaction", ex);
    }
}

From source file:org.castafiore.persistence.DaoImpl.java

License:Open Source License

public Session getSession() {
    try {/* w  w w. j a  v a 2s.  co m*/
        Session session = SESSION_THREAD.get();
        if (session == null || !session.isOpen()) {
            session = getHibernateTemplate().getSessionFactory().openSession();
            session.setFlushMode(FlushMode.MANUAL);
            //session.setCacheMode(CacheMode.IGNORE);
            SESSION_THREAD.set(session);
        }

        Transaction t = TRANSACTION_THREAD.get();
        if (t == null) {
            t = session.beginTransaction();
            t.setTimeout(9000);
            TRANSACTION_THREAD.set(t);

        } else {
            if (!t.isActive()) {
                t.begin();
            }
        }
        return session;

    } catch (Exception e) {
        //return HibernateUtil.getSession(getHibernateTemplate().getSessionFactory());
        throw new RuntimeException(e);
    }
}

From source file:org.jpos.ee.action.Open.java

License:Open Source License

private void setVisitor(JPublishContext context, Session hs) throws HibernateException {
    HttpServletRequest request = context.getRequest();
    Cookie[] cookies = request.getCookies();
    if (cookies == null)
        cookies = new Cookie[0];
    VisitorManager vmgr = new VisitorManager(hs, cookies);
    Transaction tx = hs.beginTransaction();
    tx.setTimeout(5);
    Visitor visitor = vmgr.getVisitor(true);
    vmgr.set(visitor, "IP", request.getRemoteAddr());
    vmgr.set(visitor, "HOST", request.getRemoteHost());
    vmgr.update(visitor);/* w ww .  ja  va2 s. c o  m*/
    context.getResponse().addCookie(vmgr.getCookie());
    context.put(VISITOR, visitor);

    User u = visitor.getUser();
    if (u != null && !u.isDeleted()) {
        context.getSession().setAttribute(USER, u);
        context.put(USER, u);
    }
    try {
        tx.commit();
    } catch (RuntimeException ex) {
        try {
            tx.rollback();
        } catch (RuntimeException rte) {
            context.getSyslog().warn(rte);
        }
        throw ex;
    }
}

From source file:org.jpos.ee.DB.java

License:Open Source License

/**
 * @param timeout in seconds/*  w ww .jav a2  s .com*/
 * @return newly created Transaction
 * @throws HibernateException
 */
public synchronized Transaction beginTransaction(int timeout) throws HibernateException {
    Transaction tx = session.beginTransaction();
    if (timeout > 0) {
        tx.setTimeout(timeout);
    }
    return tx;
}

From source file:org.jpos.gl.GLSession.java

License:Open Source License

/**
 * Begin hibernate transaction.//from  w w w.  j  ava 2 s. c  om
 * @param timeout timeout in seconds
 * @return new Transaction
 */
public Transaction beginTransaction(int timeout) throws HibernateException {
    Transaction tx = session.beginTransaction();
    if (timeout > 0)
        tx.setTimeout(timeout);
    return tx;
}

From source file:org.opentaps.tests.entity.HibernateTests.java

License:Open Source License

/**
 * Tests transaction roll back due to timeout.
 *
 * @throws Exception if an error occurs/* w  ww  . j  av a2 s .  c  om*/
 */
@SuppressWarnings("unchecked")
public void testTransactionTimeoutRollback() throws Exception {
    // open a new session, if session has opened, then close it first
    reOpenSession();
    // store TestEntity ids
    String ids = "";
    // open a transaction
    Transaction tx = session.getTransaction();
    tx.setTimeout(10);
    tx.begin();
    try {
        // try to create 10 TestEntity values with auto-sequenced keys, but
        // waiting 5 seconds between creating each entity
        for (int i = 0; i < 10; i++) {
            TestEntity testEntity = new TestEntity();
            testEntity.setTestStringField("string value");
            Thread.sleep(5000);
            session.save(testEntity);
            ids = ids.equals("") ? "'" + testEntity.getTestId() + "'"
                    : ids + ",'" + testEntity.getTestId() + "'";
        }
        session.flush();
        // try to close the transaction but this should not work because we
        // should have been rolled back already
        tx.commit();
    } catch (HibernateException ex) {
        Debug.logInfo("A timeout exception is expected here", MODULE);
        Debug.logError(ex, MODULE);
        try {
            tx.rollback();
        } catch (HibernateException e) {
            Debug.logError("Couldn't roll back transaction " + e, MODULE);
        } finally {
            // all hibernate exception is fatal, we need reopen session to
            // continue other work.
            reOpenSession();
        }
    }

    // verify that none of the 10 values could be found
    String hql = "from TestEntity eo where eo.testId in (" + ids + ")";
    Query query = session.createQuery(hql);
    List<TestEntity> list = query.list();
    assertEquals("Shouldn't have found any TestEntity with query [" + hql + "]", 0, list.size());
}

From source file:org.opentaps.tests.entity.HibernateTests.java

License:Open Source License

/**
 * Tests transaction completes successfully with longer timeout.
 *
 * @throws Exception if an error occurs//from   www  .j a  va 2  s  .co m
 */
@SuppressWarnings("unchecked")
public void testTransactionSetTimeout() throws Exception {
    // open a new session, if session has opened, then close it first
    reOpenSession();
    // store TestEntity ids
    String ids = "";
    // open a transaction
    Transaction tx = session.getTransaction();
    // set the transaction timeout to 100 seconds
    tx.setTimeout(100);
    tx.begin();
    try {
        // try to create 10 TestEntity values with auto-sequenced keys, but
        // waiting 5 seconds between creating each entity
        for (int i = 0; i < 10; i++) {
            TestEntity testEntity = new TestEntity();
            testEntity.setTestStringField("string value");
            Thread.sleep(5000);
            session.save(testEntity);
            ids = ids.equals("") ? "'" + testEntity.getTestId() + "'"
                    : ids + ",'" + testEntity.getTestId() + "'";
        }
        session.flush();
        // commit the transaction
        tx.commit();
    } catch (HibernateException ex) {
        Debug.logError(ex, MODULE);
        try {
            tx.rollback();
        } catch (HibernateException e) {
            Debug.logError("Couldn't rool back transcation " + e, MODULE);
        } finally {
            // all hibernate exception is fatal, we need reopen session to
            // continue other work.
            reOpenSession();
        }
    }
    // verify that all 10 values could be found
    String hql = "from TestEntity eo where eo.testId in (" + ids + ")";
    Query query = session.createQuery(hql);
    List<TestEntity> list = query.list();
    assertEquals("Should have found 10 TestEntity with [" + hql + "]", 10, list.size());
}