Search in sources :

Example 1 with DataIntegrityViolationException

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

the class AttributesManagerImpl method createAttributeExistsForInitialize.

public void createAttributeExistsForInitialize(AttributeDefinition attribute) throws InternalErrorException {
    try {
        int attributeId = Utils.getNewId(jdbc, "attr_names_id_seq");
        jdbc.update("insert into attr_names (id, attr_name, type, dsc, namespace, friendly_name, display_name, default_attr_id) values (?,?,?,?,?,?,?,NULL)", attributeId, attribute.getName(), attribute.getType(), attribute.getDescription(), attribute.getNamespace(), attribute.getFriendlyName(), attribute.getDisplayName());
        log.info("Attribute created during initialization of attributesManager: {}", attribute);
    } catch (DataIntegrityViolationException e) {
        throw new ConsistencyErrorException("Attribute already exists: " + attribute, e);
    } catch (RuntimeException e) {
        throw new InternalErrorException(e);
    }
}
Also used : ConsistencyErrorException(cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException) ConsistencyErrorRuntimeException(cz.metacentrum.perun.core.api.exceptions.rt.ConsistencyErrorRuntimeException) InternalErrorRuntimeException(cz.metacentrum.perun.core.api.exceptions.rt.InternalErrorRuntimeException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException)

Example 2 with DataIntegrityViolationException

use of org.springframework.dao.DataIntegrityViolationException 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 3 with DataIntegrityViolationException

use of org.springframework.dao.DataIntegrityViolationException in project camel by apache.

the class DefaultJdbcOptimisticLockingExceptionMapper method isOptimisticLocking.

@Override
public boolean isOptimisticLocking(Exception cause) {
    Iterator<Throwable> it = ObjectHelper.createExceptionIterator(cause);
    while (it.hasNext()) {
        Throwable throwable = it.next();
        // if its a SQL exception
        if (throwable instanceof SQLException) {
            SQLException se = (SQLException) throwable;
            if (isConstraintViolation(se)) {
                return true;
            }
        }
        if (throwable instanceof DataIntegrityViolationException) {
            return true;
        }
        // fallback to names
        String name = throwable.getClass().getName();
        if (name.contains("ConstraintViolation") || hasClassName(name)) {
            return true;
        }
    }
    return false;
}
Also used : SQLException(java.sql.SQLException) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException)

Example 4 with DataIntegrityViolationException

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

the class AlarmDaoIT method testWithoutDistPoller.

@Test
@Transactional
@Ignore
public void testWithoutDistPoller() {
    OnmsEvent event = new OnmsEvent();
    event.setEventLog("Y");
    event.setEventDisplay("Y");
    event.setEventCreateTime(new Date());
    event.setDistPoller(m_distPollerDao.whoami());
    event.setEventTime(new Date());
    event.setEventSeverity(OnmsSeverity.CRITICAL.getId());
    event.setEventUei("uei://org/opennms/test/EventDaoTest");
    event.setEventSource("test");
    m_eventDao.save(event);
    OnmsNode node = m_nodeDao.findAll().iterator().next();
    OnmsAlarm alarm = new OnmsAlarm();
    alarm.setNode(node);
    alarm.setUei(event.getEventUei());
    alarm.setSeverityId(event.getEventSeverity());
    alarm.setFirstEventTime(event.getEventTime());
    alarm.setLastEvent(event);
    alarm.setCounter(1);
    ThrowableAnticipator ta = new ThrowableAnticipator();
    ta.anticipate(new DataIntegrityViolationException("not-null property references a null or transient value: org.opennms.netmgt.model.OnmsAlarm.distPoller; nested exception is org.hibernate.PropertyValueException: not-null property references a null or transient value: org.opennms.netmgt.model.OnmsAlarm.distPoller"));
    try {
        m_alarmDao.save(alarm);
    } catch (Throwable t) {
        ta.throwableReceived(t);
    }
    ta.verifyAnticipated();
}
Also used : OnmsEvent(org.opennms.netmgt.model.OnmsEvent) OnmsNode(org.opennms.netmgt.model.OnmsNode) OnmsAlarm(org.opennms.netmgt.model.OnmsAlarm) Date(java.util.Date) ThrowableAnticipator(org.opennms.test.ThrowableAnticipator) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) Ignore(org.junit.Ignore) Test(org.junit.Test) Transactional(org.springframework.transaction.annotation.Transactional)

