Example usage for org.springframework.dao DataAccessResourceFailureException DataAccessResourceFailureException

List of usage examples for org.springframework.dao DataAccessResourceFailureException DataAccessResourceFailureException

Introduction

In this page you can find the example usage for org.springframework.dao DataAccessResourceFailureException DataAccessResourceFailureException.

Prototype

public DataAccessResourceFailureException(String msg, @Nullable Throwable cause) 

Source Link

Document

Constructor for DataAccessResourceFailureException.

Usage

From source file:org.springframework.orm.hibernate4.support.OpenSessionInViewInterceptor.java

/**
 * Open a Session for the SessionFactory that this interceptor uses.
 * <p>The default implementation delegates to the {@link SessionFactory#openSession}
 * method and sets the {@link Session}'s flush mode to "MANUAL".
 * @return the Session to use//  ww  w .j  a v  a 2s.  c o  m
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @see org.hibernate.FlushMode#MANUAL
 */
protected Session openSession() throws DataAccessResourceFailureException {
    try {
        Session session = getSessionFactory().openSession();
        session.setFlushMode(FlushMode.MANUAL);
        return session;
    } catch (HibernateException ex) {
        throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
    }
}

From source file:org.springframework.orm.hibernate5.support.OpenSessionInViewInterceptor.java

/**
 * Open a Session for the SessionFactory that this interceptor uses.
 * <p>The default implementation delegates to the {@link SessionFactory#openSession}
 * method and sets the {@link Session}'s flush mode to "MANUAL".
 * @return the Session to use/*from  w  w w.j av a 2s. c  o m*/
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @see FlushMode#MANUAL
 */
@SuppressWarnings("deprecation")
protected Session openSession() throws DataAccessResourceFailureException {
    try {
        Session session = obtainSessionFactory().openSession();
        session.setFlushMode(FlushMode.MANUAL);
        return session;
    } catch (HibernateException ex) {
        throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
    }
}

From source file:org.springframework.orm.jdo.PersistenceManagerFactoryUtils.java

/**
 * Obtain a JDO PersistenceManager via the given factory. Is aware of a
 * corresponding PersistenceManager bound to the current thread,
 * for example when using JdoTransactionManager. Will create a new
 * PersistenceManager else, if "allowCreate" is {@code true}.
 * @param pmf PersistenceManagerFactory to create the PersistenceManager with
 * @param allowCreate if a non-transactional PersistenceManager should be created
 * when no transactional PersistenceManager can be found for the current thread
 * @return the PersistenceManager/*ww w. java 2s  .co m*/
 * @throws DataAccessResourceFailureException if the PersistenceManager couldn't be obtained
 * @throws IllegalStateException if no thread-bound PersistenceManager found and
 * "allowCreate" is {@code false}
 * @see JdoTransactionManager
 */
public static PersistenceManager getPersistenceManager(PersistenceManagerFactory pmf, boolean allowCreate)
        throws DataAccessResourceFailureException, IllegalStateException {

    try {
        return doGetPersistenceManager(pmf, allowCreate);
    } catch (JDOException ex) {
        throw new DataAccessResourceFailureException("Could not obtain JDO PersistenceManager", ex);
    }
}

From source file:org.springframework.orm.jpa.EntityManagerFactoryUtils.java

/**
 * Obtain a JPA EntityManager from the given factory. Is aware of a corresponding
 * EntityManager bound to the current thread, e.g. when using JpaTransactionManager.
 * <p>Note: Will return {@code null} if no thread-bound EntityManager found!
 * @param emf EntityManagerFactory to create the EntityManager with
 * @param properties the properties to be passed into the {@code createEntityManager}
 * call (may be {@code null})/*ww w  . j av  a  2s.c o m*/
 * @return the EntityManager, or {@code null} if none found
 * @throws DataAccessResourceFailureException if the EntityManager couldn't be obtained
 * @see JpaTransactionManager
 */
