org.hibernate.exception.ConstraintViolationException Java Examples
The following examples show how to use
org.hibernate.exception.ConstraintViolationException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HerdErrorInformationExceptionHandler.java From herd with Apache License 2.0 | 6 votes |
/** * 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; if (POSTGRES_SQL_STATE_CODE_FOREIGN_KEY_VIOLATION.equals(sqlException.getSQLState()) || POSTGRES_SQL_STATE_CODE_UNIQUE_INDEX_OR_PRIMARY_KEY_VIOLATION.equals(sqlException.getSQLState())) { isConstraintViolation = true; } } } return isConstraintViolation; }
Example #2
Source File: TransactionRetryerITCaseNew.java From olat with Apache License 2.0 | 6 votes |
@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)); }
Example #3
Source File: HibernateInterceptorTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@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(); }
Example #4
Source File: TransactionRetryerITCaseNew.java From olat with Apache License 2.0 | 6 votes |
@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); }
Example #5
Source File: SybaseASE157Dialect.java From lams with GNU General Public License v2.0 | 6 votes |
@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; } }; }
Example #6
Source File: DataSourceController.java From abixen-platform with GNU Lesser General Public License v2.1 | 6 votes |
@RequestMapping(value = "/{id}", method = RequestMethod.PUT) public FormValidationResultRepresentation<DataSourceForm> updateDataSource(@PathVariable("id") Long id, @RequestBody @Valid DataSourceForm dataSourceForm, BindingResult bindingResult) { log.debug("updateDataSource() - dataSourceForm: {}, bindingResult: {}", dataSourceForm, bindingResult); if (bindingResult.hasErrors()) { List<FormErrorRepresentation> formErrors = ValidationUtil.extractFormErrors(bindingResult); return new FormValidationResultRepresentation<>(dataSourceForm, formErrors); } //FIXME - move to domain try { dataSourceManagementService.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 FormValidationResultRepresentation<>(dataSourceForm); }
Example #7
Source File: CacheSQLExceptionConversionDelegate.java From lams with GNU General Public License v2.0 | 6 votes |
/** * 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 }
Example #8
Source File: JpaExceptionMapperTests.java From crnk-framework with Apache License 2.0 | 6 votes |
@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()); }
Example #9
Source File: TransactionRetryerITCaseNew.java From olat with Apache License 2.0 | 6 votes |
@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)); }
Example #10
Source File: BlueprintService.java From cloudbreak with Apache License 2.0 | 6 votes |
private Set<Blueprint> updateDefaultBlueprintCollection(Workspace workspace) { Set<Blueprint> blueprintsInDatabase = blueprintRepository.findAllByWorkspaceIdAndStatusIn(workspace.getId(), Set.of(DEFAULT, DEFAULT_DELETED, USER_MANAGED)); if (!blueprintLoaderService.isAddingDefaultBlueprintsNecessaryForTheUser(blueprintsInDatabase)) { if (blueprintLoaderService.defaultBlueprintDoesNotExistInTheCache(blueprintsInDatabase)) { blueprintLoaderService.deleteOldDefaults(blueprintsInDatabase); } return blueprintsInDatabase.stream() .filter(bp -> DEFAULT.equals(bp.getStatus()) || DEFAULT_DELETED.equals(bp.getStatus())) .collect(Collectors.toSet()); } LOGGER.debug("Modifying blueprints based on the defaults for the '{}' workspace.", workspace.getId()); try { Set<Blueprint> updatedBlueprints = blueprintLoaderService.loadBlueprintsForTheWorkspace(blueprintsInDatabase, workspace, this::saveDefaultsWithReadRight); LOGGER.debug("Blueprint modifications finished based on the defaults for '{}' workspace.", workspace.getId()); return updatedBlueprints; } catch (ConstraintViolationException e) { return updateDefaultBlueprintCollection(workspace); } }
Example #11
Source File: AccountBase.java From zstack with Apache License 2.0 | 6 votes |
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); }
Example #12
Source File: UserStoreIntegrationTests.java From judgels with GNU General Public License v2.0 | 6 votes |
@Test void email_has_unique_constraint() { UserData userData = new UserData.Builder() .username("username") .password("password") .email("[email protected]") .build(); store.createUser(userData); UserData newUserData = new UserData.Builder() .username("new.username") .password("new.password") .email("[email protected]") .build(); assertThatExceptionOfType(ConstraintViolationException.class) .isThrownBy(() -> store.createUser(newUserData)); }
Example #13
Source File: AccountBase.java From zstack with Apache License 2.0 | 6 votes |
@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); }
Example #14
Source File: SQLiteDialect.java From yeti with MIT License | 6 votes |
@Override public SQLExceptionConverter buildSQLExceptionConverter() { return new SQLExceptionConverter() { @Override public JDBCException convert(SQLException sqlException, String message, String sql) { final int errorCode = sqlException.getErrorCode(); if (errorCode == SQLITE_CONSTRAINT) { final String constraintName = EXTRACTER.extractConstraintName(sqlException); return new ConstraintViolationException(message, sqlException, sql, constraintName); } else if (errorCode == SQLITE_TOOBIG || errorCode == SQLITE_MISMATCH) { return new DataException(message, sqlException, sql); } else if (errorCode == SQLITE_BUSY || errorCode == SQLITE_LOCKED) { return new LockAcquisitionException(message, sqlException, sql); } else if ((errorCode >= SQLITE_IOERR && errorCode <= SQLITE_PROTOCOL) || errorCode == SQLITE_NOTADB) { return new JDBCConnectionException(message, sqlException, sql); } return new GenericJDBCException(message, sqlException, sql); } }; }
Example #15
Source File: ThrowableUtilTest.java From cloudbreak with Apache License 2.0 | 5 votes |
@Test public void testExpectedExceptionIsOneLevelDeep() { ConstraintViolationException t = new ConstraintViolationException(null, null, null); RuntimeException rt = new RuntimeException("RT", t); assertEquals("Should find the desired exception if cause s set", t, ThrowableUtil.getSpecificCauseRecursively(rt, ConstraintViolationException.class)); }
Example #16
Source File: AbstractWorkspaceAwareResourceService.java From cloudbreak with Apache License 2.0 | 5 votes |
private T createInternal(T resource, Workspace workspace, User user) { try { MDCBuilder.buildMdcContext(resource); prepareCreation(resource); setWorkspace(resource, user, workspace); return repository().save(resource); } catch (DataIntegrityViolationException | ConstraintViolationException e) { String message = String.format("%s already exists with name '%s' in workspace %s", resource.getResourceName(), resource.getName(), resource.getWorkspace().getName()); throw new BadRequestException(message, e); } }
Example #17
Source File: PooledSequenceIdentifierTest.java From hibernate-master-class with Apache License 2.0 | 5 votes |
@Test @Ignore public void testPooledOptimizerThrowsException() { try { insertSequences(); fail("Expecting ConstraintViolationException!"); } catch (Exception e) { assertEquals(ConstraintViolationException.class, e.getClass()); LOGGER.error("Pooled optimizer threw", e); } }
Example #18
Source File: DatabaseEntityDao.java From yeti with MIT License | 5 votes |
public E saveOrUpdate(E e) { try { HibernateUtil.getSession().saveOrUpdate(e); return e; } catch (ConstraintViolationException cve) { Logger.getLogger("saveOrUpdate").log(Level.INFO, "The entity will not be persisted as a duplicate already exists.", cve); } return null; }
Example #19
Source File: TransactionRetryerITCaseNew.java From olat with Apache License 2.0 | 5 votes |
/** * Assumes that ConstraintViolationException could be retried once while MailSendException could be retried 3 times, see lmsLearnTestContext.xml for * maxRetriesPerException. */ @Test public void isRetryStillAllowed_twoExceptionTypes_moreRetriesAllowed() { Map<String, Long> retriesPerException = new HashMap<String, Long>(); assertTrue(transactionRetryer.isRetryStillAllowed(retriesPerException)); // retry for ConstraintViolationException transactionRetryer.addOrIncrementRetries(retriesPerException, ConstraintViolationException.class.getName()); assertTrue(transactionRetryer.isRetryStillAllowed(retriesPerException)); for (int i = 0; i < 3; i++) { // retry for MailSendException transactionRetryer.addOrIncrementRetries(retriesPerException, MailSendException.class.getName()); assertTrue(transactionRetryer.isRetryStillAllowed(retriesPerException)); } // retry for MailSendException - isRetryStillAllowed should return false since MailSendException is configured to be retried 3 times transactionRetryer.addOrIncrementRetries(retriesPerException, MailSendException.class.getName()); boolean isMailSendExceptionRetryAllowed = transactionRetryer.isRetryStillAllowed(retriesPerException); // retry second time no more allowed - throw error further transactionRetryer.addOrIncrementRetries(retriesPerException, ConstraintViolationException.class.getName()); boolean isConstraintViolationExceptionAllowed = transactionRetryer.isRetryStillAllowed(retriesPerException); assertFalse(isMailSendExceptionRetryAllowed); assertFalse(isConstraintViolationExceptionAllowed); // retry no more allowed transactionRetryer.addOrIncrementRetries(retriesPerException, ConstraintViolationException.class.getName()); assertFalse(transactionRetryer.isRetryStillAllowed(retriesPerException)); }
Example #20
Source File: SubscriberDaoITCaseNew.java From olat with Apache License 2.0 | 5 votes |
@Ignore // ignore since removed flush after save @Test(expected = ConstraintViolationException.class) public void createAndSaveSubscriber_cannotCreateSameSubscriberTwice() { Subscriber subscriberEntity_1 = createTestSubscriber(); Subscriber subscriberEntity_2 = createTestSubscriber(); }
Example #21
Source File: InventoryTests.java From salespoint with Apache License 2.0 | 5 votes |
/** * @see #68 */ void rejectsNewInventoryItemForExistingProducts() { unique.save(new UniqueInventoryItem(cookie, Quantity.of(10))); assertThatExceptionOfType(PersistenceException.class) // .isThrownBy(() -> em.flush()) // .withCauseExactlyInstanceOf(ConstraintViolationException.class); }
Example #22
Source File: TransactionRetryerITCaseNew.java From olat with Apache License 2.0 | 5 votes |
@Test(expected = ConstraintViolationException.class) public void testSubscribe_IfCoreServiceThrowsException() { NotificationService mockNotificationService = mock(NotificationService.class); when(mockNotificationService.subscribe(notificationSubscriptionContext1)).thenThrow(new ConstraintViolationException(IDENTITY_NAME_1, null, IDENTITY_NAME_1)); learnServiceImpl.setNotificationService(mockNotificationService); learnServiceImpl.subscribe(notificationSubscriptionContext1); }
Example #23
Source File: SubscriptionDaoITCaseNew.java From olat with Apache License 2.0 | 5 votes |
@Test(expected = ConstraintViolationException.class) @Ignore /** TODO: set to ignore - subscriptions are now reused **/ public void createAndSaveSubscription_cannotCreateSameSubscriptionTwice() { Publisher publisher = publisherDao.findPublisher(contextId, Publisher.ContextType.COURSE, sourceId, ForumNotificationTypeHandler.FORUM_SOURCE_TYPE); Subscription subscription_1 = subscriptionDao.createOrReuseSubscription(subscriber, publisher); Subscription subscription_2 = subscriptionDao.createOrReuseSubscription(subscriber, publisher); }
Example #24
Source File: PublisherDaoITCaseNew.java From olat with Apache License 2.0 | 5 votes |
@Ignore // ignore since removed flush after save @Test(expected = ConstraintViolationException.class) public void createAndSavePublisher_cannotCreateSamePublisherTwice() { Long contextId = 111L; ContextType contextType = Publisher.ContextType.COURSE; Long sourceId = 222L; String sourceType = ForumNotificationTypeHandler.FORUM_SOURCE_TYPE; Long subcontextId = 333L; Publisher createdPublisher = publisherDao.createAndSavePublisher(contextId, contextType, sourceId, sourceType, subcontextId); Publisher createdPublisher2 = publisherDao.createAndSavePublisher(contextId, contextType, sourceId, sourceType, subcontextId); }
Example #25
Source File: SubscriberDaoITCaseNew.java From olat with Apache License 2.0 | 5 votes |
@Ignore // ignore since removed flush after save @Test(expected = ConstraintViolationException.class) public void createAndSaveSubscriber_cannotCreateSameSubscriberTwice() { Subscriber subscriberEntity_1 = createTestSubscriber(); Subscriber subscriberEntity_2 = createTestSubscriber(); }
Example #26
Source File: RestExceptionHandler.java From POC with Apache License 2.0 | 5 votes |
/** * Handle DataIntegrityViolationException, inspects the cause for different DB causes. * @param ex the DataIntegrityViolationException * @return the ApiError object * @param request a {@link org.springframework.web.context.request.WebRequest} object. */ @ExceptionHandler(DataIntegrityViolationException.class) protected ResponseEntity<Object> handleDataIntegrityViolation(DataIntegrityViolationException ex, WebRequest request) { if (ex.getCause() instanceof ConstraintViolationException) { return buildResponseEntity(new ApiError(HttpStatus.CONFLICT, "Database error", ex.getCause())); } return buildResponseEntity(new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, ex)); }
Example #27
Source File: RestExceptionHandler.java From POC with Apache License 2.0 | 5 votes |
/** * Handles javax.validation.ConstraintViolationException. Thrown when @Validated * fails. * @param ex the ConstraintViolationException * @return the ApiError object */ @ExceptionHandler(javax.validation.ConstraintViolationException.class) protected ResponseEntity<Object> handleConstraintViolation(javax.validation.ConstraintViolationException ex) { final ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST); apiError.setMessage("Validation error"); apiError.addValidationErrors(ex.getConstraintViolations()); return buildResponseEntity(apiError); }
Example #28
Source File: PersistenceExceptionConverter.java From keycloak with Apache License 2.0 | 5 votes |
public static ModelException convert(Throwable t) { if (t.getCause() != null && t.getCause() instanceof ConstraintViolationException) { throw new ModelDuplicateException(t); } if (t instanceof EntityExistsException || t instanceof ConstraintViolationException) { throw new ModelDuplicateException(t); } else { throw new ModelException(t); } }
Example #29
Source File: HerdErrorInformationExceptionHandlerTest.java From herd with Apache License 2.0 | 5 votes |
@Test public void testConstraintViolationExceptionNoWrap() throws Exception { validateErrorInformation( exceptionHandler.handlePersistenceException(new ConstraintViolationException(MESSAGE, null, "testConstraint"), new MockHttpServletResponse()), HttpStatus.BAD_REQUEST, false); }
Example #30
Source File: HerdErrorInformationExceptionHandlerTest.java From herd with Apache License 2.0 | 5 votes |
@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); validateErrorInformation(exceptionHandler.handlePersistenceException(getPersistenceException(new SQLException(MESSAGE, HerdErrorInformationExceptionHandler.POSTGRES_SQL_STATE_CODE_UNIQUE_INDEX_OR_PRIMARY_KEY_VIOLATION, 0)), new MockHttpServletResponse()), HttpStatus.BAD_REQUEST, false); }