Example usage for org.hibernate.exception ConstraintViolationException ConstraintViolationException

List of usage examples for org.hibernate.exception ConstraintViolationException ConstraintViolationException

Introduction

In this page you can find the example usage for org.hibernate.exception ConstraintViolationException ConstraintViolationException.

Prototype

public ConstraintViolationException(String message, SQLException root, String constraintName) 

Source Link

Usage

From source file:org.finra.dm.service.helper.DmErrorInformationExceptionHandlerTest.java

License:Apache License

@Test
public void testConstraintViolationExceptionNoWrap() throws Exception {
    validateErrorInformation(exceptionHandler.handlePersistenceException(
            new ConstraintViolationException(MESSAGE, null, "testConstraint"), new MockHttpServletResponse()),
            HttpStatus.BAD_REQUEST, false);
}

From source file:org.finra.herd.service.helper.HerdErrorInformationExceptionHandlerTest.java

License:Apache License

@Test
public void testConstraintViolationException() throws Exception {
    validateErrorInformation(exceptionHandler.handlePersistenceException(
            getPersistenceException(new ConstraintViolationException(MESSAGE, null, "testConstraint")),
            new MockHttpServletResponse()), HttpStatus.BAD_REQUEST, false);

    validateErrorInformation(exceptionHandler.handlePersistenceException(
            getPersistenceException(new SQLException(MESSAGE,
                    HerdErrorInformationExceptionHandler.POSTGRES_SQL_STATE_CODE_FOREIGN_KEY_VIOLATION, 0)),
            new MockHttpServletResponse()), HttpStatus.BAD_REQUEST, false);
}

From source file:org.openeos.services.ui.internal.PostgreSQLDialectBatchUpdateResolver.java

License:Apache License

@Override
protected Throwable unencapsuleThrowable(Throwable t) {
    if (t instanceof ConstraintViolationException) {
        ConstraintViolationException constrainEx = (ConstraintViolationException) t;
        if (constrainEx.getConstraintName() == null) {
            SQLException sqlEx = constrainEx.getSQLException();
            if (sqlEx instanceof BatchUpdateException) {
                SQLException other = sqlEx.getNextException();
                if (other != null) {
                    String constraintName = conversionContext.getViolatedConstraintNameExtracter()
                            .extractConstraintName(other);
                    if (constraintName != null) {
                        return new ConstraintViolationException(t.getMessage(), sqlEx, constraintName);
                    }//w  w w.  j a  va2 s. c om
                }
            }
        }
    }
    return null;
}

From source file:org.openlmis.referencedata.errorhandling.RefDataErrorHandlingTest.java

License:Open Source License

@Test
public void shouldHandleDataIntegrityViolation() {
    // given/*from  w w w  .j  a v a 2 s.  c o  m*/
    String constraintName = "unq_program_code";
    ConstraintViolationException constraintViolation = new ConstraintViolationException(null, null,
            constraintName);
    DataIntegrityViolationException exp = new DataIntegrityViolationException(null, constraintViolation);

    // when
    mockMessage(ProgramMessageKeys.ERROR_CODE_DUPLICATED);
    LocalizedMessage message = errorHandler.handleDataIntegrityViolation(exp);

    // then
    assertMessage(message, ProgramMessageKeys.ERROR_CODE_DUPLICATED);
}

From source file:org.openlmis.referencedata.errorhandling.RefDataErrorHandlingTest.java

License:Open Source License

@Test
public void shouldHandleDataIntegrityViolationEvenIfMessageKeyNotExist() {
    // given//from ww w .j  a  v  a  2  s . co m
    String constraintName = "unq_program_code_abc_def";
    ConstraintViolationException constraintViolation = new ConstraintViolationException(null, null,
            constraintName);
    DataIntegrityViolationException exp = new DataIntegrityViolationException(null, constraintViolation);

    // when
    mockMessage(exp.getMessage());
    LocalizedMessage message = errorHandler.handleDataIntegrityViolation(exp);

    // then
    assertMessage(message, exp.getMessage());
}

From source file:org.openlmis.referencedata.web.FacilityTypeControllerIntegrationTest.java

License:Open Source License

@Test
public void shouldThrowExceptionIfCodeIsDuplicated() {
    mockUserHasRight(RightName.FACILITIES_MANAGE_RIGHT);

    doThrow(new DataIntegrityViolationException("",
            new ConstraintViolationException("", null, "unq_facility_type_code"))).when(facilityTypeRepository)
                    .save(any(FacilityType.class));

    String response = restAssured.given().header(HttpHeaders.AUTHORIZATION, getTokenHeader())
            .contentType(MediaType.APPLICATION_JSON_VALUE).body(facilityType).when().post(RESOURCE_URL).then()
            .statusCode(400).extract().path(MESSAGE_KEY);

    assertEquals(response, FacilityTypeMessageKeys.ERROR_CODE_DUPLICATED);
    assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations());
}

From source file:org.openmrs.api.impl.FormServiceImplTest.java

License:Mozilla Public License

