Search in sources :

Example 36 with ConstraintViolationException

use of org.hibernate.exception.ConstraintViolationException in project irida by phac-nml.

the class UserServiceImplTest method testCreateUserWithUnknownIntegrityConstraintViolationName.

@Test(expected = EntityExistsException.class)
public void testCreateUserWithUnknownIntegrityConstraintViolationName() {
    User u = new User();
    ConstraintViolationException constraintViolationException = new ConstraintViolationException("Duplicate", null, "Not a very nicely formatted constraint violation name.");
    DataIntegrityViolationException integrityViolationException = new DataIntegrityViolationException("Duplicate", constraintViolationException);
    when(userRepository.save(any(User.class))).thenThrow(integrityViolationException);
    when(validator.validateValue(eq(User.class), eq("password"), any(String.class))).thenReturn(new HashSet<ConstraintViolation<User>>());
    userService.create(u);
}
Also used : User(ca.corefacility.bioinformatics.irida.model.user.User) ConstraintViolation(javax.validation.ConstraintViolation) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) Test(org.junit.Test)

Example 37 with ConstraintViolationException

use of org.hibernate.exception.ConstraintViolationException in project midpoint by Evolveum.

the class ObjectUpdater method addObjectAttempt.

public <T extends ObjectType> String addObjectAttempt(PrismObject<T> object, RepoAddOptions options, OperationResult result) throws ObjectAlreadyExistsException, SchemaException {
    String classSimpleName = object.getCompileTimeClass() != null ? object.getCompileTimeClass().getSimpleName() : "(unknown class)";
    LOGGER_PERFORMANCE.debug("> add object {}, oid={}, overwrite={}", classSimpleName, object.getOid(), options.isOverwrite());
    String oid = null;
    Session session = null;
    OrgClosureManager.Context closureContext = null;
    // it is needed to keep the original oid for example for import options. if we do not keep it
    // and it was null it can bring some error because the oid is set when the object contains orgRef
    // or it is org. and by the import we do not know it so it will be trying to delete non-existing object
    String originalOid = object.getOid();
    try {
        LOGGER.trace("Object\n{}", object.debugDumpLazily());
        ObjectTypeUtil.normalizeAllRelations(object, relationRegistry);
        LOGGER.trace("Translating JAXB to data type.");
        PrismIdentifierGenerator.Operation operation = options.isOverwrite() ? PrismIdentifierGenerator.Operation.ADD_WITH_OVERWRITE : PrismIdentifierGenerator.Operation.ADD;
        PrismIdentifierGenerator idGenerator = new PrismIdentifierGenerator(operation);
        session = baseHelper.beginTransaction();
        RObject rObject = createDataObjectFromJAXB(object, idGenerator);
        // ignore options.isOverwrite() here, it's not used
        closureContext = closureManager.onBeginTransactionAdd(session, object, options.isOverwrite());
        if (options.isOverwrite()) {
            oid = overwriteAddObjectAttempt(object, rObject, originalOid, session, closureContext);
        } else {
            oid = nonOverwriteAddObjectAttempt(object, rObject, originalOid, session, closureContext);
        }
        session.getTransaction().commit();
        LOGGER.trace("Saved object '{}' with oid '{}'", classSimpleName, oid);
        object.setOid(oid);
    } catch (PersistenceException ex) {
        ConstraintViolationException constEx = ExceptionUtil.findCause(ex, ConstraintViolationException.class);
        if (constEx == null) {
            baseHelper.handleGeneralException(ex, session, result);
            throw new AssertionError("shouldn't be here");
        }
        // TODO use this throughout overwriteAddObjectAttempt to collect information about no-fetch insertion attempts
        AttemptContext attemptContext = new AttemptContext();
        handleConstraintViolationExceptionSpecialCases(constEx, session, attemptContext, result);
        baseHelper.rollbackTransaction(session, constEx, result, true);
        LOGGER.debug("Constraint violation occurred (will be rethrown as ObjectAlreadyExistsException).", constEx);
        // to the original oid and prevent of unexpected behaviour (e.g. by import with overwrite option)
        if (StringUtils.isEmpty(originalOid)) {
            object.setOid(null);
        }
        String constraintName = constEx.getConstraintName();
        // Breaker to avoid long unreadable messages
        if (constraintName != null && constraintName.length() > SqlRepositoryServiceImpl.MAX_CONSTRAINT_NAME_LENGTH) {
            constraintName = null;
        }
        throw new ObjectAlreadyExistsException("Conflicting object already exists" + (constraintName == null ? "" : " (violated constraint '" + constraintName + "')"), constEx);
    } catch (ObjectAlreadyExistsException | SchemaException ex) {
        baseHelper.rollbackTransaction(session, ex, result, true);
        throw ex;
    } catch (DtoTranslationException | RuntimeException ex) {
        baseHelper.handleGeneralException(ex, session, result);
    } finally {
        cleanupClosureAndSessionAndResult(closureContext, session, result);
    }
    return oid;
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) RObject(com.evolveum.midpoint.repo.sql.data.common.RObject) PersistenceException(javax.persistence.PersistenceException) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException) Session(org.hibernate.Session)

Example 38 with ConstraintViolationException

use of org.hibernate.exception.ConstraintViolationException in project midpoint by Evolveum.

the class ObjectUpdater method createDataObjectFromJAXB.

public <T extends ObjectType> RObject createDataObjectFromJAXB(PrismObject<T> prismObject, PrismIdentifierGenerator idGenerator) throws SchemaException {
    IdGeneratorResult generatorResult = idGenerator.generate(prismObject);
    T object = prismObject.asObjectable();
    RObject rObject;
    Class<? extends RObject> clazz = ClassMapper.getHQLTypeClass(object.getClass());
    try {
        rObject = clazz.getConstructor().newInstance();
        // Note that methods named "copyFromJAXB" that were _not_ called from this point were renamed e.g. to "fromJaxb",
        // in order to avoid confusion with dynamically called "copyFromJAXB" method.
        Method method = clazz.getMethod("copyFromJAXB", object.getClass(), clazz, RepositoryContext.class, IdGeneratorResult.class);
        method.invoke(clazz, object, rObject, new RepositoryContext(repositoryService, prismContext, relationRegistry, extItemDictionary, baseHelper.getConfiguration()), generatorResult);
    } catch (Exception ex) {
        SerializationRelatedException serializationException = ExceptionUtil.findCause(ex, SerializationRelatedException.class);
        if (serializationException != null) {
            throw serializationException;
        }
        ConstraintViolationException cve = ExceptionUtil.findCause(ex, ConstraintViolationException.class);
        if (cve != null && baseHelper.isSerializationRelatedConstraintViolationException(cve)) {
            throw cve;
        }
        String message = ex.getMessage();
        if (StringUtils.isEmpty(message) && ex.getCause() != null) {
            message = ex.getCause().getMessage();
        }
        throw new SchemaException(message, ex);
    }
    return rObject;
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) RepositoryContext(com.evolveum.midpoint.repo.sql.data.RepositoryContext) RObject(com.evolveum.midpoint.repo.sql.data.common.RObject) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) Method(java.lang.reflect.Method) SerializationRelatedException(com.evolveum.midpoint.repo.sql.SerializationRelatedException) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException) PersistenceException(javax.persistence.PersistenceException) SystemException(com.evolveum.midpoint.util.exception.SystemException) RestartOperationRequestedException(com.evolveum.midpoint.repo.sql.RestartOperationRequestedException) SerializationRelatedException(com.evolveum.midpoint.repo.sql.SerializationRelatedException)

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