Example usage for org.hibernate StatelessSession close

List of usage examples for org.hibernate StatelessSession close

Introduction

In this page you can find the example usage for org.hibernate StatelessSession close.

Prototype

void close();

Source Link

Document

Close the stateless session and release the JDBC connection.

Usage

From source file:com.denimgroup.threadfix.data.dao.hibernate.HibernateGenericVulnerabilityDao.java

License:Mozilla Public License

@Override
public void insertAll(List<GenericVulnerability> vulnerabilityList) {

    StatelessSession statelessSession = sessionFactory.openStatelessSession();
    Transaction transaction = statelessSession.beginTransaction();

    try {/* www  .j  a v  a 2 s.  c  om*/
        for (GenericVulnerability vulnerability : vulnerabilityList) {
            statelessSession.insert(vulnerability);
        }

        transaction.commit();
    } catch (Exception e) {
        transaction.rollback();
    } finally {
        statelessSession.close();
    }
}

From source file:com.ephesoft.dcma.dbexport.DbExporter.java

License:Open Source License

private void exportMetaDataToDB(final String dbTable, final String batchId, final String batchClass,
        final String docType, final String docField, final String docFieldValue,
        final String mappedDbTableColumn) throws DCMAApplicationException {
    String errorMessage = "DB Export Plugin: Problem occured in updating database table ";
    Connection connection = null;
    try {/*from   ww  w.  j a  va  2 s . c  o  m*/
        LOGGER.info("Preparing Query..");
        connection = dynamicHibernateDao.getConnectionProvider().getConnection();
        StatelessSession statelessSession = dynamicHibernateDao.getStatelessSession(connection);
        Transaction transaction = statelessSession.getTransaction();
        StringBuffer dbQueryBuffer = new StringBuffer(DbExportConstant.INSERT_INTO);
        dbQueryBuffer.append(dbTable);

        String columnNames = prepareColumnNamesString(mappedDbTableColumn);
        dbQueryBuffer.append(columnNames);

        String values = prepareQueryValues(batchId, batchClass, docType, docField, docFieldValue);
        dbQueryBuffer.append(values);

        String dbQuery = null;
        dbQuery = dbQueryBuffer.toString();
        LOGGER.info("Prepared query : " + dbQuery);

        SQLQuery query = dynamicHibernateDao.createUpdateOrInsertQuery(statelessSession, dbQuery);
        transaction.begin();
        int result = query.executeUpdate();
        transaction.commit();
        statelessSession.close();
        LOGGER.info("DB Export Plugin: Result of SQL commital transaction = " + result);
    } catch (HibernateException e) {
        LOGGER.error(errorMessage + dbTable + e.getMessage(), e);
        throw new DCMAApplicationException(errorMessage + dbTable + e.getMessage(), e);
    } catch (SQLException e) {
        LOGGER.error(errorMessage + dbTable + e.getMessage(), e);
        throw new DCMAApplicationException(errorMessage + dbTable + e.getMessage(), e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                LOGGER.error("Error closing the database session: " + e.getMessage(), e);
            }
        }
        if (dynamicHibernateDao != null) {
            dynamicHibernateDao.closeSession();
        }
    }
}

From source file:com.ephesoft.gxt.systemconfig.server.SystemConfigServiceImpl.java

License:Open Source License

@Override
public boolean testConnection(String connectionURL, String userName, String password, String driverClass) {
    boolean connectionSuccessful = false;
    if (!StringUtil.isNullOrEmpty(connectionURL) || !StringUtil.isNullOrEmpty(userName)
            || !StringUtil.isNullOrEmpty(password) || !StringUtil.isNullOrEmpty(driverClass)) {
        try {//  w  w w  .  jav a 2s.c om
            final DynamicHibernateDao dao = HibernateDaoUtil.testHibernateDaoConnection(driverClass,
                    connectionURL, userName, password);
            try {
                StatelessSession session = dao.getStatelessSession();
                connectionSuccessful = true;
                session.close();
            } catch (DCMAException dcmaException) {
                // TODO Auto-generated catch block
                connectionSuccessful = false;
                LOGGER.error(
                        StringUtil.concatenate("Unable to establish connection.", dcmaException.getMessage()));
            } finally {
                dao.closeSession();
            }

        } catch (DCMAException dcmaException) {
            // TODO Auto-generated catch block
            LOGGER.info(StringUtil.concatenate("Unable to connect to Database.", dcmaException.getMessage()));
        }
    }
    return connectionSuccessful;
}

