Java 类org.hibernate.exception.ConstraintViolationException 实例源码

项目:DocIT    文件:DepartmentBean.java   
public void save() {
    try {
        HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
        DAOFactory daoFactory = DAOFactory.instance(DAOFactory.HIBERNATE);
        department.setName(this.name);
        daoFactory.getDepartmentDAO().makePersistent(department);
        HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
    } catch (ConstraintViolationException e) {
        HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
        StringBuilder sb = new StringBuilder();
        sb.append("Error: There is already a department with the name ");
        sb.append(this.name);
        sb.append(". Enter a valid name, please.");
        FacesMessage facesMessage = new FacesMessage(sb.toString(), "name");
        FacesContext.getCurrentInstance().addMessage("name", facesMessage);
    }

}
项目:DocIT    文件:EmployeeBean.java   
public void save() {
    try {
        HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
        DAOFactory daoFactory = DAOFactory.instance(DAOFactory.HIBERNATE);
        employee.setName(this.name);
        employee.setAddress(this.address);
        employee.setSalary(this.salary);
        daoFactory.getEmployeeDAO().makePersistent(employee);
        HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
    } catch (ConstraintViolationException e) {
        HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
        StringBuilder sb = new StringBuilder();
        sb.append("Error: There is already an employee with the same name and address (name = ");
        sb.append(this.name);
        sb.append(", address = ");
        sb.append(this.address);
        sb.append("). Enter valid data, please.");
        FacesMessage facesMessage = new FacesMessage(sb.toString(), "name");
        FacesContext.getCurrentInstance().addMessage("name", facesMessage);
    }

}
项目:osc-core    文件:ServiceDispatcher.java   
private void handleException(Throwable e)
        throws VmidcDbConstraintViolationException, VmidcDbConcurrencyException, Exception {
    if (e instanceof SslCertificatesExtendedException) {
        throw (SslCertificatesExtendedException) e;
    } else if (e instanceof VmidcException) {
        log.warn("Service request failed (logically): " + e.getMessage());
    } else {
        log.error("Service request failed (unexpectedly): " + e.getMessage(), e);
    }

    if (e instanceof ConstraintViolationException) {
        log.error("Got database constraint violation exception", e);

        throw new VmidcDbConstraintViolationException("Database Constraint Violation Exception.");

    } else if (e instanceof StaleObjectStateException) {
        log.error("Got database concurrency exception", e);

        throw new VmidcDbConcurrencyException("Database Concurrency Exception.");
    } else if (e instanceof Exception) {
        throw (Exception) e;
    }


    throw new Exception("Exception or error executing service call: " + e.getMessage(), e);
}
项目:lams    文件:CacheSQLExceptionConversionDelegate.java   
/**
 * Convert the given SQLException into Hibernate's JDBCException hierarchy.
 *
 * @param sqlException The SQLException to be converted.
 * @param message     An optional error message.
 * @param sql         Optionally, the sql being performed when the exception occurred.
 * @return The resulting JDBCException; returns null if it could not be converted.
 */