@Test(expected = InvalidFileTypeException.class)
public void saveFormResource_shouldThrowAnInvalidFileTypeExceptionWhenUsedWithNonTextFiles() throws Exception {
    FormResource formResource = mock(FormResource.class);
    when(formResource.getName()).thenReturn("some resource");
    when(formResource.isDirty())//from  w w w.ja  v  a 2s  . c om
            .thenThrow(new ConstraintViolationException("some message", null, "for testing"));

    Context.getFormService().saveFormResource(formResource);
}

From source file:org.openmrs.web.controller.form.FormResourceControllerTest.java

License:Mozilla Public License

@Test
public void handleFormResource_shouldReturnViewURLOfCurrentPageWhenAnInvalidFileTypeExceptionIsThrown()
        throws Exception {

    final String EXPECTED_FORM_ID = "1";
    final String EXPECTED_DATATYPE_CLASS_NAME = (new LongFreeTextDatatype()).getClass().getName();
    final String EXPECTED_HANDLER_CLASS_NAME = (new LongFreeTextFileUploadHandler()).getClass().getName();
    final String EXPECTED_URL = "redirect:addFormResource.form?formId=" + EXPECTED_FORM_ID + "&datatype="
            + EXPECTED_DATATYPE_CLASS_NAME + "&handler=" + EXPECTED_HANDLER_CLASS_NAME;

    Errors errors = mock(Errors.class);
    when(errors.hasErrors()).thenReturn(false);

    Form form = mock(Form.class);
    when(form.getFormId()).thenReturn(1);
    when(form.getId()).thenReturn(1);//ww w.  ja va2 s. c  o m

    FormResource resource = mock(FormResource.class);
    when(resource.getForm()).thenReturn(form);
    when(resource.getDatatypeClassname()).thenReturn(EXPECTED_DATATYPE_CLASS_NAME);
    when(resource.getPreferredHandlerClassname()).thenReturn(EXPECTED_HANDLER_CLASS_NAME);
    when(resource.isDirty()).thenThrow(new ConstraintViolationException("for testing", null, "for testing"));

    MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();
    request.setMethod("POST");
    request.setParameter("formId", "1");
    request.setParameter("datatype", EXPECTED_DATATYPE_CLASS_NAME);
    request.setParameter("handler", EXPECTED_HANDLER_CLASS_NAME);

    FormResourceController controller = new FormResourceController();

    String actualUrl = controller.handleAddFormResource(resource, errors, request);

    assertEquals(EXPECTED_URL, actualUrl);
}

From source file:org.springframework.orm.hibernate3.HibernateInterceptorTests.java

License:Apache License

@Test
public void testInterceptorWithFlushFailure() throws Throwable {
    SQLException sqlEx = new SQLException("argh", "27");
    ConstraintViolationException jdbcEx = new ConstraintViolationException("", sqlEx, null);
    willThrow(jdbcEx).given(session).flush();

    HibernateInterceptor interceptor = new HibernateInterceptor();
    interceptor.setSessionFactory(sessionFactory);
    try {/*from  w w w  .  j  av  a2 s  . c  om*/
        interceptor.invoke(invocation);
        fail("Should have thrown DataIntegrityViolationException");
    } catch (DataIntegrityViolationException ex) {
        // expected
        assertEquals(jdbcEx, ex.getCause());
    }

    verify(session).close();
}

From source file:org.springframework.orm.hibernate3.HibernateTemplateTests.java

License:Apache License