From source file:com.jredrain.dao.HibernateDao.java

License:Apache License

@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
protected <T> void save(List<T> entities) {
    StatelessSession session = sessionFactory.openStatelessSession();
    for (T entity : entities) {
        session.update(entity);//from www  . j  av a2 s. c o m
    }
    session.close();
}

From source file:com.romeikat.datamessie.core.base.util.hibernate.HibernateSessionProvider.java

License:Open Source License

private void closeStatelessSession(final StatelessSession statelessSession) {
    try {/*from w w w .j a v  a 2s.c  o m*/
        statelessSession.close();
    } catch (final Exception e) {
        LOG.warn("Could not close stateless session", e);
    }
}

From source file:com.sapienter.jbilling.server.util.db.HibernateIdGenerator.java

License:Open Source License

public Serializable getId() {
    StatelessSession session = sessionFactory.openStatelessSession();
    Serializable id = generator.generate((StatelessSessionImpl) session, new ID());
    session.close();
    return id;/* w ww .  ja va  2 s . c  o  m*/
}

From source file:com.twinsoft.convertigo.engine.billing.HibernateTicketManager.java

License:Open Source License

public synchronized Ticket peekTicket() throws BillingException {
    final Ticket[] ticket = { null };
    hibernateHelper.retry(new Runnable() {
        @Override/*from   w w  w . jav a2  s . c om*/
        public void run() {
            StatelessSession session = hibernateHelper.getSession();
            try {
                ticket[0] = (Ticket) session.createCriteria(Ticket.class).setMaxResults(1).uniqueResult();
                ;
                if (log.isDebugEnabled()) {
                    log.debug("(HibernateTicketManager) peekTicket " + ticket[0]);
                }
            } finally {
                session.close();
            }
        }
    });
    return ticket[0];
}

From source file:com.twinsoft.convertigo.engine.SecurityTokenManager.java

License:Open Source License

public synchronized SecurityToken consumeToken(final String tokenID)
        throws NoSuchSecurityTokenException, ExpiredSecurityTokenException {
    final SecurityToken[] token = { null };

    Engine.logSecurityTokenManager.debug("(SecurityTokenManager) Try to consume tokenID: '" + tokenID + "'");

    removeExpired();//from   ww w.ja v a 2  s. com

    if (tokens != null) {
        token[0] = tokens.get(tokenID);
        if (Engine.logSecurityTokenManager.isDebugEnabled()) {
            Engine.logSecurityTokenManager
                    .debug("(SecurityTokenManager) Memory tokens manager retrieves: " + token[0]);
        }
    }

    if (hibernateHelper != null) {
        hibernateHelper.retry(new Runnable() {
            @Override
            public void run() {
                StatelessSession session = hibernateHelper.getSession();
                try {
                    token[0] = (SecurityToken) session.createCriteria(SecurityToken.class)
                            .add(Restrictions.eq("tokenID", tokenID)).uniqueResult();
                } finally {
                    session.close();
                }
            }
        });

        if (Engine.logSecurityTokenManager.isDebugEnabled()) {
            Engine.logSecurityTokenManager
                    .debug("(SecurityTokenManager) Database tokens manager retrieves: " + token[0]);
        }
    }

    if (token[0] == null) {
        Engine.logSecurityTokenManager.debug("(SecurityTokenManager) Not found tokenID: '" + tokenID + "'");
        throw new NoSuchSecurityTokenException(tokenID);
    }

    if (tokens != null) {
        tokens.remove(tokenID);
    }

    if (hibernateHelper != null) {
        hibernateHelper.delete(token[0]);
    }

    if (token[0].isExpired()) {
        Engine.logSecurityTokenManager.debug("(SecurityTokenManager) Expired tokenID: '" + tokenID + "'");
        throw new ExpiredSecurityTokenException(tokenID);
    }

    Engine.logSecurityTokenManager.debug("(SecurityTokenManager) The security token is: '" + token[0] + "'");
    return token[0];
}

