Example usage for org.springframework.dao DataIntegrityViolationException DataIntegrityViolationException

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

Introduction

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

Prototype

public DataIntegrityViolationException(String msg, Throwable cause) 

Source Link

Document

Constructor for DataIntegrityViolationException.

Usage

From source file:com.couchbase.spring.core.CouchbaseExceptionTranslator.java

/**
 * Translate Couchbase specific exceptions to spring exceptions if possible.
 *
 * @param ex the exception to translate.
 * @return the translated exception or null.
 *//*from   ww w.j a v a2s.c o m*/
@Override
public final DataAccessException translateExceptionIfPossible(RuntimeException ex) {
    if (ex instanceof ConnectionException) {
        return new DataAccessResourceFailureException(ex.getMessage(), ex);
    }

    if (ex instanceof ObservedException || ex instanceof ObservedTimeoutException
            || ex instanceof ObservedModifiedException) {
        return new DataIntegrityViolationException(ex.getMessage(), ex);
    }

    return null;
}

From source file:com._4dconcept.springframework.data.marklogic.core.MarklogicExceptionTranslator.java

@Override
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {

    // Check for well-known MarklogicException subclasses.

    String exception = ClassUtils.getShortName(ClassUtils.getUserClass(ex.getClass()));

    if (RESOURCE_FAILURE_EXCEPTIONS.contains(exception)) {
        return new DataAccessResourceFailureException(ex.getMessage(), ex);
    }/*  w  w w  .  jav  a 2 s.co  m*/

    if (RESOURCE_USAGE_EXCEPTIONS.contains(exception)) {
        return new InvalidDataAccessResourceUsageException(ex.getMessage(), ex);
    }

    if (DATA_INTEGRETY_EXCEPTIONS.contains(exception)) {
        return new DataIntegrityViolationException(ex.getMessage(), ex);
    }

    return null;
}

From source file:org.jasig.portlet.weather.service.AbstractWeatherService.java

public void saveLocations(List<SavedLocation> savedLocations, PortletPreferences prefs) {
    final List<String> locationCodes = new ArrayList<String>(savedLocations.size());
    final List<String> locations = new ArrayList<String>(savedLocations.size());
    final List<String> metrics = new ArrayList<String>(savedLocations.size());

    for (final SavedLocation savedLocation : savedLocations) {
        locationCodes.add(savedLocation.code);
        locations.add(savedLocation.name);
        metrics.add(savedLocation.temperatureUnit.toString());
    }/* w  w  w .  j  a  v a 2  s.  c o m*/

    try {
        prefs.setValues(LOCATION_CODES, locationCodes.toArray(new String[locationCodes.size()]));
        prefs.setValues(LOCATIONS, locations.toArray(new String[locations.size()]));
        prefs.setValues(UNITS, metrics.toArray(new String[metrics.size()]));
        prefs.reset(METRICS); //Clear value, handling legacy preferences structure
        prefs.store();
    } catch (ReadOnlyException roe) {
        throw new PermissionDeniedDataAccessException(
                "Failed to save preferences due to one being marked read-only. The portlet preferences locationCode, locations, and metrics must not be read only.",
                roe);
    } catch (ValidatorException ve) {
        throw new DataIntegrityViolationException("Validation of saved locations preferences failed", ve);
    } catch (IOException ioe) {
        throw new RuntimeException("Failed to store saved locations preferences due to IO error", ioe);
    }
}

From source file:com.autentia.tnt.manager.security.AuthenticationManager.java