@Override
public JDBCException convert(SQLException sqlException, String message, String sql) {
    String sqlStateClassCode = JdbcExceptionHelper.extractSqlStateClassCode( sqlException );
    if ( sqlStateClassCode != null ) {
        Integer errorCode = JdbcExceptionHelper.extractErrorCode( sqlException );
        if ( INTEGRITY_VIOLATION_CATEGORIES.contains( errorCode ) ) {
            String constraintName =
                    getConversionContext()
                            .getViolatedConstraintNameExtracter()
                            .extractConstraintName( sqlException );
            return new ConstraintViolationException( message, sqlException, sql, constraintName );
        }
        else if ( DATA_CATEGORIES.contains( sqlStateClassCode ) ) {
            return new DataException( message, sqlException, sql );
        }
    }
    return null; // allow other delegates the chance to look
}
项目:lams    文件:SybaseASE157Dialect.java   
@Override
public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() {
    return new SQLExceptionConversionDelegate() {
        @Override
        public JDBCException convert(SQLException sqlException, String message, String sql) {
            final String sqlState = JdbcExceptionHelper.extractSqlState( sqlException );
            final int errorCode = JdbcExceptionHelper.extractErrorCode( sqlException );
            if("JZ0TO".equals( sqlState ) || "JZ006".equals( sqlState )){
                throw new LockTimeoutException( message, sqlException, sql );
            }
            if ( 515 == errorCode && "ZZZZZ".equals( sqlState ) ) {
                // Attempt to insert NULL value into column; column does not allow nulls.
                final String constraintName = getViolatedConstraintNameExtracter().extractConstraintName( sqlException );
                return new ConstraintViolationException( message, sqlException, sql, constraintName );
            }
            return null;
        }
    };
}
项目:dropwizard-db-sharding-bundle    文件:LockTest.java   
@Test(expected = ConstraintViolationException.class)
public void testPersist_alreadyExistingDifferent() throws Exception {
    SomeLookupObject p1 = SomeLookupObject.builder()
            .myId("0")
            .name("Parent 1")
            .build();

    lookupDao.save(p1);

    SomeLookupObject p2 = SomeLookupObject.builder()
            .myId("0")
            .name("Changed")
            .build();

    lookupDao.saveAndGetExecutor(p2)
            .filter(parent -> !Strings.isNullOrEmpty(parent.getName()))
            .save(relationDao, parent -> SomeOtherObject.builder()
                    .my_id(parent.getMyId())
                    .value("Hello")
                    .build())
            .execute();

    Assert.assertEquals(p1.getMyId(), lookupDao.get("0").get().getMyId());
    Assert.assertEquals("Changed", lookupDao.get("0").get().getName());
}
项目:notification-server    文件:BaseDAO.java   
public T create(T entity) throws HibernateException, SQLException {
    Transaction t = getSession().getTransaction();
    try {
        t.begin();
        getSession().saveOrUpdate(entity);
        t.commit();
    } catch (HibernateException e) {
        if (t != null) {
            LOGGER.error("ROLLBACK: " + entity);
            t.rollback();
        }
        if (e instanceof ConstraintViolationException){
            throw ((ConstraintViolationException)e).getSQLException();
        }
        throw e;
    }
    return entity;
}
项目:abixen-platform    文件:DataSourceController.java   
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public FormValidationResultDto updateDataSource(@PathVariable("id") Long id, @RequestBody @Valid DataSourceForm dataSourceForm, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        List<FormErrorDto> formErrors = ValidationUtil.extractFormErrors(bindingResult);
        return new FormValidationResultDto(dataSourceForm, formErrors);
    }
    try {
        dataSourceFacade.updateDataSource(dataSourceForm);
    } catch (Throwable e) {
        log.error(e.getMessage());
        if (e.getCause() instanceof ConstraintViolationException) {
            throw new PlatformRuntimeException("Data source can not be updated. If you want to change available columns then you need to detach they from module firstly.");
        } else {
            throw e;
        }
    }
    return new FormValidationResultDto(dataSourceForm);
}
项目:flux    文件:StateMachineResource.java   
/**
 * Will instantiate a state machine in the flux execution engine
 *
 * @param stateMachineDefinition User input for state machine
 * @return unique machineId of the instantiated state machine
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Timed
public Response createStateMachine(StateMachineDefinition stateMachineDefinition) throws Exception {

    if (stateMachineDefinition == null)
        throw new IllegalRepresentationException("State machine definition is empty");

    StateMachine stateMachine = null;

    try {
        stateMachine = createAndInitStateMachine(stateMachineDefinition);
        metricsClient.markMeter(new StringBuilder().
                append("stateMachine.").
                append(stateMachine.getName()).
                append(".started").toString());
    } catch (ConstraintViolationException ex) {
        //in case of Duplicate correlation key, return http code 409 conflict
        return Response.status(Response.Status.CONFLICT.getStatusCode()).entity(ex.getCause() != null ? ex.getCause().getMessage() : null).build();
    }

    return Response.status(Response.Status.CREATED.getStatusCode()).entity(stateMachine.getId()).build();
}
项目:herd    文件:HerdErrorInformationExceptionHandler.java   
/**
 * Returns {@code true} if the given throwable is or is not caused by a database constraint violation.
 *
 * @param exception - throwable to check.
 *
 * @return {@code true} if is constraint violation, {@code false} otherwise.
 */