Example 5 with DataIntegrityViolationException

use of org.springframework.dao.DataIntegrityViolationException in project libresonic by Libresonic.

the class UserDaoTestCase method testUserSettings.

@Test
public void testUserSettings() {
    assertNull("Error in getUserSettings.", userDao.getUserSettings("sindre"));
    try {
        userDao.updateUserSettings(new UserSettings("sindre"));
        fail("Expected DataIntegrityViolationException.");
    } catch (DataIntegrityViolationException x) {
    }
    userDao.createUser(new User("sindre", "secret", null));
    assertNull("Error in getUserSettings.", userDao.getUserSettings("sindre"));
    userDao.updateUserSettings(new UserSettings("sindre"));
    UserSettings userSettings = userDao.getUserSettings("sindre");
    assertNotNull("Error in getUserSettings().", userSettings);
    assertNull("Error in getUserSettings().", userSettings.getLocale());
    assertNull("Error in getUserSettings().", userSettings.getThemeId());
    assertFalse("Error in getUserSettings().", userSettings.isFinalVersionNotificationEnabled());
    assertFalse("Error in getUserSettings().", userSettings.isBetaVersionNotificationEnabled());
    assertFalse("Error in getUserSettings().", userSettings.isSongNotificationEnabled());
    assertFalse("Error in getUserSettings().", userSettings.isShowSideBar());
    assertFalse("Error in getUserSettings().", userSettings.isLastFmEnabled());
    assertNull("Error in getUserSettings().", userSettings.getLastFmUsername());
    assertNull("Error in getUserSettings().", userSettings.getLastFmPassword());
    assertSame("Error in getUserSettings().", TranscodeScheme.OFF, userSettings.getTranscodeScheme());
    assertFalse("Error in getUserSettings().", userSettings.isShowNowPlayingEnabled());
    assertEquals("Error in getUserSettings().", -1, userSettings.getSelectedMusicFolderId());
    assertFalse("Error in getUserSettings().", userSettings.isPartyModeEnabled());
    assertFalse("Error in getUserSettings().", userSettings.isNowPlayingAllowed());
    assertSame("Error in getUserSettings().", AvatarScheme.NONE, userSettings.getAvatarScheme());
    assertNull("Error in getUserSettings().", userSettings.getSystemAvatarId());
    assertEquals("Error in getUserSettings().", 0, userSettings.getListReloadDelay());
    assertFalse("Error in getUserSettings().", userSettings.isKeyboardShortcutsEnabled());
    assertEquals("Error in getUserSettings().", 0, userSettings.getPaginationSize());
    UserSettings settings = new UserSettings("sindre");
    settings.setLocale(Locale.SIMPLIFIED_CHINESE);
    settings.setThemeId("midnight");
    settings.setBetaVersionNotificationEnabled(true);
    settings.setSongNotificationEnabled(false);
    settings.setShowSideBar(true);
    settings.getMainVisibility().setBitRateVisible(true);
    settings.getPlaylistVisibility().setYearVisible(true);
    settings.setLastFmEnabled(true);
    settings.setLastFmUsername("last_user");
    settings.setLastFmPassword("last_pass");
    settings.setTranscodeScheme(TranscodeScheme.MAX_192);
    settings.setShowNowPlayingEnabled(false);
    settings.setSelectedMusicFolderId(3);
    settings.setPartyModeEnabled(true);
    settings.setNowPlayingAllowed(true);
    settings.setAvatarScheme(AvatarScheme.SYSTEM);
    settings.setSystemAvatarId(1);
    settings.setChanged(new Date(9412L));
    settings.setListReloadDelay(60);
    settings.setKeyboardShortcutsEnabled(true);
    settings.setPaginationSize(120);
    userDao.updateUserSettings(settings);
    userSettings = userDao.getUserSettings("sindre");
    assertNotNull("Error in getUserSettings().", userSettings);
    assertEquals("Error in getUserSettings().", Locale.SIMPLIFIED_CHINESE, userSettings.getLocale());
    assertEquals("Error in getUserSettings().", false, userSettings.isFinalVersionNotificationEnabled());
    assertEquals("Error in getUserSettings().", true, userSettings.isBetaVersionNotificationEnabled());
    assertEquals("Error in getUserSettings().", false, userSettings.isSongNotificationEnabled());
    assertEquals("Error in getUserSettings().", true, userSettings.isShowSideBar());
    assertEquals("Error in getUserSettings().", "midnight", userSettings.getThemeId());
    assertEquals("Error in getUserSettings().", true, userSettings.getMainVisibility().isBitRateVisible());
    assertEquals("Error in getUserSettings().", true, userSettings.getPlaylistVisibility().isYearVisible());
    assertEquals("Error in getUserSettings().", true, userSettings.isLastFmEnabled());
    assertEquals("Error in getUserSettings().", "last_user", userSettings.getLastFmUsername());
    assertEquals("Error in getUserSettings().", "last_pass", userSettings.getLastFmPassword());
    assertSame("Error in getUserSettings().", TranscodeScheme.MAX_192, userSettings.getTranscodeScheme());
    assertFalse("Error in getUserSettings().", userSettings.isShowNowPlayingEnabled());
    assertEquals("Error in getUserSettings().", 3, userSettings.getSelectedMusicFolderId());
    assertTrue("Error in getUserSettings().", userSettings.isPartyModeEnabled());
    assertTrue("Error in getUserSettings().", userSettings.isNowPlayingAllowed());
    assertSame("Error in getUserSettings().", AvatarScheme.SYSTEM, userSettings.getAvatarScheme());
    assertEquals("Error in getUserSettings().", 1, userSettings.getSystemAvatarId().intValue());
    assertEquals("Error in getUserSettings().", new Date(9412L), userSettings.getChanged());
    assertEquals("Error in getUserSettings().", 60, userSettings.getListReloadDelay());
    assertTrue("Error in getUserSettings().", userSettings.isKeyboardShortcutsEnabled());
    assertEquals("Error in getUserSettings().", 120, userSettings.getPaginationSize());
    userDao.deleteUser("sindre");
    assertNull("Error in cascading delete.", userDao.getUserSettings("sindre"));
}
Also used : User(org.libresonic.player.domain.User) UserSettings(org.libresonic.player.domain.UserSettings) Date(java.util.Date) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) Test(org.junit.Test)

Aggregations

DataIntegrityViolationException (org.springframework.dao.DataIntegrityViolationException)108 Test (org.junit.Test)25 BadRequestException (com.sequenceiq.cloudbreak.controller.BadRequestException)11 Transactional (org.springframework.transaction.annotation.Transactional)11 HashMap (java.util.HashMap)10 Test (org.junit.jupiter.api.Test)10 Transactional (javax.transaction.Transactional)9 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)9 User (ca.corefacility.bioinformatics.irida.model.user.User)8 SQLException (java.sql.SQLException)8 ConstraintViolation (javax.validation.ConstraintViolation)8 HashSet (java.util.HashSet)7 ConstraintViolationException (javax.validation.ConstraintViolationException)6 List (java.util.List)5 Set (java.util.Set)5 EntityExistsException (ca.corefacility.bioinformatics.irida.exceptions.EntityExistsException)4 ConnectorException (com.netflix.metacat.common.server.connectors.exception.ConnectorException)4 InvalidMetaException (com.netflix.metacat.common.server.connectors.exception.InvalidMetaException)4 ResultSet (java.sql.ResultSet)4 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)4