From source file:edu.psu.iam.cpr.batch.processor.impl.AddressBatchProcessor.java

License:Creative Commons License

/**
 * This method implements the core logic of the batch processor.
 * @param databaseSession contains the database session from the abstract class that will be used to iterator over the individual records.
 * @param messagingCore contains a reference to the messaging infrastructure.
 * @param dataQualityService contains a reference to the data quality service.
 * @throws CprException will be thrown for any Cpr Related problems.
 * @throws JSONException will be thrown for any JSON problems.
 * @throws JMSException will be thrown for any messaging problems.
 *///from www. j  a  va2s . c  o  m
@Override
public void implementBatchProcessor(StatelessSession databaseSession, MessagingCore messagingCore,
        DataQualityService dataQualityService)
        throws CprException, ParseException, JSONException, JMSException {

    final Date d = new Date();

    // Calculate the start and end date/times based on the current date.
    setStartDateTime(Utility.makeStartDate(d));
    setEndDateTime(Utility.makeEndDate(d));

    // Do a select to find all of the people who have had an address changed for the current date.
    final Query query = databaseSession
            .createQuery("from AddressStaging where importDate BETWEEN :start_date AND :end_date");
    query.setFetchSize(RECORD_FETCH_SIZE);
    query.setParameter("start_date", startDateTime);
    query.setParameter("end_date", endDateTime);

    // Init some objects.
    StatelessSession recordSession = SessionFactoryUtil.getSessionFactory().openStatelessSession();
    final AddressPostProcessor addressPostProcessor = new AddressPostProcessor(recordSession, messagingCore);
    final ChangeNotification changeNotification = new ChangeNotification(recordSession, messagingCore);
    final PersonBio personBio = new PersonBio(recordSession, BatchDataSource.ADDRESS_POSTPROCESS,
            dataQualityService);
    Transaction tx = null;

    // Loop through the results.
    for (final Iterator<?> it = query.list().iterator(); it.hasNext();) {
        AddressStaging bean = (AddressStaging) it.next();
        final Long personId = bean.getPersonId();

        try {

            tx = recordSession.beginTransaction();

            // Process an address change for a person.
            addressPostProcessor.resetHistoryBeans();
            addressPostProcessor.processAddressChange(personId, AddressType.get(bean.getDataTypeKey()));

            // Only check for messaging if there was a change.
            if (addressPostProcessor.getOldAddressBean() != null
                    || addressPostProcessor.getNewAddressBean() != null) {

                // Find the person using their person identifier.
                Long pid = personBio.findPersonUsingPersonId(personId);
                if (pid != null && pid.equals(personId)) {

                    // Set the required information for a json message.
                    if (addressPostProcessor.getNewAddressBean() != null) {

                        changeNotification.setRequiredInfo(personId, personBio.getPsuIdNumber(),
                                personBio.getPrimaryUserid(),
                                addressPostProcessor.getNewAddressBean().getImportFrom());

                        // Address change.
                        changeNotification.addressChange(addressPostProcessor.getOldAddressBean(),
                                addressPostProcessor.getNewAddressBean());
                    } else {
                        LOG.info(
                                "Address Post Process Batch: expired old address, but did not add a new one for person identifier : "
                                        + personId);
                    }
                }
            }

            tx.commit();
        } catch (HibernateException e) { // $codepro.audit.disable logExceptions
            LOG.error("Address Post Processor Batch: error encountered person identifier : " + personId);
            tx.rollback();
            recordSession.close();
            recordSession = SessionFactoryUtil.getSessionFactory().openStatelessSession();
            addressPostProcessor.setStatelessSession(recordSession);
            changeNotification.setStatelessSession(recordSession);
            personBio.setDatabaseSession(recordSession);
        }
    }

    try {
        recordSession.close();
    } catch (Exception e) { // $codepro.audit.disable emptyCatchClause
    }

}