@Nullable
public static EntityManager getTransactionalEntityManager(EntityManagerFactory emf,
        @Nullable Map<?, ?> properties) throws DataAccessResourceFailureException {
    try {
        return doGetTransactionalEntityManager(emf, properties, true);
    } catch (PersistenceException ex) {
        throw new DataAccessResourceFailureException("Could not obtain JPA EntityManager", ex);
    }
}

From source file:org.springframework.orm.jpa.vendor.HibernateJpaDialect.java

/**
 * Convert the given HibernateException to an appropriate exception
 * from the {@code org.springframework.dao} hierarchy.
 * @param ex HibernateException that occurred
 * @return the corresponding DataAccessException instance
 *///from  w ww . j  a  va 2  s. c om
protected DataAccessException convertHibernateAccessException(HibernateException ex) {
    if (ex instanceof JDBCConnectionException) {
        return new DataAccessResourceFailureException(ex.getMessage(), ex);
    }
    if (ex instanceof SQLGrammarException) {
        SQLGrammarException jdbcEx = (SQLGrammarException) ex;
        return new InvalidDataAccessResourceUsageException(ex.getMessage() + "; SQL [" + jdbcEx.getSQL() + "]",
                ex);
    }
    if (ex instanceof QueryTimeoutException) {
        QueryTimeoutException jdbcEx = (QueryTimeoutException) ex;
        return new org.springframework.dao.QueryTimeoutException(
                ex.getMessage() + "; SQL [" + jdbcEx.getSQL() + "]", ex);
    }
    if (ex instanceof LockAcquisitionException) {
        LockAcquisitionException jdbcEx = (LockAcquisitionException) ex;
        return new CannotAcquireLockException(ex.getMessage() + "; SQL [" + jdbcEx.getSQL() + "]", ex);
    }
    if (ex instanceof PessimisticLockException) {
        PessimisticLockException jdbcEx = (PessimisticLockException) ex;
        return new PessimisticLockingFailureException(ex.getMessage() + "; SQL [" + jdbcEx.getSQL() + "]", ex);
    }
    if (ex instanceof ConstraintViolationException) {
        ConstraintViolationException jdbcEx = (ConstraintViolationException) ex;
        return new DataIntegrityViolationException(ex.getMessage() + "; SQL [" + jdbcEx.getSQL()
                + "]; constraint [" + jdbcEx.getConstraintName() + "]", ex);
    }
    if (ex instanceof DataException) {
        DataException jdbcEx = (DataException) ex;
        return new DataIntegrityViolationException(ex.getMessage() + "; SQL [" + jdbcEx.getSQL() + "]", ex);
    }
    // end of JDBCException subclass handling

    if (ex instanceof QueryException) {
        return new InvalidDataAccessResourceUsageException(ex.getMessage(), ex);
    }
    if (ex instanceof NonUniqueResultException) {
        return new IncorrectResultSizeDataAccessException(ex.getMessage(), 1, ex);
    }
    if (ex instanceof NonUniqueObjectException) {
        return new DuplicateKeyException(ex.getMessage(), ex);
    }
    if (ex instanceof PropertyValueException) {
        return new DataIntegrityViolationException(ex.getMessage(), ex);
    }
    if (ex instanceof PersistentObjectException) {
        return new InvalidDataAccessApiUsageException(ex.getMessage(), ex);
    }
    if (ex instanceof TransientObjectException) {
        return new InvalidDataAccessApiUsageException(ex.getMessage(), ex);
    }
    if (ex instanceof ObjectDeletedException) {
        return new InvalidDataAccessApiUsageException(ex.getMessage(), ex);
    }
    if (ex instanceof UnresolvableObjectException) {
        UnresolvableObjectException hibEx = (UnresolvableObjectException) ex;
        return new ObjectRetrievalFailureException(hibEx.getEntityName(), hibEx.getIdentifier(),
                ex.getMessage(), ex);
    }
    if (ex instanceof WrongClassException) {
        WrongClassException hibEx = (WrongClassException) ex;
        return new ObjectRetrievalFailureException(hibEx.getEntityName(), hibEx.getIdentifier(),
                ex.getMessage(), ex);
    }
    if (ex instanceof StaleObjectStateException) {
        StaleObjectStateException hibEx = (StaleObjectStateException) ex;
        return new ObjectOptimisticLockingFailureException(hibEx.getEntityName(), hibEx.getIdentifier(), ex);
    }
    if (ex instanceof StaleStateException) {
        return new ObjectOptimisticLockingFailureException(ex.getMessage(), ex);
    }
    if (ex instanceof OptimisticEntityLockException) {
        return new ObjectOptimisticLockingFailureException(ex.getMessage(), ex);
    }
    if (ex instanceof PessimisticEntityLockException) {
        if (ex.getCause() instanceof LockAcquisitionException) {
            return new CannotAcquireLockException(ex.getMessage(), ex.getCause());
        }
        return new PessimisticLockingFailureException(ex.getMessage(), ex);
    }

    // fallback
    return new JpaSystemException(ex);
}

