Search in sources :

Example 31 with ConstraintViolationException

use of org.hibernate.exception.ConstraintViolationException in project uPortal by Jasig.

the class JdbcAuthDao method createToken.

protected void createToken(final String serviceName) {
    try {
        this.jdbcOperations.execute(new ConnectionCallback<Object>() {

            @Override
            public Object doInConnection(Connection con) throws SQLException, DataAccessException {
                // This is horribly hacky but we can't rely on the main uPortal TM
                // directly or we get
                // into a circular dependency loop from JPA to Ehcache to jGroups and
                // back to JPA
                final DataSource ds = new SingleConnectionDataSource(con, true);
                final PlatformTransactionManager ptm = new DataSourceTransactionManager(ds);
                final TransactionOperations to = new TransactionTemplate(ptm);
                to.execute(new TransactionCallbackWithoutResult() {

                    @Override
                    protected void doInTransactionWithoutResult(TransactionStatus status) {
                        logger.info("Creating jGroups auth token");
                        final String authToken = RandomTokenGenerator.INSTANCE.generateRandomToken(authTokenLength);
                        final ImmutableMap<String, String> params = ImmutableMap.of(PRM_SERVICE_NAME, serviceName, PRM_RANDOM_TOKEN, authToken);
                        namedParameterJdbcOperations.update(INSERT_SQL, params);
                    }
                });
                return null;
            }
        });
    } catch (ConstraintViolationException e) {
    // Ignore, just means a concurrent token creation
    } catch (DataIntegrityViolationException e) {
    // Ignore, just means a concurrent token creation
    }
}
Also used : SingleConnectionDataSource(org.springframework.jdbc.datasource.SingleConnectionDataSource) TransactionOperations(org.springframework.transaction.support.TransactionOperations) SQLException(java.sql.SQLException) Connection(java.sql.Connection) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) TransactionStatus(org.springframework.transaction.TransactionStatus) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) SingleConnectionDataSource(org.springframework.jdbc.datasource.SingleConnectionDataSource) DataSource(javax.sql.DataSource) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) DataAccessException(org.springframework.dao.DataAccessException) DataSourceTransactionManager(org.springframework.jdbc.datasource.DataSourceTransactionManager) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult)

Example 32 with ConstraintViolationException

use of org.hibernate.exception.ConstraintViolationException in project jo-client-platform by jo-source.

the class HibernateExceptionDecoratorImpl method decorate.

private Throwable decorate(final Throwable exception, final Throwable rootException) {
    if (exception instanceof ConstraintViolationException) {
        final ConstraintViolationException constViolationException = (ConstraintViolationException) exception;
        final String message = constViolationException.getMessage();
        final String constraintName = constViolationException.getConstraintName();
        final String userBaseMessage = Messages.getString("HibernateExceptionDecoratorImpl.database_constraint_violated");
        final String userMessage;
        if (!EmptyCheck.isEmpty(constraintName)) {
            userMessage = userBaseMessage.replace("%1", "'" + constraintName + "'");
        } else {
            final SQLException sqlException = constViolationException.getSQLException();
            if (sqlException != null) {
                if (!EmptyCheck.isEmpty(sqlException.getLocalizedMessage())) {
                    userMessage = sqlException.getLocalizedMessage();
                } else if (!EmptyCheck.isEmpty(sqlException.getMessage())) {
                    userMessage = sqlException.getMessage();
                } else {
                    userMessage = userBaseMessage.replace("%1", "");
                }
            } else {
                userMessage = userBaseMessage.replace("%1", "");
            }
        }
        return new ExecutableCheckException(null, message, userMessage);
    } else if (exception instanceof OptimisticLockException && exception.getCause() instanceof StaleObjectStateException) {
        return getStaleBeanException((StaleObjectStateException) exception);
    } else if (exception instanceof UnresolvableObjectException) {
        return getDeletedBeanException((UnresolvableObjectException) exception);
    } else if (exception instanceof JDBCException && !excludeJDBCExceptionDecoration((JDBCException) exception)) {
        return decorateJDBCException((JDBCException) exception);
    } else if (exception instanceof InvocationTargetException && ((InvocationTargetException) exception).getTargetException() != null) {
        return decorate(((InvocationTargetException) exception).getTargetException(), rootException);
    } else if (exception.getCause() != null) {
        return decorate(exception.getCause(), rootException);
    }
    return rootException;
}
Also used : JDBCException(org.hibernate.JDBCException) SQLException(java.sql.SQLException) UnresolvableObjectException(org.hibernate.UnresolvableObjectException) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) OptimisticLockException(javax.persistence.OptimisticLockException) ExecutableCheckException(org.jowidgets.cap.common.api.exception.ExecutableCheckException) StaleObjectStateException(org.hibernate.StaleObjectStateException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 33 with ConstraintViolationException

use of org.hibernate.exception.ConstraintViolationException in project CzechIdMng by bcvsolutions.

the class ExceptionControllerAdvice method handle.

@ExceptionHandler(PersistenceException.class)
public ResponseEntity<ResultModels> handle(PersistenceException ex) {
    ErrorModel errorModel = null;
    // 
    if (ex.getCause() != null && ex.getCause() instanceof ConstraintViolationException) {
        ConstraintViolationException constraintEx = (ConstraintViolationException) ex.getCause();
        // TODO: registrable contstrain error codes
        if (constraintEx.getConstraintName().contains("name")) {
            errorModel = new DefaultErrorModel(CoreResultCode.NAME_CONFLICT, ImmutableMap.of("name", constraintEx.getConstraintName()));
        } else if (constraintEx.getConstraintName().contains("code")) {
            errorModel = new DefaultErrorModel(CoreResultCode.CODE_CONFLICT, ImmutableMap.of("name", constraintEx.getConstraintName()));
        } else {
            errorModel = new DefaultErrorModel(CoreResultCode.CONFLICT, ImmutableMap.of("name", constraintEx.getConstraintName()));
        }
    } else {
        errorModel = new DefaultErrorModel(CoreResultCode.CONFLICT, ex.getMessage());
    }
    LOG.error("[" + errorModel.getId() + "] ", ex);
    return new ResponseEntity<>(new ResultModels(errorModel), new HttpHeaders(), errorModel.getStatus());
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) DefaultErrorModel(eu.bcvsolutions.idm.core.api.exception.DefaultErrorModel) ErrorModel(eu.bcvsolutions.idm.core.api.exception.ErrorModel) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) DefaultErrorModel(eu.bcvsolutions.idm.core.api.exception.DefaultErrorModel) ResultModels(eu.bcvsolutions.idm.core.api.dto.ResultModels) ExceptionHandler(org.springframework.web.bind.annotation.ExceptionHandler)