@Test
public void testExceptions() throws HibernateException {
    SQLException sqlEx = new SQLException("argh", "27");

    final JDBCConnectionException jcex = new JDBCConnectionException("mymsg", sqlEx);
    try {/*from w ww  .j  a  v a  2s  . co  m*/
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw jcex;
            }
        });
        fail("Should have thrown DataAccessResourceFailureException");
    } catch (DataAccessResourceFailureException ex) {
        // expected
        assertEquals(jcex, ex.getCause());
        assertTrue(ex.getMessage().indexOf("mymsg") != -1);
    }

    final SQLGrammarException sgex = new SQLGrammarException("mymsg", sqlEx);
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw sgex;
            }
        });
        fail("Should have thrown InvalidDataAccessResourceUsageException");
    } catch (InvalidDataAccessResourceUsageException ex) {
        // expected
        assertEquals(sgex, ex.getCause());
        assertTrue(ex.getMessage().indexOf("mymsg") != -1);
    }

    final LockAcquisitionException laex = new LockAcquisitionException("mymsg", sqlEx);
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw laex;
            }
        });
        fail("Should have thrown CannotAcquireLockException");
    } catch (CannotAcquireLockException ex) {
        // expected
        assertEquals(laex, ex.getCause());
        assertTrue(ex.getMessage().indexOf("mymsg") != -1);
    }

    final ConstraintViolationException cvex = new ConstraintViolationException("mymsg", sqlEx, "myconstraint");
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw cvex;
            }
        });
        fail("Should have thrown DataIntegrityViolationException");
    } catch (DataIntegrityViolationException ex) {
        // expected
        assertEquals(cvex, ex.getCause());
        assertTrue(ex.getMessage().indexOf("mymsg") != -1);
    }

    final DataException dex = new DataException("mymsg", sqlEx);
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw dex;
            }
        });
        fail("Should have thrown DataIntegrityViolationException");
    } catch (DataIntegrityViolationException ex) {
        // expected
        assertEquals(dex, ex.getCause());
        assertTrue(ex.getMessage().indexOf("mymsg") != -1);
    }

    final JDBCException jdex = new JDBCException("mymsg", sqlEx);
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw jdex;
            }
        });
        fail("Should have thrown HibernateJdbcException");
    } catch (HibernateJdbcException ex) {
        // expected
        assertEquals(jdex, ex.getCause());
        assertTrue(ex.getMessage().indexOf("mymsg") != -1);
    }

    final PropertyValueException pvex = new PropertyValueException("mymsg", "myentity", "myproperty");
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw pvex;
            }
        });
        fail("Should have thrown DataIntegrityViolationException");
    } catch (DataIntegrityViolationException ex) {
        // expected
        assertEquals(pvex, ex.getCause());
        assertTrue(ex.getMessage().indexOf("mymsg") != -1);
    }

    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw new PersistentObjectException("");
            }
        });
        fail("Should have thrown InvalidDataAccessApiUsageException");
    } catch (InvalidDataAccessApiUsageException ex) {
        // expected
    }

    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw new TransientObjectException("");
            }
        });
        fail("Should have thrown InvalidDataAccessApiUsageException");
    } catch (InvalidDataAccessApiUsageException ex) {
        // expected
    }

    final ObjectDeletedException odex = new ObjectDeletedException("msg", "id", TestBean.class.getName());
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw odex;
            }
        });
        fail("Should have thrown InvalidDataAccessApiUsageException");
    } catch (InvalidDataAccessApiUsageException ex) {
        // expected
        assertEquals(odex, ex.getCause());
    }

    final QueryException qex = new QueryException("msg");
    qex.setQueryString("query");
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw qex;
            }
        });
        fail("Should have thrown InvalidDataAccessResourceUsageException");
    } catch (HibernateQueryException ex) {
        // expected
        assertEquals(qex, ex.getCause());
        assertEquals("query", ex.getQueryString());
    }

    final UnresolvableObjectException uoex = new UnresolvableObjectException("id", TestBean.class.getName());
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw uoex;
            }
        });
        fail("Should have thrown HibernateObjectRetrievalFailureException");
    } catch (HibernateObjectRetrievalFailureException ex) {
        // expected
        assertEquals(TestBean.class.getName(), ex.getPersistentClassName());
        assertEquals("id", ex.getIdentifier());
        assertEquals(uoex, ex.getCause());
    }

    final ObjectNotFoundException onfe = new ObjectNotFoundException("id", TestBean.class.getName());
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw onfe;
            }
        });
        fail("Should have thrown HibernateObjectRetrievalFailureException");
    } catch (HibernateObjectRetrievalFailureException ex) {
        // expected
        assertEquals(TestBean.class.getName(), ex.getPersistentClassName());
        assertEquals("id", ex.getIdentifier());
        assertEquals(onfe, ex.getCause());
    }

    final WrongClassException wcex = new WrongClassException("msg", "id", TestBean.class.getName());
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw wcex;
            }
        });
        fail("Should have thrown HibernateObjectRetrievalFailureException");
    } catch (HibernateObjectRetrievalFailureException ex) {
        // expected
        assertEquals(TestBean.class.getName(), ex.getPersistentClassName());
        assertEquals("id", ex.getIdentifier());
        assertEquals(wcex, ex.getCause());
    }

    final NonUniqueResultException nuex = new NonUniqueResultException(2);
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw nuex;
            }
        });
        fail("Should have thrown IncorrectResultSizeDataAccessException");
    } catch (IncorrectResultSizeDataAccessException ex) {
        // expected
        assertEquals(1, ex.getExpectedSize());
        assertEquals(-1, ex.getActualSize());
    }

    final StaleObjectStateException sosex = new StaleObjectStateException(TestBean.class.getName(), "id");
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw sosex;
            }
        });
        fail("Should have thrown HibernateOptimisticLockingFailureException");
    } catch (HibernateOptimisticLockingFailureException ex) {
        // expected
        assertEquals(TestBean.class.getName(), ex.getPersistentClassName());
        assertEquals("id", ex.getIdentifier());
        assertEquals(sosex, ex.getCause());
    }

    final StaleStateException ssex = new StaleStateException("msg");
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw ssex;
            }
        });
        fail("Should have thrown HibernateOptimisticLockingFailureException");
    } catch (HibernateOptimisticLockingFailureException ex) {
        // expected
        assertNull(ex.getPersistentClassName());
        assertNull(ex.getIdentifier());
        assertEquals(ssex, ex.getCause());
    }

    final HibernateException hex = new HibernateException("msg");
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw hex;
            }
        });
        fail("Should have thrown HibernateSystemException");
    } catch (HibernateSystemException ex) {
        // expected
        assertEquals(hex, ex.getCause());
    }
}