Search in sources :

Example 26 with ConstraintViolationException

use of org.hibernate.exception.ConstraintViolationException in project hibernate-orm by hibernate.

the class BulkManipulationTest method testManyToManyBulkDelete.

@Test
@TestForIssue(jiraKey = "HHH-8476")
public void testManyToManyBulkDelete() {
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Farm farm1 = new Farm();
    farm1.setName("farm1");
    Crop crop = new Crop();
    crop.setName("crop1");
    farm1.setCrops(new ArrayList());
    farm1.getCrops().add(crop);
    s.save(farm1);
    Farm farm2 = new Farm();
    farm2.setName("farm2");
    farm2.setCrops(new ArrayList());
    farm2.getCrops().add(crop);
    s.save(farm2);
    s.flush();
    try {
        s.createQuery("delete from Farm f where f.name='farm1'").executeUpdate();
        assertEquals(s.createQuery("from Farm").list().size(), 1);
        s.createQuery("delete from Farm").executeUpdate();
        assertEquals(s.createQuery("from Farm").list().size(), 0);
    } catch (ConstraintViolationException cve) {
        fail("The join table was not cleared prior to the bulk delete.");
    } finally {
        t.rollback();
        s.close();
    }
}
Also used : Transaction(org.hibernate.Transaction) ArrayList(java.util.ArrayList) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) Session(org.hibernate.Session) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 27 with ConstraintViolationException

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

the class HibernateOracleExceptionDecoratorImpl method decorate.

@Override
public Throwable decorate(final Throwable original) {
    if (original instanceof PersistenceException) {
        final PersistenceException persistenceException = (PersistenceException) original;
        final Throwable cause = persistenceException.getCause();
        if (cause instanceof ConstraintViolationException) {
            final String constraintName = getConstraintName((ConstraintViolationException) cause);
            if (!EmptyCheck.isEmpty(constraintName)) {
                final ConstraintType constraintType = getConstraintType(constraintName);
                if (constraintType == ConstraintType.FK) {
                    return new ForeignKeyConstraintViolationException();
                } else if (constraintType != ConstraintType.UNSUPPORTED) {
                    final List<String> properties = getViolatedProperties(constraintName, constraintType);
                    if (!EmptyCheck.isEmpty(properties)) {
                        return new UniqueConstraintViolationException(properties);
                    }
                }
            }
        }
    }
    return original;
}
Also used : PersistenceException(javax.persistence.PersistenceException) UniqueConstraintViolationException(org.jowidgets.cap.common.api.exception.UniqueConstraintViolationException) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) ForeignKeyConstraintViolationException(org.jowidgets.cap.common.api.exception.ForeignKeyConstraintViolationException) List(java.util.List) LinkedList(java.util.LinkedList) ForeignKeyConstraintViolationException(org.jowidgets.cap.common.api.exception.ForeignKeyConstraintViolationException) UniqueConstraintViolationException(org.jowidgets.cap.common.api.exception.UniqueConstraintViolationException)

Example 28 with ConstraintViolationException

use of org.hibernate.exception.ConstraintViolationException in project crnk-framework by crnk-project.

the class JpaExceptionMapperTests method testConstraintException.

@Test
public void testConstraintException() {
    ConstraintViolationException exception = new ConstraintViolationException("message", null, "constraint");
    ExceptionMapperRegistry exceptionMapperRegistry = boot.getExceptionMapperRegistry();
    HibernateConstraintViolationExceptionMapper mapper = (HibernateConstraintViolationExceptionMapper) exceptionMapperRegistry.findMapperFor(ConstraintViolationException.class).get();
    ErrorResponse response = mapper.toErrorResponse(exception);
    ErrorData errorData = response.getErrors().iterator().next();
    Assert.assertEquals(Integer.toString(HttpStatus.UNPROCESSABLE_ENTITY_422), errorData.getStatus());
    Assert.assertEquals(exception.getConstraintName(), errorData.getCode());
    Assert.assertEquals(exception.getMessage(), errorData.getDetail());
    Assert.assertTrue(mapper.accepts(response));
    ConstraintViolationException deserializedException = mapper.fromErrorResponse(response);
    Assert.assertEquals(exception.getMessage(), deserializedException.getMessage());
    Assert.assertEquals(exception.getConstraintName(), deserializedException.getConstraintName());
}
Also used : HibernateConstraintViolationExceptionMapper(io.crnk.jpa.internal.HibernateConstraintViolationExceptionMapper) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) ExceptionMapperRegistry(io.crnk.core.engine.internal.exception.ExceptionMapperRegistry) ErrorData(io.crnk.core.engine.document.ErrorData) ErrorResponse(io.crnk.core.engine.error.ErrorResponse) Test(org.junit.Test)

Example 29 with ConstraintViolationException

use of org.hibernate.exception.ConstraintViolationException in project candlepin by candlepin.

the class OwnerResourceTest method testConflictOnDelete.