Example 34 with ConstraintViolationException

use of org.hibernate.exception.ConstraintViolationException in project flytecnologia-api by jullierme.

the class FlyExceptionHandler method handleNotAuthenticated.

@ExceptionHandler(value = { ConstraintViolationException.class })
protected ResponseEntity<Object> handleNotAuthenticated(RuntimeException ex, WebRequest request) {
    String fieldError = ((ConstraintViolationException) ex.getCause()).getConstraintName();
    List<Error> errors = getListOfErros(fieldError, ex);
    return handleExceptionInternal(ex, errors, new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) FieldError(org.springframework.validation.FieldError) ExceptionHandler(org.springframework.web.bind.annotation.ExceptionHandler) ResponseEntityExceptionHandler(org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler)

Example 35 with ConstraintViolationException

use of org.hibernate.exception.ConstraintViolationException in project bw-calendar-engine by Bedework.

the class CalSvc method addUser.

/* Create the user. Get a new CalSvc object for that purpose.
   *
   */
BwPrincipal addUser(final String val) throws CalFacadeException {
    final Users users = (Users) getUsersHandler();
    /* Run this in a separate transaction to ensure we don't fail if the user
     * gets created by a concurrent process.
     */
    // if (creating) {
    // // Get a fake user
    // return users.initUserObject(val);
    // }
    // In case we need to replace the session
    getCal().flush();
    try {
        users.createUser(val);
    } catch (final CalFacadeException cfe) {
        if (cfe.getCause() instanceof ConstraintViolationException) {
            // We'll assume it was created by another process.
            warn("ConstraintViolationException trying to create " + val);
        // Does this session still work?
        } else {
            rollbackTransaction();
            if (debug) {
                cfe.printStackTrace();
            }
            throw cfe;
        }
    } catch (final Throwable t) {
        rollbackTransaction();
        if (debug) {
            t.printStackTrace();
        }
        throw new CalFacadeException(t);
    }
    final BwPrincipal principal = users.getUser(val);
    if (principal == null) {
        return null;
    }
    final String caladdr = getDirectories().userToCaladdr(principal.getPrincipalRef());
    if (caladdr != null) {
        final List<String> emails = Collections.singletonList(caladdr.substring("mailto:".length()));
        final Notifications notify = (Notifications) getNotificationsHandler();
        notify.subscribe(principal, emails);
    }
    return principal;
}
Also used : BwPrincipal(org.bedework.calfacade.BwPrincipal) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) BwString(org.bedework.calfacade.BwString) CalFacadeException(org.bedework.calfacade.exc.CalFacadeException)

Aggregations

ConstraintViolationException (org.hibernate.exception.ConstraintViolationException)38 Test (org.junit.Test)16 PersistenceException (javax.persistence.PersistenceException)12 Session (org.hibernate.Session)11 SQLException (java.sql.SQLException)7 RObject (com.evolveum.midpoint.repo.sql.data.common.RObject)4 ObjectAlreadyExistsException (com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException)4 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)4 DataIntegrityViolationException (org.springframework.dao.DataIntegrityViolationException)4 HttpHeaders (org.springframework.http.HttpHeaders)4 ExceptionHandler (org.springframework.web.bind.annotation.ExceptionHandler)4 User (ca.corefacility.bioinformatics.irida.model.user.User)3 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)3 Connection (java.sql.Connection)3 AbstractManyToManyAssociationClassTest (org.hibernate.test.manytomanyassociationclass.AbstractManyToManyAssociationClassTest)3 ResultModels (eu.bcvsolutions.idm.core.api.dto.ResultModels)2 DefaultErrorModel (eu.bcvsolutions.idm.core.api.exception.DefaultErrorModel)2 ErrorModel (eu.bcvsolutions.idm.core.api.exception.ErrorModel)2 ErrorData (io.crnk.core.engine.document.ErrorData)2 PreparedStatement (java.sql.PreparedStatement)2