private boolean isCausedByConstraintViolationException(Exception exception)
{
    // some databases will throw ConstraintViolationException
    boolean isConstraintViolation = ExceptionUtils.indexOfThrowable(exception, ConstraintViolationException.class) != -1;

    // other databases will not throw a nice exception
    if (!isConstraintViolation)
    {
        // We must manually check the error codes
        Throwable rootThrowable = getRootCause(exception);
        if (rootThrowable instanceof SQLException)
        {
            SQLException sqlException = (SQLException) rootThrowable;
            isConstraintViolation = POSTGRES_SQL_STATE_CODE_FOREIGN_KEY_VIOLATION.equals(sqlException.getSQLState());
        }
    }
    return isConstraintViolation;
}
项目:WechatTicketSystem    文件:Register.java   
private Object register(long sid, String name, ISP isp, String netAccount, int block, int room, long phone, String wechat) {
    if (sid == -1) return Error.INVALID_PARAMETER.withMsg("Invalid_Student_Id");
    if (name == null) return Error.INVALID_PARAMETER.withMsg("Invalid_Name");
    if (isp == null) return Error.INVALID_PARAMETER.withMsg("Invalid_ISP");
    if (netAccount == null) return Error.INVALID_PARAMETER.withMsg("Invalid_Account");
    if (block == -1) return Error.INVALID_PARAMETER.withMsg("Invalid_Block");
    if (room == -1) return Error.INVALID_PARAMETER.withMsg("Invalid_Room");
    if (phone == -1) return Error.INVALID_PARAMETER.withMsg("Invalid_Phone_Number");
    User user = TableUser.getById(sid);
    if (user == null) return Error.INVALID_PARAMETER.withMsg("Invalid_Student_Id");
    if (!user.getName().equals(name)) return Error.INVALID_PARAMETER.withMsg("Invalid_Name");
    if (user.getWechatId() != null) return Error.INVALID_PARAMETER.withMsg("User_Already_Registered");
    user.setIsp(isp);
    user.setNetAccount(netAccount);
    user.setBlock(block);
    user.setRoom(room);
    user.setPhone(phone);
    user.setWechatId(wechat);
    try {
        TableUser.update(user);
    } catch (ConstraintViolationException e) {
        String dupKey = e.getConstraintName();
        return Error.INVALID_PARAMETER.withMsg("Duplicated_" + dupKey.toUpperCase()); // PHONE ACCOUNT WECHAT
    }
    return Error.OK;
}
项目:coner-core    文件:RunDaoTest.java   
@Test
@Ignore("Deferring work on this, see https://github.com/caeos/coner-core/issues/181")
public void itShouldThrowWhenEventAndSequenceNotUnique() throws InterruptedException {
    RunHibernateEntity entity1 = buildUnsavedRun();
    entity1.setSequence(1);
    RunHibernateEntity entity2 = buildUnsavedRun();
    entity2.setSequence(1);

    // sanity checks
    assertThat(entity1.getEvent()).isSameAs(entity2.getEvent());
    assertThat(entity1.getSequence()).isEqualTo(entity2.getSequence());

    try {
        daoTestRule.inTransaction(() -> {
            dao.create(entity1);
            dao.create(entity2);
            failBecauseExceptionWasNotThrown(PersistenceException.class);
        });
    } catch (Exception e) {
        assertThat(e)
                .isInstanceOf(PersistenceException.class)
                .hasCauseInstanceOf(ConstraintViolationException.class);
    }
}
项目:gisgraphy    文件:OpenStreetMapDaoTest.java   
@Test
public void testCouldNotSaveNonUniqueGID(){
    OpenStreetMap streetOSM = GisgraphyTestHelper.createOpenStreetMapForPeterMartinStreet();
openStreetMapDao.save(streetOSM);
assertNotNull(openStreetMapDao.get(streetOSM.getId()));

OpenStreetMap streetOSM2 = GisgraphyTestHelper.createOpenStreetMapForPeterMartinStreet();
try {
    openStreetMapDao.save(streetOSM2);
    openStreetMapDao.flushAndClear();
    fail("we should not save street with non unique GID");
} catch (DataIntegrityViolationException e) {
  assertTrue("a ConstraintViolationException should be throw when saving an openstreetmap with a non unique gid ",e.getCause() instanceof ConstraintViolationException);
}


}
项目:atsy    文件:UserServiceImpl.java   
@Transactional
@Override
public Long saveOrUpdate(UserDTO userDTO) {
  Assert.notNull(userDTO);
  UserEntity entity = converterService.convert(userDTO, UserEntity.class);
  try {
    return userRepository.saveAndFlush(entity).getId();
  } catch (ConstraintViolationException | DataIntegrityViolationException ex) {
    log.error("Save to repository failed.", ex);

    String userName = entity.getUserName();

    throw new DuplicateRecordException(userName,
        "Duplication occurred when saving user: " + userName, ex);
  }
}
项目:atsy    文件:CandidateServiceImplTest.java   
@Test
public void saveOrUpdateShouldThrowDREAfterCatchingConstraintViolationException()
    throws DuplicateCandidateException {
  // Given
  given(converterService.convert(dummyCandidateDto, CandidateEntity.class))
      .willReturn(dummyCandidateEntity);

  given(candidateRepository.saveAndFlush(dummyCandidateEntity))
      .willThrow(ConstraintViolationException.class);

  expectedException.expect(DuplicateCandidateException.class);
  expectedException.expectMessage(CoreMatchers.endsWith(NAME));
  expectedException.expectCause(Matchers.isA(ConstraintViolationException.class));

  // When
  candidateService.saveOrUpdate(dummyCandidateDto);
  // Then
}
项目:ums-backend    文件:PersistenceExceptionHandler.java   
@Override
@ResponseBody
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(value = {PersistenceException.class})
public MessageResource handle(final PersistenceException e) {
    LOGGER.error("Handling persistence exception", e);

    MessageResource message = new MessageResource();
    message.setMessageType(MessageType.ERROR);
    if (e.getCause() instanceof ConstraintViolationException) {
        message.setMessage(MessageFormat.format("ConstraintViolationName : {0}", ((ConstraintViolationException) e.getCause()).getConstraintName()));
    } else {
        message.setMessage(e.getMessage());
    }

    return message;
}
项目:zstack    文件:AccountBase.java   
@Transactional
private void handle(APIAttachPoliciesToUserMsg msg) {
    for (String puuid : msg.getPolicyUuids()) {
        try {
            UserPolicyRefVO refVO = new UserPolicyRefVO();
            refVO.setUserUuid(msg.getUserUuid());
            refVO.setPolicyUuid(puuid);
            dbf.getEntityManager().persist(refVO);
            dbf.getEntityManager().flush();
        } catch (Throwable t) {
            if (!ExceptionDSL.isCausedBy(t, ConstraintViolationException.class)) {
                throw t;
            }

            // the policy is already attached
        }
    }

    APIAttachPoliciesToUserEvent evt = new APIAttachPoliciesToUserEvent(msg.getId());
    bus.publish(evt);
}
项目:zstack    文件:AccountBase.java   
private void handle(APIAttachPolicyToUserGroupMsg msg) {
    UserGroupPolicyRefVO grvo = new UserGroupPolicyRefVO();
    grvo.setGroupUuid(msg.getGroupUuid());
    grvo.setPolicyUuid(msg.getPolicyUuid());

    try {
        dbf.persist(grvo);
    } catch (Throwable t) {
        if (!ExceptionDSL.isCausedBy(t, ConstraintViolationException.class)) {
            throw t;
        }

        // the policy is already attached
    }

    APIAttachPolicyToUserGroupEvent evt = new APIAttachPolicyToUserGroupEvent(msg.getId());
    bus.publish(evt);
}
项目:zstack    文件:AccountBase.java   
private void handle(APIAttachPolicyToUserMsg msg) {
    UserPolicyRefVO upvo = new UserPolicyRefVO();
    upvo.setPolicyUuid(msg.getPolicyUuid());
    upvo.setUserUuid(msg.getUserUuid());
    try {
        dbf.persist(upvo);
    } catch (Throwable t) {
        if (!ExceptionDSL.isCausedBy(t, ConstraintViolationException.class)) {
            throw t;
        }

        // the policy is already attached
    }

    APIAttachPolicyToUserEvent evt = new APIAttachPolicyToUserEvent(msg.getId());
    bus.publish(evt);
}
项目:Lucee4    文件:CommonUtil.java   
public static PageException toPageException(Throwable t) {
    lucee.commons.lang.ExceptionUtil.rethrowIfNecessary(t);
    PageException pe = caster().toPageException(t);;
    if (t instanceof org.hibernate.HibernateException) {
        org.hibernate.HibernateException he = (org.hibernate.HibernateException)t;
        Throwable cause = he.getCause();
        if(cause != null) {
            pe = caster().toPageException( cause );
            ExceptionUtil.setAdditional(pe, CommonUtil.createKey("hibernate exception"), t );
        }
    }
    if ( t instanceof JDBCException ) {
        JDBCException je = (JDBCException)t;
        ExceptionUtil.setAdditional(pe, CommonUtil.createKey("sql"), je.getSQL());
    }
    if( t instanceof ConstraintViolationException) {
        ConstraintViolationException cve = (ConstraintViolationException)t;
        if(!Util.isEmpty(cve.getConstraintName())) {
            ExceptionUtil.setAdditional(pe, CommonUtil.createKey("constraint name"), cve.getConstraintName());
        }
    }
    return pe;

}
项目:jspresso-ce    文件:AbstractFrontendController.java   
/**
 * Refines the data integrity violation exception to determine the translation
 * key from which the user message will be constructed.
 *
 * @param exception
 *     the DataIntegrityViolationException.
 * @return the translation key to use.
 */