/**
 * Load a User for ACEGI given its user name
 * //w ww .  j a v  a 2  s. co  m
 * @param username
 *            user name
 * @throws org.acegisecurity.userdetails.UsernameNotFoundException
 * @throws org.springframework.dao.DataAccessException
 * @return the user object description as specified by ACEGI
 */
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
    try {
        Version db = Version.getDatabaseVersion();
        Version code = Version.getApplicationVersion();

        if (db.compareTo(code, Version.MINOR) == 0) {
            log.info("loadUserByUsername - getting user " + username + " using Hibernate");
            User user = userDAO.searchByLogin(username);

            GrantedAuthority[] auths = userRolesService.getAuthorities(user);

            if (log.isDebugEnabled()) {
                StringBuilder sb = new StringBuilder();
                for (GrantedAuthority auth : auths) {
                    sb.append(auth);
                    sb.append(" ");
                }
                log.debug("loadUserByUsername - user roles: " + sb);
            }

            final Principal principal = new Principal(user, auths);

            //setting user preferred Locale
            final SettingSearch s = new SettingSearch();
            s.setName(SettingPath.GENERAL_PREFERRED_LOCALE);
            s.setOwnerId(user.getId());
            final List<Setting> vals = settings.search(s, null);

            final Setting val = (vals != null && vals.size() > 0) ? vals.get(0) : null;

            if (val != null) {
                final Locale local = new Locale(val.getValue());
                principal.setLocale(local);
            }

            return principal;
        } else {
            log.info("loadUserByUsername - getting user " + username + " using JDBC");
            return jdbcSearchByLogin(username);
        }
    } catch (SecException e) {
        log.warn("loadUserByUsername - exception", e);
        throw new DataRetrievalFailureException("Error getting roles for user: " + username, e);
    } catch (DataIntegrityException e) {
        log.warn("loadUserByUsername - exception", e);
        throw new DataIntegrityViolationException("Inconsistent user name: " + username, e);
    } catch (DataNotFoundException e) {
        log.warn("loadUserByUsername - exception", e);
        throw new UsernameNotFoundException("User not found: " + username, e);
    } catch (DataAccException e) {
        log.warn("loadUserByUsername - exception", e);
        throw new DataRetrievalFailureException("Error getting user: " + username, e);
    } catch (SQLException e) {
        log.warn("loadUserByUsername - exception", e);
        throw new DataRetrievalFailureException("Error getting user: " + username, e);
    }
}

From source file:github.priyatam.springrest.resource.PolicyResource.java

