Search in sources :

Example 1 with DataAccessException

use of org.springframework.dao.DataAccessException in project opennms by OpenNMS.

the class DefaultEventConfDao method loadConfig.

private synchronized void loadConfig() throws DataAccessException {
    try {
        Events events = JaxbUtils.unmarshal(Events.class, m_configResource);
        m_lastModifiedEventFiles = events.loadEventFiles(m_configResource);
        m_partition = new EnterpriseIdPartition();
        events.initialize(m_partition, new EventOrdering());
        m_events = events;
    } catch (Exception e) {
        throw new DataRetrievalFailureException("Unabled to load " + m_configResource, e);
    }
}
Also used : EventOrdering(org.opennms.netmgt.xml.eventconf.EventOrdering) Events(org.opennms.netmgt.xml.eventconf.Events) DataRetrievalFailureException(org.springframework.dao.DataRetrievalFailureException) DataAccessException(org.springframework.dao.DataAccessException) DataRetrievalFailureException(org.springframework.dao.DataRetrievalFailureException) IOException(java.io.IOException)

Example 2 with DataAccessException

use of org.springframework.dao.DataAccessException in project perun by CESNET.

the class AttributesManagerImpl method setAttributeInDB.

private boolean setAttributeInDB(final PerunSession sess, final Attribute attribute, final String tableName, final Map<String, Object> params) throws InternalErrorException {
    // get two sorted lists for parameter names and values
    List<String> columnNames = new ArrayList<>();
    List<Object> columnValues = new ArrayList<>();
    for (Entry entry : params.entrySet()) {
        columnNames.add((String) entry.getKey());
        columnValues.add(entry.getValue());
    }
    try {
        // deleting the attibute if the given attribute value is null
        if (attribute.getValue() == null) {
            int numAffected = jdbc.update("delete from " + tableName + " where " + buildParameters(columnNames, "=?", " and "), columnValues.toArray());
            if (numAffected > 1) {
                throw new ConsistencyErrorException(String.format("Too much rows to delete (" + numAffected + " rows). SQL: delete from " + tableName + " where " + buildParameters(columnNames, "=%s", " and "), columnValues.toArray()));
            }
            return numAffected == 1;
        }
        // set the column name according to the size of the attribute
        boolean largeAttribute = isLargeAttribute(sess, attribute);
        String valueColName = (largeAttribute ? "attr_value_text" : "attr_value");
        // if the DB value is the same as parameter, return
        if (!largeAttribute) {
            try {
                Object value = BeansUtils.stringToAttributeValue(jdbc.queryForObject("select attr_value from " + tableName + " where " + buildParameters(columnNames, "=?", " and "), String.class, columnValues.toArray()), attribute.getType());
                if (attribute.getValue().equals(value)) {
                    return false;
                }
            } catch (EmptyResultDataAccessException ex) {
            //This is ok. Attribute will be stored later.
            }
        }
        int repetatCounter = 0;
        while (true) {
            // number of values of this attribute value in db
            int numOfAttributesInDb = jdbc.queryForInt("select count(attr_id) from " + tableName + " where " + buildParameters(columnNames, "=?", " and "), columnValues.toArray());
            switch(numOfAttributesInDb) {
                case 0:
                    {
                        // value doesn't exist -> insert
                        try {
                            return self.insertAttribute(sess, valueColName, attribute, tableName, columnNames, columnValues);
                        } catch (DataAccessException ex) {
                            // unsuccessful insert, do it again in while loop
                            if (++repetatCounter > MERGE_TRY_CNT) {
                                throw new InternalErrorException("SQL merger (or other UPSERT command) failed more than " + MERGE_TRY_CNT + " times.");
                            }
                            try {
                                //randomized sleep
                                Thread.sleep(Math.round(MERGE_RAND_SLEEP_MAX * Math.random()));
                            } catch (InterruptedException IGNORE) {
                            }
                        }
                        break;
                    }
                case 1:
                    {
                        // value exists -> update
                        try {
                            return self.updateAttribute(sess, valueColName, attribute, tableName, columnNames, columnValues);
                        } catch (DataAccessException ex) {
                            // unsuccessful insert, do it again in while loop
                            if (++repetatCounter > MERGE_TRY_CNT) {
                                throw new InternalErrorException("SQL merger (or other UPSERT command) failed more than " + MERGE_TRY_CNT + " times.");
                            }
                            try {
                                //randomized sleep
                                Thread.sleep(Math.round(MERGE_RAND_SLEEP_MAX * Math.random()));
                            } catch (InterruptedException IGNORE) {
                            }
                        }
                        break;
                    }
                default:
                    throw new ConsistencyErrorException(String.format("Attribute id " + attribute.getId() + " for " + tableName + " with parameters: " + buildParameters(columnNames, "=%s", " and ") + " is more than once in DB.", columnValues.toArray()));
            }
        }
    } catch (RuntimeException e) {
        throw new InternalErrorException(e);
    }
}
Also used : ConsistencyErrorException(cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) Entry(java.util.Map.Entry) ConsistencyErrorRuntimeException(cz.metacentrum.perun.core.api.exceptions.rt.ConsistencyErrorRuntimeException) InternalErrorRuntimeException(cz.metacentrum.perun.core.api.exceptions.rt.InternalErrorRuntimeException) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) DataAccessException(org.springframework.dao.DataAccessException)