protected String refineIntegrityViolationTranslationKey(DataIntegrityViolationException exception) {
  if (exception.getCause() instanceof ConstraintViolationException) {
    ConstraintViolationException cve = (ConstraintViolationException) exception.getCause();
    if (cve.getSQL() != null && cve.getSQL().toUpperCase().contains("DELETE")) {
      return "error.fk.delete";
    }
    if (cve.getConstraintName() != null) {
      if (cve.getConstraintName().toUpperCase().contains("FK")) {
        return "error.fk.update";
      }
      return "error.unicity";
    }
    return "error.integrity";
  }
  return "error.integrity";
}
项目:gomall.la    文件:MappingExceptionResolver.java   
/**
 * Gets the exception message.
 * 
 * @param e
 *            the e
 * @return the exception message
 */
public void getExceptionMessage(UserMessages uem, Exception e,String errorCode ) {
    Throwable throwable = e;
    if (throwable.getCause() != null) {
        throwable = throwable.getCause();
    }
    String title = ResourceBundleHelper.getString("error.code." + errorCode);
    if(AppUtils.isNotBlank(title)){
        uem.setTitle(title);
    }else{
        String errCode = null;
        if ((throwable instanceof ConstraintViolationException) || (throwable instanceof BatchUpdateException) || (throwable instanceof DataIntegrityViolationException)) {
            errCode = ErrorCodes.RESOURCE_CONFLICT;
        }else if (throwable instanceof NullPointerException) {
            errCode = ErrorCodes.ENTITY_NO_FOUND;
        }
        uem.setTitle(ResourceBundleHelper.getString("error.code." + errCode));
    }

    uem.setDesc(throwable.getMessage());
}
项目:systematic-trading    文件:HibernateTradingDayPricesDao.java   
@Override
public void create( final TradingDayPrices[] data ) {

    final Session session = HibernateUtil.sessionFactory().getCurrentSession();
    final Transaction tx = session.beginTransaction();

    for (final TradingDayPrices d : data) {
        try {
            create(d, session);
        } catch (final HibernateException e) {

            if (e.getCause() instanceof ConstraintViolationException) {
                // Only constraint violation here will be primary key, or attempting to insert
                // data already present
                LOG.debug(e.getMessage());
            } else {
                throw e;
            }

        }
    }

    tx.commit();
}
项目:zlogger    文件:CommentaryServiceImpl.java   
@Override
@Transactional
public Long add(Commentary entity) {
    Objects.requireNonNull(entity, "Can't add null commentary");
    User user = entity.getCreator();
    Post post = entity.getPost();
    Objects.requireNonNull(post, "Can't add commentary with null post");
    Objects.requireNonNull(user, "Can't add commentary with null creator");
    Objects.requireNonNull(post.getId(), "Can't add commentary with null post_id");
    Objects.requireNonNull(user.getUsername(),
            "Can't add commentary with null creator_name");
    if (!user.getEnabled()) {
        throw new IllegalStateException("Can't add commentary with disabled creator");
    }

    entity.setCreationDate(new Date());
    try {
        return commentaryDao.create(entity);
    } catch (ConstraintViolationException e) {
        LOGGER.log(Level.WARNING, e.toString());
        throw new IllegalArgumentException("Commentary is malformed or it's " +
                "dependencies are not persistent. " +
                "Violated constraint: " + e.getConstraintName());

    }
}
项目:olat    文件:TransactionRetryerITCaseNew.java   
@Test
public void testSubscribe_IfCoreServiceThrowsException_checkNumberOfRetries() {

    NotificationService mockNotificationService = mock(NotificationService.class);
    when(mockNotificationService.subscribe(notificationSubscriptionContext1)).thenThrow(new ConstraintViolationException(IDENTITY_NAME_1, null, IDENTITY_NAME_1));
    learnServiceImpl.setNotificationService(mockNotificationService);

    try {
        verify(learnServiceImpl.subscribe(notificationSubscriptionContext1));
    } catch (Exception e) {
        System.out.println("catch to check for number of retries");
    }
    // the number of retries for ConstraintViolationException is configured via maxRetriesPerException bean property in lmsLearnTestContext.xml
    verify(mockNotificationService, times(2)).subscribe(notificationSubscriptionContext1);

}
项目:olat    文件:TransactionRetryerITCaseNew.java   
@Test
public void isRetryStillAllowed_oneExceptionType_oneRetryAllowed() {
    Map<String, Long> retriesPerException = new HashMap<String, Long>();
    assertTrue(transactionRetryer.isRetryStillAllowed(retriesPerException));

    // retry once allowed
    transactionRetryer.addOrIncrementRetries(retriesPerException, ConstraintViolationException.class.getName());
    assertTrue(transactionRetryer.isRetryStillAllowed(retriesPerException));

    // retry second time no more allowed
    transactionRetryer.addOrIncrementRetries(retriesPerException, ConstraintViolationException.class.getName());
    assertFalse(transactionRetryer.isRetryStillAllowed(retriesPerException));

    // retry no more allowed
    transactionRetryer.addOrIncrementRetries(retriesPerException, ConstraintViolationException.class.getName());
    assertFalse(transactionRetryer.isRetryStillAllowed(retriesPerException));
}
项目:olat    文件:TransactionRetryerITCaseNew.java   
@Test
public void testSubscribe_IfCoreServiceThrowsException_checkNumberOfRetries() {

    NotificationService mockNotificationService = mock(NotificationService.class);
    when(mockNotificationService.subscribe(notificationSubscriptionContext1)).thenThrow(new ConstraintViolationException(IDENTITY_NAME_1, null, IDENTITY_NAME_1));
    learnServiceImpl.setNotificationService(mockNotificationService);

    try {
        verify(learnServiceImpl.subscribe(notificationSubscriptionContext1));
    } catch (Exception e) {
        System.out.println("catch to check for number of retries");
    }
    // the number of retries for ConstraintViolationException is configured via maxRetriesPerException bean property in lmsLearnTestContext.xml
    verify(mockNotificationService, times(2)).subscribe(notificationSubscriptionContext1);

}
项目:olat    文件:TransactionRetryerITCaseNew.java   
@Test
public void isRetryStillAllowed_oneExceptionType_oneRetryAllowed() {
    Map<String, Long> retriesPerException = new HashMap<String, Long>();
    assertTrue(transactionRetryer.isRetryStillAllowed(retriesPerException));

    // retry once allowed
    transactionRetryer.addOrIncrementRetries(retriesPerException, ConstraintViolationException.class.getName());
    assertTrue(transactionRetryer.isRetryStillAllowed(retriesPerException));

    // retry second time no more allowed
    transactionRetryer.addOrIncrementRetries(retriesPerException, ConstraintViolationException.class.getName());
    assertFalse(transactionRetryer.isRetryStillAllowed(retriesPerException));

    // retry no more allowed
    transactionRetryer.addOrIncrementRetries(retriesPerException, ConstraintViolationException.class.getName());
    assertFalse(transactionRetryer.isRetryStillAllowed(retriesPerException));
}
项目:openeos    文件:UIDAOServiceImpl.java   
@Override
@Transactional(readOnly = false, rollbackFor = { UIDAOCoinstraintValidationException.class })
public void save(UIBean bean) throws UIDAOCoinstraintValidationException {
    if (bean instanceof UIBeanImpl) {
        UIBeanImpl uiBeanI = (UIBeanImpl) bean;
        Session ses = getSession();
        Object id = dictionaryService.getClassDefinition(uiBeanI.getBeanWrapped().getClass()).getIdPropertyDefinition()
                .get(uiBeanI.getBeanWrapped());
        try {
            ses.saveOrUpdate(uiBeanI.getBeanWrapped());
            ses.flush();
            uiBeanI.fireOnSave();
        } catch (HibernateException ex) {
            // See https://hibernate.atlassian.net/browse/HB-1014
            dictionaryService.getClassDefinition(uiBeanI.getBeanWrapped().getClass()).getIdPropertyDefinition()
                    .set(uiBeanI.getBeanWrapped(), id);
            if (ex instanceof ConstraintViolationException) {
                ConstraintViolationException constraintException = (ConstraintViolationException) ex;
                throw new UIDAOCoinstraintValidationException(constraintException);
            }
            throw ex;
        }
    } else {
        throw new UnsupportedOperationException("Don't recognice bean passes as argument, must be UIBeanImpl class.");
    }
}
项目:openeos    文件:PostgreSQLDialectBatchUpdateResolver.java   
@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);
                    }
                }
            }
        }
    }
    return null;
}
项目:openeos    文件:AttachmentServiceImpl.java   
@Override
public Attachment attachFile(Class<?> entityClass, String entityId, String attachmentType, String name, String mimeType,
        InputStream content) {
    try {
        org.openeos.attachments.model.Attachment attachModel = new org.openeos.attachments.model.Attachment();
        attachModel.setAttachmentType(attachmentType);
        attachModel.setCreationDate(new Date());
        attachModel.setModifiedDate(attachModel.getCreationDate());
        attachModel.setEntityClass(entityClass.getName());
        attachModel.setEntityId(entityId);
        attachModel.setName(name);
        attachModel.setMimeType(mimeType);
        attachmentDAO.setContent(attachModel, content);
        attachmentDAO.create(attachModel);
        return createAttachment(attachModel);
    } catch (ConstraintViolationException e) {
        throw new RuntimeException("The given name, attachment type already exists in the entity given");
    }
}
项目:coner-core    文件:RunDaoTest.java   
@Test
@Ignore("Deferring work on this, see https://github.com/caeos/coner-core/issues/181")
public void itShouldThrowWhenEventAndSequenceNotUnique() throws InterruptedException {
    RunHibernateEntity entity1 = buildUnsavedRun();
    entity1.setSequence(1);
    RunHibernateEntity entity2 = buildUnsavedRun();
    entity2.setSequence(1);

    // sanity checks
    assertThat(entity1.getEvent()).isSameAs(entity2.getEvent());
    assertThat(entity1.getSequence()).isEqualTo(entity2.getSequence());

    try {
        daoTestRule.inTransaction(() -> {
            dao.create(entity1);
            dao.create(entity2);
            failBecauseExceptionWasNotThrown(PersistenceException.class);
        });
    } catch (Exception e) {
        assertThat(e)
                .isInstanceOf(PersistenceException.class)
                .hasCauseInstanceOf(ConstraintViolationException.class);
    }
}
项目:class-guard    文件:HibernateInterceptorTests.java   
@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 {
        interceptor.invoke(invocation);
        fail("Should have thrown DataIntegrityViolationException");
    }
    catch (DataIntegrityViolationException ex) {
        // expected
        assertEquals(jdbcEx, ex.getCause());
    }

    verify(session).close();
}
项目:budgetapp    文件:SQLConstraintViolationExceptionMapper.java   
private List<String> getMessage(PersistenceException e) {

        LOGGER.error(e.getMessage(), e);

        if(e.getCause() instanceof ConstraintViolationException) {
            // a hack to convert exception to friendly error message
            ConstraintViolationException cve = (ConstraintViolationException) e.getCause();
            if ("fk_budgets_categories".equalsIgnoreCase(cve.getConstraintName())) {
                return Collections.singletonList("Failed to delete category due to references to existing budget(s).");
            } else if ("fk_transactions_budgets".equalsIgnoreCase(cve.getConstraintName())) {
                return Collections.singletonList("Failed to delete budget due to references to existing transaction(s).");
            }
            return Collections.singletonList(e.getMessage());
        } else {
            return Collections.singletonList(e.getMessage());
        }
    }