@Test(expected = ConflictException.class)
public void testConflictOnDelete() {
    Owner o = mock(Owner.class);
    OwnerCurator oc = mock(OwnerCurator.class);
    ProductCurator pc = mock(ProductCurator.class);
    OwnerManager ownerManager = mock(OwnerManager.class);
    EventFactory eventFactory = mock(EventFactory.class);
    OwnerResource or = new OwnerResource(oc, pc, null, null, i18n, null, eventFactory, null, null, null, poolManager, ownerManager, null, null, null, null, null, null, null, null, null, null, contentOverrideValidator, serviceLevelValidator, null, null, null, null, null, this.modelTranslator);
    when(oc.lookupByKey(eq("testOwner"))).thenReturn(o);
    ConstraintViolationException ce = new ConstraintViolationException(null, null, null);
    PersistenceException pe = new PersistenceException(ce);
    Mockito.doThrow(pe).when(ownerManager).cleanupAndDelete(eq(o), eq(true));
    or.deleteOwner("testOwner", true, true);
}
Also used : OwnerCurator(org.candlepin.model.OwnerCurator) Owner(org.candlepin.model.Owner) ProductCurator(org.candlepin.model.ProductCurator) PersistenceException(javax.persistence.PersistenceException) EventFactory(org.candlepin.audit.EventFactory) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) OwnerManager(org.candlepin.controller.OwnerManager) Test(org.junit.Test)

Example 30 with ConstraintViolationException

use of org.hibernate.exception.ConstraintViolationException in project candlepin by candlepin.

the class Importer method doExport.

private ImportRecord doExport(Owner owner, File exportDir, ConflictOverrides overrides, String uploadedFileName) throws ImporterException {
    Map<String, Object> result = new HashMap<>();
    try {
        File signature = new File(exportDir, "signature");
        if (signature.length() == 0) {
            throw new ImportExtractionException(i18n.tr("The archive does not contain the required signature file"));
        }
        boolean verifiedSignature = pki.verifySHA256WithRSAHashAgainstCACerts(new File(exportDir, "consumer_export.zip"), loadSignature(new File(exportDir, "signature")));
        if (!verifiedSignature) {
            log.warn("Archive signature check failed.");
            if (!overrides.isForced(Conflict.SIGNATURE_CONFLICT)) {
                /*
                     * Normally for import conflicts that can be overridden, we try to
                     * report them all the first time so if the user intends to override,
                     * they can do so with just one more request. However in the case of
                     * a bad signature, we're going to report immediately due to the nature
                     * of what this might mean.
                     */
                throw new ImportConflictException(i18n.tr("Archive failed signature check"), Conflict.SIGNATURE_CONFLICT);
            } else {
                log.warn("Ignoring signature check failure.");
            }
        }
        File consumerExport = new File(exportDir, "consumer_export.zip");
        File consumerExportDir = extractArchive(exportDir, consumerExport.getName(), new FileInputStream(consumerExport));
        Map<String, File> importFiles = new HashMap<>();
        File[] listFiles = consumerExportDir.listFiles();
        if (listFiles == null || listFiles.length == 0) {
            throw new ImportExtractionException(i18n.tr("The consumer_export archive has no contents"));
        }
        for (File file : listFiles) {
            importFiles.put(file.getName(), file);
        }
        // Need the rules file as well which is in a nested dir:
        File rulesFile = new File(consumerExportDir, ImportFile.RULES_FILE.fileName());
        importFiles.put(ImportFile.RULES_FILE.fileName(), rulesFile);
        List<Subscription> importSubs = importObjects(owner, importFiles, overrides);
        Meta m = mapper.readValue(importFiles.get(ImportFile.META.fileName()), Meta.class);
        result.put("subscriptions", importSubs);
        result.put("meta", m);
        sink.emitImportCreated(owner);
        return recordImportSuccess(owner, result, overrides, uploadedFileName);
    } catch (FileNotFoundException fnfe) {
        log.error("Archive file does not contain consumer_export.zip", fnfe);
        throw new ImportExtractionException(i18n.tr("The archive does not contain " + "the required consumer_export.zip file"));
    } catch (ConstraintViolationException cve) {
        log.error("Failed to import archive", cve);
        throw new ImporterException(i18n.tr("Failed to import archive"), cve, result);
    } catch (PersistenceException pe) {
        log.error("Failed to import archive", pe);
        throw new ImporterException(i18n.tr("Failed to import archive"), pe, result);
    } catch (IOException e) {
        log.error("Exception caught importing archive", e);
        throw new ImportExtractionException(i18n.tr("Unable to extract export archive"), e, result);
    } catch (CertificateException e) {
        log.error("Certificate exception checking archive signature", e);
        throw new ImportExtractionException(i18n.tr("Certificate exception checking archive signature"), e, result);
    } finally {
        if (exportDir != null) {
            try {
                FileUtils.deleteDirectory(exportDir);
            } catch (IOException e) {
                log.error("Failed to delete extracted export", e);
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) FileNotFoundException(java.io.FileNotFoundException) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) PersistenceException(javax.persistence.PersistenceException) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) Subscription(org.candlepin.model.dto.Subscription) ManifestFile(org.candlepin.sync.file.ManifestFile) File(java.io.File)

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