@RequestMapping(method = RequestMethod.GET, value = "/policy/future/{futureKey}")
@ResponseBody/*from  w w w  .  ja va  2  s.  c o  m*/
public ResponseEntity<Policy> poll(@PathVariable String futureKey) {
    logger.debug("Polling policy with future:" + futureKey);

    String location = resourceHelper.getPermLocation(futureKey);
    if (Strings.isNullOrEmpty(location)) {
        logger.warn("No Policy found for future. Is future expired?");
        return new ResponseEntity<Policy>(null, new HttpHeaders(), HttpStatus.NOT_FOUND);
    }
    if (ResourceHelper.ProcessingStatus.PROCESSING.toString().equals(location)) {
        logger.debug("Policy is still processing.");
        return new ResponseEntity<Policy>(null, new HttpHeaders(), HttpStatus.ACCEPTED);
    }
    if (ResourceHelper.ProcessingStatus.ERROR.toString().equals(location)) {
        logger.debug("Policy was not created but resulted in an error.");
        throw new DataIntegrityViolationException("Unable to save Policy",
                new RuntimeException(resourceHelper.getError(futureKey)));
    }

    logger.debug("Received notification that policy creation is completed");
    String policyNum = resourceHelper.parseKey(resourceHelper.getPermLocation(futureKey));

    // Lookup
    Policy policy = persistenceHelper.loadPolicy(policyNum);
    if (policy == null) {
        logger.error("Can't read policy with key: " + policyNum);
        return new ResponseEntity<Policy>(null, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    // Convert to Restful Resource with sparse objects
    responseBuilder.toPolicy(policy);

    return new ResponseEntity<Policy>(policy, HttpStatus.CREATED);
}

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  a v  a 2s . c  om*/
    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 = "";
    }//  ww w  .ja v  a2  s.c om
    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.jdbc.support.SQLStateSQLExceptionTranslator.java

public DataAccessException translate(String task, String sql, SQLException sqlEx) {
    if (task == null) {
        task = "";
    }/*w w w.  j  av a  2s.  com*/
    if (sql == null) {
        sql = "";
    }

    String sqlState = sqlEx.getSQLState();
    // Some JDBC drivers nest the actual exception from a batched update: need to get the nested one.
    if (sqlState == null) {
        SQLException nestedEx = sqlEx.getNextException();
        if (nestedEx != null) {
            sqlState = nestedEx.getSQLState();
        }
    }
    if (sqlState != null && sqlState.length() >= 2) {
        String classCode = sqlState.substring(0, 2);
        if (BAD_SQL_CODES.contains(classCode)) {
            return new BadSqlGrammarException(task, sql, sqlEx);
        } else if (INTEGRITY_VIOLATION_CODES.contains(classCode)) {
            return new DataIntegrityViolationException(buildMessage(task, sql, sqlEx), sqlEx);
        }
    }

    // We couldn't identify it more precisely.
    return new UncategorizedSQLException(task, sql, sqlEx);
}

From source file:org.springframework.orm.hibernate3.SessionFactoryUtils.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
 * @see HibernateAccessor#convertHibernateAccessException
 * @see HibernateTransactionManager#convertHibernateAccessException
 *///from www.  j av a 2 s.c  om
public static 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);
    }
    if (ex instanceof JDBCException) {
        return new HibernateJdbcException((JDBCException) ex);
    }
    // end of JDBCException (subclass) handling

    if (ex instanceof QueryException) {
        return new HibernateQueryException((QueryException) 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) {
        return new HibernateObjectRetrievalFailureException((UnresolvableObjectException) ex);
    }
    if (ex instanceof WrongClassException) {
        return new HibernateObjectRetrievalFailureException((WrongClassException) ex);
    }
    if (ex instanceof StaleObjectStateException) {
        return new HibernateOptimisticLockingFailureException((StaleObjectStateException) ex);
    }
    if (ex instanceof StaleStateException) {
        return new HibernateOptimisticLockingFailureException((StaleStateException) ex);
    }
    if (ex instanceof OptimisticLockException) {
        return new HibernateOptimisticLockingFailureException((OptimisticLockException) ex);
    }

    // fallback
    return new HibernateSystemException(ex);
}

From source file:org.springframework.orm.hibernate4.fix.SessionFactoryUtils.java

/**
 * Convert the given HibernateException to an appropriate exception
 * from the {@code org.springframework.dao} hierarchy.
 * @param ex HibernateException that occured
 * @return the corresponding DataAccessException instance
 * @see HibernateExceptionTranslator#convertHibernateAccessException
 * @see HibernateTransactionManager#convertHibernateAccessException
 *//*from   w  ww .  j  a  va2 s .  c o  m*/
public static 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 LockAcquisitionException) {
        LockAcquisitionException jdbcEx = (LockAcquisitionException) ex;
        return new CannotAcquireLockException(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);
    }
    if (ex instanceof JDBCException) {
        return new HibernateJdbcException((JDBCException) ex);
    }
    // end of JDBCException (subclass) handling

    if (ex instanceof QueryException) {
        return new HibernateQueryException((QueryException) 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) {
        return new HibernateObjectRetrievalFailureException((UnresolvableObjectException) ex);
    }
    if (ex instanceof WrongClassException) {
        return new HibernateObjectRetrievalFailureException((WrongClassException) ex);
    }
    if (ex instanceof StaleObjectStateException) {
        return new HibernateOptimisticLockingFailureException((StaleObjectStateException) ex);
    }
    if (ex instanceof StaleStateException) {
        return new HibernateOptimisticLockingFailureException((StaleStateException) ex);
    }

    // fallback
    return new HibernateSystemException(ex);
}