Example 3 with DataAccessException

use of org.springframework.dao.DataAccessException in project opennms by OpenNMS.

the class TemporaryDatabasePostgreSQL method setupDatabase.

public void setupDatabase() throws TemporaryDatabaseException {
    try {
        setDataSource(new SimpleDataSource(m_driver, m_url + getTestDatabase(), m_adminUser, m_adminPassword));
        setAdminDataSource(new SimpleDataSource(m_driver, m_url + "template1", m_adminUser, m_adminPassword));
        m_xaDataSource = new PGXADataSource();
        m_xaDataSource.setServerName("localhost");
        m_xaDataSource.setDatabaseName(getTestDatabase());
        m_xaDataSource.setUser(m_adminUser);
        m_xaDataSource.setPassword(m_adminPassword);
        m_adminXaDataSource = new PGXADataSource();
        m_adminXaDataSource.setServerName("localhost");
        m_adminXaDataSource.setDatabaseName("template1");
        m_adminXaDataSource.setUser(m_adminUser);
        m_adminXaDataSource.setPassword(m_adminPassword);
    } catch (final ClassNotFoundException e) {
        throw new TemporaryDatabaseException("Failed to initialize driver " + m_driver, e);
    }
    if (!m_useExisting) {
        // to the template1 database
        synchronized (TEMPLATE1_MUTEX) {
            createTestDatabase();
        }
    }
    setJdbcTemplate(new JdbcTemplate(this));
    // Test connecting to test database and ensuring we can do a basic query
    try {
        getJdbcTemplate().queryForObject("SELECT now()", Date.class);
    } catch (DataAccessException e) {
        throw new TemporaryDatabaseException("Error occurred while testing database is connectable: " + e.getMessage(), e);
    }
    if (!m_useExisting) {
        setupBlame(getJdbcTemplate(), getBlame());
    }
}
Also used : SimpleDataSource(org.opennms.core.db.install.SimpleDataSource) PGXADataSource(org.postgresql.xa.PGXADataSource) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) DataAccessException(org.springframework.dao.DataAccessException)

Example 4 with DataAccessException

use of org.springframework.dao.DataAccessException in project spring-framework by spring-projects.

the class SQLErrorCodeSQLExceptionTranslator method doTranslate.