From source file:org.springframework.orm.ojb.OjbFactoryUtils.java

/**
 * Get an OJB PersistenceBroker for the given PBKey. Is aware of a
 * corresponding PersistenceBroker bound to the current thread, for
 * example when using PersistenceBrokerTransactionManager. Will
 * create a new PersistenceBroker else, if allowCreate is true.
 * @param pbKey PBKey to create the PersistenceBroker for
 * @param allowCreate if a non-transactional PersistenceBroker should be created
 * when no transactional PersistenceBroker can be found for the current thread
 * @return the PersistenceBroker/*from  w  w w  .j ava2  s  .  c  om*/
 * @throws DataAccessResourceFailureException if the PersistenceBroker couldn't be created
 * @throws IllegalStateException if no thread-bound PersistenceBroker found and allowCreate false
 */
public static PersistenceBroker getPersistenceBroker(PBKey pbKey, boolean allowCreate)
        throws DataAccessResourceFailureException, IllegalStateException {

    PersistenceBrokerHolder pbHolder = (PersistenceBrokerHolder) TransactionSynchronizationManager
            .getResource(pbKey);
    if (pbHolder != null) {
        return pbHolder.getPersistenceBroker();
    }

    if (!allowCreate && !TransactionSynchronizationManager.isSynchronizationActive()) {
        throw new IllegalStateException("No OJB PersistenceBroker bound to thread, "
                + "and configuration does not allow creation of non-transactional one here");
    }

    try {
        logger.debug("Opening OJB PersistenceBroker");
        PersistenceBroker pb = PersistenceBrokerFactory.createPersistenceBroker(pbKey);

        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            logger.debug("Registering transaction synchronization for OJB PersistenceBroker");
            // Use same PersistenceBroker for further OJB actions within the transaction.
            // Thread object will get removed by synchronization at transaction completion.
            pbHolder = new PersistenceBrokerHolder(pb);
            pbHolder.setSynchronizedWithTransaction(true);
            TransactionSynchronizationManager
                    .registerSynchronization(new PersistenceBrokerSynchronization(pbHolder, pbKey));
            TransactionSynchronizationManager.bindResource(pbKey, pbHolder);
        }

        return pb;
    } catch (OJBRuntimeException ex) {
        throw new DataAccessResourceFailureException("Could not open OJB PersistenceBroker", ex);
    }
}

From source file:org.springframework.orm.toplink.SessionFactoryUtils.java