From source file:edu.psu.iam.cpr.batch.processor.impl.EmployeeBatchProcessor.java

License:Creative Commons License

@Override
public void implementBatchProcessor(final StatelessSession databaseSession, final MessagingCore messagingCore,
        final DataQualityService dataQualityService) throws CprException, JSONException, JMSException {

    final long startTime, stopTime;
    final long totalRecords;
    long recordsProcessed = 0;

    startTime = System.currentTimeMillis();

    // Perform a query for all of the trans empl records.
    final Query query = databaseSession.createQuery("FROM TransEmpl ORDER BY codeApptType ASC");
    query.setFetchSize(RECORD_FETCH_SIZE);

    StatelessSession recordSession = SessionFactoryUtil.getSessionFactory().openStatelessSession();
    final EmployeeInfo employeeInfo = new EmployeeInfo(recordSession, BATCH_DATA_SOURCE, dataQualityService);
    final ChangeNotification changeNotification = new ChangeNotification(recordSession, messagingCore);
    affiliationCalculator = new EduPersonAffiliationCalculator(recordSession, BATCH_DATA_SOURCE,
            dataQualityService);/* ww  w.j  ava  2  s.  c  o m*/

    Transaction tx = null;

    final List<?> queryList = query.list();
    totalRecords = queryList.size();

    // Loop for all of the records that were found.
    for (final Iterator<?> it = queryList.iterator(); it.hasNext();) {
        final TransEmpl transEmpl = (TransEmpl) it.next();
        recordsProcessed++;

        fixBogusData(transEmpl);

        try {
            // Begin transaction.
            tx = recordSession.beginTransaction();

            employeeInfo.resetHistoryBeans();
            affiliationCalculator.resetHistoryBeans();

            employeeInfo.setRecordNumber(transEmpl.getTransEmplKey().longValue());
            employeeInfo.findPerson(transEmpl.getPsuId());

            final Long personId = employeeInfo.getPersonId();
            if (personId == null) {
                addEmployee(transEmpl, employeeInfo, changeNotification);
            } else {
                updateEmployee(transEmpl, employeeInfo, changeNotification);
            }

            // Commit!
            tx.commit();
        } catch (final HibernateException ex) {

            // Log the error.
            LOG.error(BATCH_DATA_SOURCE.toString() + " Batch: error encountered on record #: "
                    + transEmpl.getTransEmplKey(), ex);

            // Rollback the transaction, close the session.
            tx.rollback();
            recordSession.close();

            // We need to create a new session and update the person bio with the new session.
            recordSession = SessionFactoryUtil.getSessionFactory().openStatelessSession();
            employeeInfo.setDatabaseSession(recordSession);
            changeNotification.setStatelessSession(recordSession);
            affiliationCalculator.setDatabaseSession(recordSession);
        } catch (final CprException ex) {

            // Log the error.
            LOG.error(BATCH_DATA_SOURCE.toString() + " Batch: error encountered on record #: "
                    + transEmpl.getTransEmplKey(), ex);
            throw ex;
        }
    }

    try {
        recordSession.close();
    } catch (final HibernateException e) {

        // Rollback the transaction, close the session.
        tx.rollback();
        recordSession.close();

        // We need to create a new session and update the helper classes with the new session.
        recordSession = SessionFactoryUtil.getSessionFactory().openStatelessSession();
        employeeInfo.setDatabaseSession(recordSession);
        changeNotification.setStatelessSession(recordSession);
        affiliationCalculator.setDatabaseSession(recordSession);
    }

    stopTime = System.currentTimeMillis();
    final double elapsedTime = ((double) stopTime - startTime) / 1000;

    LOG.info(BATCH_DATA_SOURCE.toString() + " Batch: processed " + recordsProcessed + " records out of "
            + totalRecords + " in " + elapsedTime + " seconds");
}