项目:ss    文件:IraBankExceptionController.java   
@ExceptionHandler(value = 
        {
        Exception.class, 
        NullPointerException.class,
        NoSuchRequestHandlingMethodException.class, 
        RuntimeException.class,
        ResourceAccessException.class,
        AccessDeniedException.class,
        PropertyNotFoundException.class,
        ConstraintViolationException.class,
        NestedServletException.class}
        )

// Don't pass model object here. Seriously was creating issues here.
   public ModelAndView globalErrorHandler(HttpServletRequest request, Exception e) {
           System.out.println("comes in exception controller");
           ModelAndView mdlViewObj = new ModelAndView("/common/Exception");
           logger.error(e.getStackTrace());
           return mdlViewObj;
           //return new ModelAndView("common/Exception"); // Error java.lang.IllegalStateException: No suitable resolver for argument [0] [type=org.springframework.ui.ModelMap]
}
项目:ss    文件:AccountDAOImpl.java   
@Override
public Boolean addNewAccount(AccountDetailsDTO accountdetailsDTO) {

    try{

        sessionFactory.getCurrentSession().save(accountdetailsDTO);

        return true;
    }
    catch (ConstraintViolationException e){
     System.out.println("The error is "+ e);
     e.printStackTrace();
     return false;   
    }

}
项目:spring-test-example    文件:AbstractDataOnDemand.java   
public void init() {
    //Some repositories might have security annotations so we temporary acquire admin rights.
    SecurityContextHolder.getContext().setAuthentication(AuthenticationMocks.adminAuthentication(0L));
    data = repository.findAll();
    if (data == null) {
        throw new IllegalStateException("Find entries implementation for 'Component' illegally returned null");
    }
    if (data.size() > getExpectedElements()) {
        return;
    }

    data = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        S obj = getNewTransientObject(i);
        try {
            repository.save(obj);
        } catch (final ConstraintViolationException e) {
            throw new IllegalStateException(e);
        }
        data.add(obj);
    }
}
项目:ABRAID-MP    文件:AdminUnitDiseaseExtentClassDaoTest.java   
@Test(expected = ConstraintViolationException.class)
public void cannotSpecifyBothGlobalAndTropicalAdminUnit() {
    // Arrange
    AdminUnitGlobal adminUnitGlobal = adminUnitGlobalDao.getByGaulCode(2510);
    AdminUnitTropical adminUnitTropical = adminUnitTropicalDao.getByGaulCode(204001);
    DiseaseGroup diseaseGroup = diseaseGroupDao.getById(96);
    DiseaseExtentClass extentClass = diseaseExtentClassDao.getByName(DiseaseExtentClass.ABSENCE);
    DiseaseExtentClass validatorExtentClass = diseaseExtentClassDao.getByName(DiseaseExtentClass.POSSIBLE_ABSENCE);
    int occurrenceCount = 0;

    AdminUnitDiseaseExtentClass adminUnitDiseaseExtentClass = new AdminUnitDiseaseExtentClass(
            adminUnitTropical, diseaseGroup, extentClass, validatorExtentClass, occurrenceCount);
    adminUnitDiseaseExtentClass.setAdminUnitGlobal(adminUnitGlobal);

    // Act
    // Cannot use catchException() because the sessionFactory becomes null for some reason -
    // expected exception is specified in the @Test annotation
    adminUnitDiseaseExtentClassDao.save(adminUnitDiseaseExtentClass);
}
项目:gort-public    文件:GortEntityManager.java   
public void insertEntity(EntityManager em, Object o) {
    if (o == null) {
        return;
    }

    if (em == null) {
        em = getDefaultEntityManager();
    }

    try {
        em.getTransaction().begin();
        em.persist(o);
        em.getTransaction().commit();
    } catch (ConstraintViolationException cve) {
        System.out.println("Constration violation while adding " + o);
        cve.printStackTrace();
    }
}