/**
 * Get a TopLink Session for the given SessionFactory. Is aware of and will
 * return any existing corresponding Session bound to the current thread, for
 * example when using TopLinkTransactionManager. Will create a new Session
 * otherwise, if "allowCreate" is <code>true</code>.
 * <p>This is the <code>getSession</code> method used by typical data access code,
 * in combination with <code>releaseSession</code> called when done with
 * the Session. Note that TopLinkTemplate allows to write data access code
 * without caring about such resource handling.
 * @param sessionFactory TopLink SessionFactory to create the session with
 * @param allowCreate if a non-transactional Session should be created when no
 * transactional Session can be found for the current thread
 * @return the TopLink Session//  w  w  w . ja v a2s .c om
 * @throws DataAccessResourceFailureException if the Session couldn't be created
 * @throws IllegalStateException if no thread-bound Session found and
 * "allowCreate" is <code>false</code>
 * @see #releaseSession
 * @see TopLinkTemplate
 */
public static Session getSession(SessionFactory sessionFactory, boolean allowCreate)
        throws DataAccessResourceFailureException, IllegalStateException {

    try {
        return doGetSession(sessionFactory, allowCreate);
    } catch (TopLinkException ex) {
        throw new DataAccessResourceFailureException("Could not open TopLink Session", ex);
    }
}

From source file:org.springframework.test.jdbc.SimpleJdbcTestUtils.java

/**
 * Execute the given SQL script.//from   w ww .j a  va 2s. c  om
 * <p>The script will normally be loaded by classpath. There should be one statement
 * per line. Any semicolons will be removed. <b>Do not use this method to execute
 * DDL if you expect rollback.</b>
 * @param simpleJdbcTemplate the SimpleJdbcTemplate with which to perform JDBC operations
 * @param resource the resource (potentially associated with a specific encoding)
 * to load the SQL script from.
 * @param continueOnError whether or not to continue without throwing an
 * exception in the event of an error.
 * @throws DataAccessException if there is an error executing a statement
 * and continueOnError was {@code false}
 */
public static void executeSqlScript(SimpleJdbcTemplate simpleJdbcTemplate, EncodedResource resource,
        boolean continueOnError) throws DataAccessException {

    if (logger.isInfoEnabled()) {
        logger.info("Executing SQL script from " + resource);
    }

    long startTime = System.currentTimeMillis();
    List<String> statements = new LinkedList<String>();
    LineNumberReader reader = null;
    try {
        reader = new LineNumberReader(resource.getReader());
        String script = JdbcTestUtils.readScript(reader);
        char delimiter = ';';
        if (!JdbcTestUtils.containsSqlScriptDelimiters(script, delimiter)) {
            delimiter = '\n';
        }
        JdbcTestUtils.splitSqlScript(script, delimiter, statements);
        for (String statement : statements) {
            try {
                int rowsAffected = simpleJdbcTemplate.update(statement);
                if (logger.isDebugEnabled()) {
                    logger.debug(rowsAffected + " rows affected by SQL: " + statement);
                }
            } catch (DataAccessException ex) {
                if (continueOnError) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("SQL: " + statement + " failed", ex);
                    }
                } else {
                    throw ex;
                }
            }
        }
        long elapsedTime = System.currentTimeMillis() - startTime;
        if (logger.isInfoEnabled()) {
            logger.info("Done executing SQL scriptBuilder from " + resource + " in " + elapsedTime + " ms.");
        }
    } catch (IOException ex) {
        throw new DataAccessResourceFailureException("Failed to open SQL script from " + resource, ex);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException ex) {
            // ignore
        }

    }
}

From source file:org.springmodules.workflow.jbpm30.JbpmSessionFactoryUtils.java

/**
 * Returns a jBPM session. It is aware of and will return the thread-bound session if one is found.
 * //from  w ww  . j a  va  2 s .c o m
 * @param sessionFactory
 * @return
 */
public static JbpmSession getSession(JbpmSessionFactory sessionFactory) {
    try {
        return doGetSession(sessionFactory, true);
    } catch (RuntimeException e) {
        throw new DataAccessResourceFailureException("Could not open jBPM Session", e);
    }
}