List of usage examples for org.springframework.dao DataAccessResourceFailureException DataAccessResourceFailureException
public DataAccessResourceFailureException(String msg, @Nullable Throwable cause)
From source file:org.springframework.jdbc.support.lob.TemporaryLobCreator.java
@Override public void setBlobAsBinaryStream(PreparedStatement ps, int paramIndex, @Nullable InputStream binaryStream, int contentLength) throws SQLException { if (binaryStream != null) { Blob blob = ps.getConnection().createBlob(); try {/*from w ww . j av a2 s . co m*/ FileCopyUtils.copy(binaryStream, blob.setBinaryStream(1)); } catch (IOException ex) { throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex); } this.temporaryBlobs.add(blob); ps.setBlob(paramIndex, blob); } else { ps.setBlob(paramIndex, (Blob) null); } if (logger.isDebugEnabled()) { logger.debug( binaryStream != null ? "Copied binary stream into temporary BLOB with length " + contentLength : "Set BLOB to null"); } }
From source file:org.springframework.jdbc.support.lob.TemporaryLobCreator.java
@Override public void setClobAsAsciiStream(PreparedStatement ps, int paramIndex, @Nullable InputStream asciiStream, int contentLength) throws SQLException { if (asciiStream != null) { Clob clob = ps.getConnection().createClob(); try {/*from w w w . j a v a2 s . c o m*/ FileCopyUtils.copy(asciiStream, clob.setAsciiStream(1)); } catch (IOException ex) { throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex); } this.temporaryClobs.add(clob); ps.setClob(paramIndex, clob); } else { ps.setClob(paramIndex, (Clob) null); } if (logger.isDebugEnabled()) { logger.debug( asciiStream != null ? "Copied ASCII stream into temporary CLOB with length " + contentLength : "Set CLOB to null"); } }
From source file:org.springframework.jdbc.support.lob.TemporaryLobCreator.java
@Override public void setClobAsCharacterStream(PreparedStatement ps, int paramIndex, @Nullable Reader characterStream, int contentLength) throws SQLException { if (characterStream != null) { Clob clob = ps.getConnection().createClob(); try {//from www.j a va 2s .com FileCopyUtils.copy(characterStream, clob.setCharacterStream(1)); } catch (IOException ex) { throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex); } this.temporaryClobs.add(clob); ps.setClob(paramIndex, clob); } else { ps.setClob(paramIndex, (Clob) null); } if (logger.isDebugEnabled()) { logger.debug(characterStream != null ? "Copied character stream into temporary CLOB with length " + contentLength : "Set CLOB to null"); } }
From source file:org.springframework.jdbc.support.nativejdbc.WebSphereNativeJdbcExtractor.java
/** * Retrieve the Connection via WebSphere's <code>getNativeConnection</code> method. *///from w ww. j a v a 2 s .co m protected Connection doGetNativeConnection(Connection con) throws SQLException { // WebSphere 5 connection? if (this.webSphere5ConnectionClass != null && this.webSphere5ConnectionClass.isAssignableFrom(con.getClass())) { try { // WebSphere 5's WSJdbcUtil.getNativeConnection(wsJdbcConnection) return (Connection) this.webSphere5NativeConnectionMethod.invoke(null, new Object[] { con }); } catch (InvocationTargetException ex) { throw new DataAccessResourceFailureException("WebSphere5's getNativeConnection method failed", ex.getTargetException()); } catch (Exception ex) { throw new DataAccessResourceFailureException( "Could not access WebSphere5's getNativeConnection method", ex); } } // WebSphere 4 connection (or version 4 connection on WebSphere 5)? else if (this.webSphere4ConnectionClass != null && this.webSphere4ConnectionClass.isAssignableFrom(con.getClass())) { try { // WebSphere 4's connectionProxy.getPhysicalConnection() return (Connection) this.webSphere4PhysicalConnectionMethod.invoke(con, (Object[]) null); } catch (InvocationTargetException ex) { throw new DataAccessResourceFailureException("WebSphere4's getPhysicalConnection method failed", ex.getTargetException()); } catch (Exception ex) { throw new DataAccessResourceFailureException( "Could not access WebSphere4's getPhysicalConnection method", ex); } } // No known WebSphere connection -> return as-is. else { if (logger.isDebugEnabled()) { logger.debug("Connection [" + con + "] is not a WebSphere 5/4 connection, returning as-is"); } return con; } }
From source file:org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.java
public DataAccessException translate(String task, String sql, SQLException sqlEx) { if (task == null) { task = ""; }//from w w w. j av a 2s.co m if (sql == null) { sql = ""; } // First, try custom translation from overridden method. DataAccessException dex = customTranslate(task, sql, sqlEx); if (dex != null) { return dex; } // Check SQLErrorCodes with corresponding error code, if available. if (this.sqlErrorCodes != null) { String errorCode = null; if (this.sqlErrorCodes.isUseSqlStateForTranslation()) { errorCode = sqlEx.getSQLState(); } else { errorCode = Integer.toString(sqlEx.getErrorCode()); } if (errorCode != null) { // Look for defined custom translations first. CustomSQLErrorCodesTranslation[] customTranslations = this.sqlErrorCodes.getCustomTranslations(); if (customTranslations != null) { for (int i = 0; i < customTranslations.length; i++) { CustomSQLErrorCodesTranslation customTranslation = customTranslations[i]; if (Arrays.binarySearch(customTranslation.getErrorCodes(), errorCode) >= 0) { if (customTranslation.getExceptionClass() != null) { DataAccessException customException = createCustomException(task, sql, sqlEx, customTranslation.getExceptionClass()); if (customException != null) { logTranslation(task, sql, sqlEx, true); return customException; } } } } } // Next, look for grouped error codes. if (Arrays.binarySearch(this.sqlErrorCodes.getBadSqlGrammarCodes(), errorCode) >= 0) { logTranslation(task, sql, sqlEx, false); return new BadSqlGrammarException(task, sql, sqlEx); } else if (Arrays.binarySearch(this.sqlErrorCodes.getInvalidResultSetAccessCodes(), errorCode) >= 0) { logTranslation(task, sql, sqlEx, false); return new InvalidResultSetAccessException(task, sql, sqlEx); } else if (Arrays.binarySearch(this.sqlErrorCodes.getDataAccessResourceFailureCodes(), errorCode) >= 0) { logTranslation(task, sql, sqlEx, false); return new DataAccessResourceFailureException(buildMessage(task, sql, sqlEx), sqlEx); } else if (Arrays.binarySearch(this.sqlErrorCodes.getDataIntegrityViolationCodes(), errorCode) >= 0) { logTranslation(task, sql, sqlEx, false); return new DataIntegrityViolationException(buildMessage(task, sql, sqlEx), sqlEx); } else if (Arrays.binarySearch(this.sqlErrorCodes.getCannotAcquireLockCodes(), errorCode) >= 0) { logTranslation(task, sql, sqlEx, false); return new CannotAcquireLockException(buildMessage(task, sql, sqlEx), sqlEx); } else if (Arrays.binarySearch(this.sqlErrorCodes.getDeadlockLoserCodes(), errorCode) >= 0) { logTranslation(task, sql, sqlEx, false); return new DeadlockLoserDataAccessException(buildMessage(task, sql, sqlEx), sqlEx); } else if (Arrays.binarySearch(this.sqlErrorCodes.getCannotSerializeTransactionCodes(), errorCode) >= 0) { logTranslation(task, sql, sqlEx, false); return new CannotSerializeTransactionException(buildMessage(task, sql, sqlEx), sqlEx); } } } // We couldn't identify it more precisely - let's hand it over to the SQLState fallback translator. if (logger.isDebugEnabled()) { logger.debug("Unable to translate SQLException with errorCode '" + sqlEx.getErrorCode() + "', will now try the fallback translator"); } return this.fallbackTranslator.translate(task, sql, sqlEx); }
From source file:org.springframework.jdbc.support.SQLExceptionSubclassTranslator.java
public DataAccessException translate(String task, String sql, SQLException ex) { Assert.notNull(ex, "Cannot translate a null SQLException."); if (task == null) { task = ""; }//from ww w . j ava 2 s . c o m if (sql == null) { sql = ""; } if (ex instanceof SQLTransientException) { if (ex instanceof SQLTransactionRollbackException) { return new ConcurrencyFailureException(buildMessage(task, sql, ex), ex); } if (ex instanceof SQLTransientConnectionException) { return new TransientDataAccessResourceException(buildMessage(task, sql, ex), ex); } if (ex instanceof SQLTimeoutException) { return new TransientDataAccessResourceException(buildMessage(task, sql, ex), ex); } } else if (ex instanceof SQLNonTransientException) { if (ex instanceof SQLDataException) { return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex); } else if (ex instanceof SQLFeatureNotSupportedException) { return new BadSqlGrammarException(task, sql, ex); } else if (ex instanceof SQLIntegrityConstraintViolationException) { return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex); } else if (ex instanceof SQLInvalidAuthorizationSpecException) { return new PermissionDeniedDataAccessException(buildMessage(task, sql, ex), ex); } else if (ex instanceof SQLNonTransientConnectionException) { return new DataAccessResourceFailureException(buildMessage(task, sql, ex), ex); } else if (ex instanceof SQLSyntaxErrorException) { return new BadSqlGrammarException(task, sql, ex); } } else if (ex instanceof SQLRecoverableException) { return new RecoverableDataAccessException(buildMessage(task, sql, ex), ex); } // We couldn't identify it more precisely - let's allow other translation strategies to kick in. return null; }
From source file:org.springframework.ldap.pool.factory.PoolingContextSource.java
/** * Gets a DirContext of the specified type from the keyed object pool. * /*from w w w.ja v a 2 s . c o m*/ * @param dirContextType The type of context to return. * @return A wrapped DirContext of the specified type. * @throws DataAccessResourceFailureException If retrieving the object from * the pool throws an exception */ protected DirContext getContext(DirContextType dirContextType) { final DirContext dirContext; try { dirContext = (DirContext) this.keyedObjectPool.borrowObject(dirContextType); } catch (Exception e) { throw new DataAccessResourceFailureException("Failed to borrow DirContext from pool.", e); } if (dirContext instanceof LdapContext) { return new DelegatingLdapContext(this.keyedObjectPool, (LdapContext) dirContext, dirContextType); } return new DelegatingDirContext(this.keyedObjectPool, dirContext, dirContextType); }
From source file:org.springframework.orm.hibernate.SessionFactoryUtils.java
/** * Get a Hibernate Session for the given SessionFactory. Is aware of and will * return any existing corresponding Session bound to the current thread, for * example when using {@link HibernateTransactionManager}. Will create a new * Session otherwise, if "allowCreate" is <code>true</code>. * @param sessionFactory Hibernate SessionFactory to create the session with * @param entityInterceptor Hibernate entity interceptor, or <code>null</code> if none * @param jdbcExceptionTranslator SQLExceptionTranslator to use for flushing the * Session on transaction synchronization (may be <code>null</code>) * @param allowCreate whether a non-transactional Session should be created * when no transactional Session can be found for the current thread * @return the Hibernate Session//from w w w . j av a 2 s .c o m * @throws DataAccessResourceFailureException if the Session couldn't be created * @throws IllegalStateException if no thread-bound Session found and * "allowCreate" is <code>false</code> */ private static Session getSession(SessionFactory sessionFactory, Interceptor entityInterceptor, SQLExceptionTranslator jdbcExceptionTranslator, boolean allowCreate) throws DataAccessResourceFailureException, IllegalStateException { Assert.notNull(sessionFactory, "No SessionFactory specified"); SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); if (sessionHolder != null && !sessionHolder.isEmpty()) { // pre-bound Hibernate Session Session session = null; if (TransactionSynchronizationManager.isSynchronizationActive() && sessionHolder.doesNotHoldNonDefaultSession()) { // Spring transaction management is active -> // register pre-bound Session with it for transactional flushing. session = sessionHolder.getValidatedSession(); if (!sessionHolder.isSynchronizedWithTransaction()) { logger.debug("Registering Spring transaction synchronization for existing Hibernate Session"); TransactionSynchronizationManager.registerSynchronization(new SpringSessionSynchronization( sessionHolder, sessionFactory, jdbcExceptionTranslator, false)); sessionHolder.setSynchronizedWithTransaction(true); // Switch to FlushMode.AUTO if we're not within a read-only transaction. FlushMode flushMode = session.getFlushMode(); if (FlushMode.NEVER.equals(flushMode) && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { session.setFlushMode(FlushMode.AUTO); sessionHolder.setPreviousFlushMode(flushMode); } } } else { // No Spring transaction management active -> try JTA transaction synchronization. session = getJtaSynchronizedSession(sessionHolder, sessionFactory, jdbcExceptionTranslator); } if (session != null) { return session; } } try { logger.debug("Opening Hibernate Session"); Session session = (entityInterceptor != null ? sessionFactory.openSession(entityInterceptor) : sessionFactory.openSession()); // Set Session to FlushMode.NEVER if we're within a read-only transaction. // Use same Session for further Hibernate actions within the transaction. // Thread object will get removed by synchronization at transaction completion. if (TransactionSynchronizationManager.isSynchronizationActive()) { // We're within a Spring-managed transaction, possibly from JtaTransactionManager. logger.debug("Registering Spring transaction synchronization for new Hibernate Session"); SessionHolder holderToUse = sessionHolder; if (holderToUse == null) { holderToUse = new SessionHolder(session); } else { holderToUse.addSession(session); } if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { session.setFlushMode(FlushMode.NEVER); } TransactionSynchronizationManager.registerSynchronization(new SpringSessionSynchronization( holderToUse, sessionFactory, jdbcExceptionTranslator, true)); holderToUse.setSynchronizedWithTransaction(true); if (holderToUse != sessionHolder) { TransactionSynchronizationManager.bindResource(sessionFactory, holderToUse); } } else { // No Spring transaction management active -> try JTA transaction synchronization. registerJtaSynchronization(session, sessionFactory, jdbcExceptionTranslator, sessionHolder); } // Check whether we are allowed to return the Session. if (!allowCreate && !isSessionTransactional(session, sessionFactory)) { doClose(session); throw new IllegalStateException("No Hibernate Session bound to thread, " + "and configuration does not allow creation of non-transactional one here"); } return session; } catch (HibernateException ex) { throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex); } }
From source file:org.springframework.orm.hibernate.SessionFactoryUtils.java
/** * Retrieve a Session from the given SessionHolder, potentially from a * JTA transaction synchronization.// w w w. j a v a 2s .c o m * @param sessionHolder the SessionHolder to check * @param sessionFactory the SessionFactory to get the JTA TransactionManager from * @param jdbcExceptionTranslator SQLExceptionTranslator to use for flushing the * Session on transaction synchronization (may be <code>null</code>) * @return the associated Session, if any * @throws DataAccessResourceFailureException if the Session couldn't be created */ private static Session getJtaSynchronizedSession(SessionHolder sessionHolder, SessionFactory sessionFactory, SQLExceptionTranslator jdbcExceptionTranslator) throws DataAccessResourceFailureException { // JTA synchronization is only possible with a javax.transaction.TransactionManager. // We'll check the Hibernate SessionFactory: If a TransactionManagerLookup is specified // in Hibernate configuration, it will contain a TransactionManager reference. TransactionManager jtaTm = getJtaTransactionManager(sessionFactory, sessionHolder.getAnySession()); if (jtaTm != null) { // Check whether JTA transaction management is active -> // fetch pre-bound Session for the current JTA transaction, if any. // (just necessary for JTA transaction suspension, with an individual // Hibernate Session per currently active/suspended transaction) try { // Look for transaction-specific Session. Transaction jtaTx = jtaTm.getTransaction(); if (jtaTx != null) { int jtaStatus = jtaTx.getStatus(); if (jtaStatus == Status.STATUS_ACTIVE || jtaStatus == Status.STATUS_MARKED_ROLLBACK) { Session session = sessionHolder.getValidatedSession(jtaTx); if (session == null && !sessionHolder.isSynchronizedWithTransaction()) { // No transaction-specific Session found: If not already marked as // synchronized with transaction, register the default thread-bound // Session as JTA-transactional. If there is no default Session, // we're a new inner JTA transaction with an outer one being suspended: // In that case, we'll return null to trigger opening of a new Session. session = sessionHolder.getValidatedSession(); if (session != null) { logger.debug( "Registering JTA transaction synchronization for existing Hibernate Session"); sessionHolder.addSession(jtaTx, session); jtaTx.registerSynchronization(new JtaSessionSynchronization( new SpringSessionSynchronization(sessionHolder, sessionFactory, jdbcExceptionTranslator, false), jtaTm)); sessionHolder.setSynchronizedWithTransaction(true); // Switch to FlushMode.AUTO if we're not within a read-only transaction. FlushMode flushMode = session.getFlushMode(); if (FlushMode.NEVER.equals(flushMode)) { session.setFlushMode(FlushMode.AUTO); sessionHolder.setPreviousFlushMode(flushMode); } } } return session; } } // No transaction active -> simply return default thread-bound Session, if any // (possibly from OpenSessionInViewFilter/Interceptor). return sessionHolder.getValidatedSession(); } catch (Throwable ex) { throw new DataAccessResourceFailureException("Could not check JTA transaction", ex); } } else { // No JTA TransactionManager -> simply return default thread-bound Session, if any // (possibly from OpenSessionInViewFilter/Interceptor). return sessionHolder.getValidatedSession(); } }
From source file:org.springframework.orm.hibernate.SessionFactoryUtils.java
/** * Register a JTA synchronization for the given Session, if any. * @param sessionHolder the existing thread-bound SessionHolder, if any * @param session the Session to register * @param sessionFactory the SessionFactory that the Session was created with * @param jdbcExceptionTranslator SQLExcepionTranslator to use for flushing the * Session on transaction synchronization (may be <code>null</code>) */// w ww. j av a2s . co m private static void registerJtaSynchronization(Session session, SessionFactory sessionFactory, SQLExceptionTranslator jdbcExceptionTranslator, SessionHolder sessionHolder) { // JTA synchronization is only possible with a javax.transaction.TransactionManager. // We'll check the Hibernate SessionFactory: If a TransactionManagerLookup is specified // in Hibernate configuration, it will contain a TransactionManager reference. TransactionManager jtaTm = getJtaTransactionManager(sessionFactory, session); if (jtaTm != null) { try { Transaction jtaTx = jtaTm.getTransaction(); if (jtaTx != null) { int jtaStatus = jtaTx.getStatus(); if (jtaStatus == Status.STATUS_ACTIVE || jtaStatus == Status.STATUS_MARKED_ROLLBACK) { logger.debug("Registering JTA transaction synchronization for new Hibernate Session"); SessionHolder holderToUse = sessionHolder; // Register JTA Transaction with existing SessionHolder. // Create a new SessionHolder if none existed before. if (holderToUse == null) { holderToUse = new SessionHolder(jtaTx, session); } else { holderToUse.addSession(jtaTx, session); } jtaTx.registerSynchronization( new JtaSessionSynchronization(new SpringSessionSynchronization(holderToUse, sessionFactory, jdbcExceptionTranslator, true), jtaTm)); holderToUse.setSynchronizedWithTransaction(true); if (holderToUse != sessionHolder) { TransactionSynchronizationManager.bindResource(sessionFactory, holderToUse); } } } } catch (Throwable ex) { throw new DataAccessResourceFailureException( "Could not register synchronization with JTA TransactionManager", ex); } } }