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);
}
}
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);
}
}
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());
}
}
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;
}
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());
}
}
Aggregations