@Override
protected DataAccessException doTranslate(String task, String sql, SQLException ex) {
    SQLException sqlEx = ex;
    if (sqlEx instanceof BatchUpdateException && sqlEx.getNextException() != null) {
        SQLException nestedSqlEx = sqlEx.getNextException();
        if (nestedSqlEx.getErrorCode() > 0 || nestedSqlEx.getSQLState() != null) {
            logger.debug("Using nested SQLException from the BatchUpdateException");
            sqlEx = nestedSqlEx;
        }
    }
    // First, try custom translation from overridden method.
    DataAccessException dex = customTranslate(task, sql, sqlEx);
    if (dex != null) {
        return dex;
    }
    // Next, try the custom SQLException translator, if available.
    if (this.sqlErrorCodes != null) {
        SQLExceptionTranslator customTranslator = this.sqlErrorCodes.getCustomSqlExceptionTranslator();
        if (customTranslator != null) {
            DataAccessException customDex = customTranslator.translate(task, sql, sqlEx);
            if (customDex != null) {
                return customDex;
            }
        }
    }
    // Check SQLErrorCodes with corresponding error code, if available.
    if (this.sqlErrorCodes != null) {
        String errorCode;
        if (this.sqlErrorCodes.isUseSqlStateForTranslation()) {
            errorCode = sqlEx.getSQLState();
        } else {
            // Try to find SQLException with actual error code, looping through the causes.
            // E.g. applicable to java.sql.DataTruncation as of JDK 1.6.
            SQLException current = sqlEx;
            while (current.getErrorCode() == 0 && current.getCause() instanceof SQLException) {
                current = (SQLException) current.getCause();
            }
            errorCode = Integer.toString(current.getErrorCode());
        }
        if (errorCode != null) {
            // Look for defined custom translations first.
            CustomSQLErrorCodesTranslation[] customTranslations = this.sqlErrorCodes.getCustomTranslations();
            if (customTranslations != null) {
                for (CustomSQLErrorCodesTranslation customTranslation : customTranslations) {
                    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.getDuplicateKeyCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new DuplicateKeyException(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.getPermissionDeniedCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new PermissionDeniedDataAccessException(buildMessage(task, sql, sqlEx), 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.getTransientDataAccessResourceCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new TransientDataAccessResourceException(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()) {
        String codes;
        if (this.sqlErrorCodes != null && this.sqlErrorCodes.isUseSqlStateForTranslation()) {
            codes = "SQL state '" + sqlEx.getSQLState() + "', error code '" + sqlEx.getErrorCode();
        } else {
            codes = "Error code '" + sqlEx.getErrorCode() + "'";
        }
        logger.debug("Unable to translate SQLException with " + codes + ", will now try the fallback translator");
    }
    return null;
}
Also used : BadSqlGrammarException(org.springframework.jdbc.BadSqlGrammarException) TransientDataAccessResourceException(org.springframework.dao.TransientDataAccessResourceException) CannotAcquireLockException(org.springframework.dao.CannotAcquireLockException) SQLException(java.sql.SQLException) DataAccessResourceFailureException(org.springframework.dao.DataAccessResourceFailureException) PermissionDeniedDataAccessException(org.springframework.dao.PermissionDeniedDataAccessException) InvalidResultSetAccessException(org.springframework.jdbc.InvalidResultSetAccessException) DuplicateKeyException(org.springframework.dao.DuplicateKeyException) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) CannotSerializeTransactionException(org.springframework.dao.CannotSerializeTransactionException) DeadlockLoserDataAccessException(org.springframework.dao.DeadlockLoserDataAccessException) DataAccessException(org.springframework.dao.DataAccessException) DeadlockLoserDataAccessException(org.springframework.dao.DeadlockLoserDataAccessException) PermissionDeniedDataAccessException(org.springframework.dao.PermissionDeniedDataAccessException) BatchUpdateException(java.sql.BatchUpdateException)

Example 5 with DataAccessException

use of org.springframework.dao.DataAccessException in project spring-framework by spring-projects.

the class JpaTransactionManager method doCommit.

@Override
protected void doCommit(DefaultTransactionStatus status) {
    JpaTransactionObject txObject = (JpaTransactionObject) status.getTransaction();
    if (status.isDebug()) {
        logger.debug("Committing JPA transaction on EntityManager [" + txObject.getEntityManagerHolder().getEntityManager() + "]");
    }
    try {
        EntityTransaction tx = txObject.getEntityManagerHolder().getEntityManager().getTransaction();
        tx.commit();
    } catch (RollbackException ex) {
        if (ex.getCause() instanceof RuntimeException) {
            DataAccessException dex = getJpaDialect().translateExceptionIfPossible((RuntimeException) ex.getCause());
            if (dex != null) {
                throw dex;
            }
        }
        throw new TransactionSystemException("Could not commit JPA transaction", ex);
    } catch (RuntimeException ex) {
        // Assumably failed to flush changes to database.
        throw DataAccessUtils.translateIfNecessary(ex, getJpaDialect());
    }
}
Also used : EntityTransaction(javax.persistence.EntityTransaction) TransactionSystemException(org.springframework.transaction.TransactionSystemException) RollbackException(javax.persistence.RollbackException) DataAccessException(org.springframework.dao.DataAccessException)

Aggregations

DataAccessException (org.springframework.dao.DataAccessException)147 SQLException (java.sql.SQLException)49 ResultSet (java.sql.ResultSet)20 Connection (java.sql.Connection)18 PreparedStatement (java.sql.PreparedStatement)17 Test (org.junit.Test)15 MongoException (com.mongodb.MongoException)13 IOException (java.io.IOException)13 Transactional (org.springframework.transaction.annotation.Transactional)12 Test (org.junit.jupiter.api.Test)10 JdbcTemplate (org.springframework.jdbc.core.JdbcTemplate)10 HashMap (java.util.HashMap)9 ArrayList (java.util.ArrayList)8 Map (java.util.Map)8 Document (org.bson.Document)8 RedisConnection (org.springframework.data.redis.connection.RedisConnection)7 RedisCallback (org.springframework.data.redis.core.RedisCallback)7 StringRedisSerializer (org.springframework.data.redis.serializer.StringRedisSerializer)7 List (java.util.List)6 Logger (org.slf4j.Logger)6