protected void validate(SamlServiceProvider provider) {
if (provider == null) {
throw new NullPointerException("SAML Service Provider can not be null.");
if (!StringUtils.hasText(provider.getIdentityZoneId())) {
throw new DataIntegrityViolationException("Identity zone ID must be set.");
@SuppressWarnings("serial") @Test public void customTranslateMethodTranslation() { final String TASK = "TASK"; final String SQL = "SQL SELECT *"; final DataAccessException customDex = new DataAccessException("") {}; final SQLException badSqlEx = new SQLException("", "", 1); SQLException intVioEx = new SQLException("", "", 6); SQLErrorCodeSQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator() { @Override @Nullable protected DataAccessException customTranslate(String task, @Nullable String sql, SQLException sqlex) { assertEquals(TASK, task); assertEquals(SQL, sql); return (sqlex == badSqlEx) ? customDex : null; sext.setSqlErrorCodes(ERROR_CODES); // Shouldn't custom translate this assertEquals(customDex, sext.translate(TASK, SQL, badSqlEx)); DataIntegrityViolationException diex = (DataIntegrityViolationException) sext.translate(TASK, SQL, intVioEx); assertEquals(intVioEx, diex.getCause());
/**
* The method provides the functionality to store a new token in the token repository
* @param token The token that will be stored in the token repository
@Override
public void createNewToken(PersistentRememberMeToken token) {
try {
mongoOperations.insert(new SessionToken(token));
} catch (DataIntegrityViolationException ex) {
LOGGER.error(ex.getMessage());
throw new DataIntegrityViolationException("Series Id \'" + token.getSeries() + "\' already exists!");
@ExceptionHandler(DataIntegrityViolationException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) protected ErrorResponse handleDataIntegrityViolationException(DataIntegrityViolationException e) { log.error(e.getMessage()); return buildError(ErrorCode.INPUT_VALUE_INVALID);
@Override public JsonResult<User> register(User userToAdd) { if (userToAdd.getAccount() == null || !Util.checkEmail(userToAdd.getAccount())) { return JsonResult.<User>builder().error("注册帐号错误!").build(); BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); final String rawPassword = userToAdd.getPassword(); userToAdd.setPassword(encoder.encode(rawPassword)); userToAdd.setLastPasswordResetDate(new Date()); Role userRole = roleRepository.findByName("ROLE_USER"); if (userRole == null){ userRole = roleRepository.save(new Role("ROLE_USER")); userToAdd.setRoles(Collections.singletonList(userRole)); try { return JsonResult.<User>builder().data(userRepository.save(userToAdd)).build(); } catch (DataIntegrityViolationException e) { logger.debug(e.getMessage()); return JsonResult.<User>builder().error(e.getRootCause().getMessage()).build();
String specificCauseMessage = ((DataIntegrityViolationException) error).getMostSpecificCause()
.getMessage();
String duplicateRegex = "^Duplicate entry '(.*?)'.*";
message = ((DataIntegrityViolationException) error).getRootCause().getMessage();
private void updateEO(Object entity, DataIntegrityViolationException de) {
if (!MySQLIntegrityConstraintViolationException.class.isAssignableFrom(de.getRootCause().getClass())) {
throw de;
MySQLIntegrityConstraintViolationException me = (MySQLIntegrityConstraintViolationException) de.getRootCause();
if (!(me.getErrorCode() == 1062 && "23000".equals(me.getSQLState()) && me.getMessage().contains("PRIMARY"))) {
throw de;
if (!hasEO()) {
throw de;
// at this point, the error is caused by a update tried on VO entity which has been soft deleted. This is mostly
// caused by a deletion cascade(e.g deleting host will cause vm running on it to be deleted, and deleting vm is trying to return capacity
// to host which has been soft deleted, because vm deletion is executed in async manner). In this case, we make the update to EO table
Object idval = getEOPrimaryKeyValue(entity);
Object eo = getEntityManager().find(eoClass, idval);
final Object deo = ObjectUtils.copy(eo, entity);
new Runnable() {
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void run() {
getEntityManager().merge(deo);
}.run();
logger.debug(String.format("A EO[%s] update has been made", eoClass.getName()));
/**
* {@inheritDoc}
@Override
public void createTagIfNotExists(@NotBlank(message = "Tag cannot be blank") final String tag) {
if (this.tagRepository.existsByTag(tag)) {
return;
try {
this.tagRepository.saveAndFlush(new TagEntity(tag));
} catch (final DataIntegrityViolationException e) {
// Must've been created during the time between exists query and now
log.error("Tag expected not to be there but seems to be {}", e.getMessage(), e);
String specificCauseMessage = ((DataIntegrityViolationException) e).
getMostSpecificCause()
.getMessage();
String duplicateRegex = "^Duplicate entry '(.*?)'.*";
message = ((DataIntegrityViolationException) e).getRootCause().getMessage();
Throwable root = e.getRootCause();
String msg = root.getMessage();
Assert.isTrue(msg.contains("Duplicate entry"));
public boolean refreshApproval(final Approval approval, final String zoneId) {
logger.debug(String.format("refreshing approval: [%s]", approval));
int refreshed = jdbcTemplate.update(REFRESH_AUTHZ_SQL, new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setTimestamp(1, new Timestamp(approval.getLastUpdatedAt().getTime()));
ps.setTimestamp(2, new Timestamp(approval.getExpiresAt().getTime()));
ps.setString(3, (approval.getStatus() == null ? APPROVED : approval.getStatus()).toString());
ps.setString(4, approval.getUserId());
ps.setString(5, approval.getClientId());
ps.setString(6, approval.getScope());
ps.setString(7, zoneId);
if (refreshed != 1) {
throw new DataIntegrityViolationException("Attempt to refresh non-existent authorization");
return true;
/**
* {@inheritDoc}
@Override
public void createFileIfNotExists(@NotBlank(message = "File path cannot be blank") final String file) {
if (this.fileRepository.existsByFile(file)) {
return;
// Try to create the file
final FileEntity fileEntity = new FileEntity(file);
try {
this.fileRepository.saveAndFlush(fileEntity);
} catch (final DataIntegrityViolationException e) {
// Must've been created during the time between exists query and now
log.error("File expected not to be there but seems to be {}", e.getMessage(), e);
@Test public void customExceptionTranslation() { final String TASK = "TASK"; final String SQL = "SQL SELECT *"; final SQLErrorCodes customErrorCodes = new SQLErrorCodes(); final CustomSQLErrorCodesTranslation customTranslation = new CustomSQLErrorCodesTranslation(); customErrorCodes.setBadSqlGrammarCodes(new String[] {"1", "2"}); customErrorCodes.setDataIntegrityViolationCodes(new String[] {"3", "4"}); customTranslation.setErrorCodes(new String[] {"1"}); customTranslation.setExceptionClass(CustomErrorCodeException.class); customErrorCodes.setCustomTranslations(new CustomSQLErrorCodesTranslation[] {customTranslation}); SQLErrorCodeSQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(); sext.setSqlErrorCodes(customErrorCodes); // Should custom translate this SQLException badSqlEx = new SQLException("", "", 1); assertEquals(CustomErrorCodeException.class, sext.translate(TASK, SQL, badSqlEx).getClass()); assertEquals(badSqlEx, sext.translate(TASK, SQL, badSqlEx).getCause()); // Shouldn't custom translate this SQLException invResEx = new SQLException("", "", 3); DataIntegrityViolationException diex = (DataIntegrityViolationException) sext.translate(TASK, SQL, invResEx); assertEquals(invResEx, diex.getCause()); // Shouldn't custom translate this - invalid class exception.expect(IllegalArgumentException.class); customTranslation.setExceptionClass(String.class);
@Override public String process(String item) throws Exception { if (item.equals("1")) { throw new DataIntegrityViolationException("Planned"); return item;
/**
* Method that captures all the {@link DataIntegrityViolationException} exceptions.
* @param response
* {@link HttpServletResponse}
* @param request
* {@link HttpServletRequest}
* @param exception
* {@link Exception}
* @return {@link ErroInfo}.
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(DataIntegrityViolationException.class)
public @ResponseBody ErroInfo handleSqlException(HttpServletResponse response, HttpServletRequest request, DataIntegrityViolationException exception) {
if (exception.getMessage().contains("email")) {
return buildErrorInfo(request, new HeimdallException(ExceptionMessage.EMAIL_ALREADY_EXIST));
if (exception.getMessage().contains("username")) {
return buildErrorInfo(request, new HeimdallException(ExceptionMessage.USERNAME_ALREADY_EXIST));
return buildErrorInfo(request, new HeimdallException(ExceptionMessage.GLOBAL_RESOURCE_NOT_FOUND));
return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex);
@Test public void testCreateNewToken_AlreadyExists_ThrowsException() { String series = "1uyasddf32"; PersistentRememberMeToken rememberMeToken = new PersistentRememberMeToken("abdullah", series, "134xsdf32", new Date()); sessionTokenRepository.createNewToken(rememberMeToken); try { sessionTokenRepository.createNewToken(rememberMeToken); fail("should throws exception"); } catch (DataIntegrityViolationException ex) { // Keeping the same message format of the file-based implementation for full compliance. assertThat(ex.getMessage()).isEqualTo("Series Id '1uyasddf32' already exists!");
public class DataIntegrityViolationExceptionsAdvice { public void afterThrowing(DataIntegrityViolationException ex) throws DataIntegrityViolationException { // extract the affected database constraint name: String constraintName = null; if ((ex.getCause() != null) && (ex.getCause() instanceof ConstraintViolationException)) { constraintName = ((ConstraintViolationException) ex.getCause()).getConstraintName();