Java Code Examples for org.springframework.dao.DataIntegrityViolationException

The following examples show how to use org.springframework.dao.DataIntegrityViolationException. These examples are extracted from open source projects. 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
@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 2
public CourseSet createCourseSet(String eid, String title, String description, String category,
		String parentCourseSetEid) throws IdExistsException {
	CourseSet parent = null;
	if(parentCourseSetEid != null) {
		parent = (CourseSet)getObjectByEid(parentCourseSetEid, CourseSetCmImpl.class.getName());
	}
	CourseSetCmImpl courseSet = new CourseSetCmImpl(eid, title, description, category, parent);
	courseSet.setCreatedBy(authn.getUserEid());
	courseSet.setCreatedDate(new Date());
	try {
		getHibernateTemplate().save(courseSet);
		return courseSet;
	} catch (DataIntegrityViolationException dive) {
		throw new IdExistsException(eid, CourseSet.class.getName());
	}
}
 
Example 3
Source Project: vividus   Source File: DatabaseSteps.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Step intended to execute UPDATE, INSERT, DELETE queries.
 * In case of SELECT query exception will be thrown.
 * For SELECT queries please use step:
 * <br><b>When I execute SQL query `$sqlQuery` against `$dbKey`
 * and save result to $scopes variable `$variableName`</b>
 * Actions performed in the step:
 * <ul>
 *     <li>executes provided SQL query against database by the provided key</li>
 *     <li>logs affected lines</li>
 * </ul>
 *
 * @param sqlQuery SQL query to execute
 * @param dbKey Key identifying the database connection
 */
@When("I execute SQL query `$sqlQuery` against `$dbKey`")
public void executeSql(String sqlQuery, String dbKey)
{
    try
    {
        LOGGER.info("Executed query: {}\nAffected rows:{}", sqlQuery, getJdbcTemplate(dbKey).update(sqlQuery));
    }
    catch (DataIntegrityViolationException e)
    {
        throw new IllegalStateException("Exception occured during query execution.\n"
            + "If you are trying execute SELECT query consider using step:"
            + "When I execute SQL query '$sqlQuery' and save the result to the $scopes variable '$variableName'",
            e);
    }
}
 
Example 4
Source Project: vividus   Source File: DatabaseStepsTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void shouldThrowIllegalStateExceptionInCaseOfDataIntegrityViolationException() throws SQLException
{
    DataIntegrityViolationException cause =
            new DataIntegrityViolationException("A result was returned when none was expected.");
    Statement stmt = mock(Statement.class);
    when(stmt.executeUpdate(QUERY)).thenThrow(cause);
    Connection con = mock(Connection.class);
    when(con.createStatement()).thenReturn(stmt);
    DriverManagerDataSource dataSource = mock(DriverManagerDataSource.class);
    when(dataSource.getConnection()).thenReturn(con);
    when(dataSources.get(DB_KEY)).thenReturn(dataSource);
    IllegalStateException actual = assertThrows(IllegalStateException.class,
        () -> databaseSteps.executeSql(QUERY, DB_KEY));
    assertEquals(cause, actual.getCause());
    assertEquals(actual.getMessage(), "Exception occured during query execution.\n"
            + "If you are trying execute SELECT query consider using step:"
            + "When I execute SQL query '$sqlQuery' and save the result to the $scopes variable '$variableName'");
}
 
Example 5
Source Project: oneops   Source File: CmRestController.java    License: Apache License 2.0 6 votes vote down vote up
@RequestMapping(method=RequestMethod.POST, value="/cm/simple/relations")
@ResponseBody
public CmsCIRelationSimple createCIRelation(
		@RequestParam(value="value", required = false)  String valueType, 
		@RequestBody CmsCIRelationSimple relSimple,
		@RequestHeader(value="X-Cms-Scope", required = false)  String scope,
		@RequestHeader(value="X-Cms-User", required = false)  String userId) throws CIValidationException {
	
	scopeVerifier.verifyScope(scope, relSimple);
	
	CmsCIRelation rel = cmsUtil.custCIRelationSimple2CIRelation(relSimple, valueType);
	rel.setCreatedBy(userId);
	try {
		CmsCIRelation newRel = cmManager.createRelation(rel);
		return cmsUtil.custCIRelation2CIRelationSimple(newRel, valueType,false);
	} catch (DataIntegrityViolationException dive) {
		if (dive instanceof DuplicateKeyException) {
			throw new CIValidationException(CmsError.CMS_DUPCI_NAME_ERROR, dive.getMessage());
		} else {
			throw new CmsException(CmsError.CMS_EXCEPTION, dive.getMessage());
		}
	}
}
 
Example 6
Source Project: cloudbreak   Source File: AccountTagService.java    License: Apache License 2.0 6 votes vote down vote up
public List<AccountTag> create(List<AccountTag> accountTags, String accountId) {
    try {
        accountTagRepository.arhiveAll(accountId);

        List<AccountTag> result = new ArrayList<>();
        for (AccountTag accountTag : accountTags) {
            accountTag.setAccountId(accountId);
            accountTag.setArchived(false);
            accountTag.setResourceCrn(createCRN(accountId));
            result.add(accountTagRepository.save(accountTag));
        }
        return result;
    } catch (DataIntegrityViolationException e) {
        throw new AccessDeniedException("Access denied", e);
    }
}
 
Example 7
Source Project: syndesis   Source File: TeiidOpenShiftClient.java    License: Apache License 2.0 6 votes vote down vote up
public void createDataSource(DefaultSyndesisDataSource scd) throws AdminException {
    String syndesisName = scd.getSyndesisName();
    debug(syndesisName, "Creating the Datasource of Type " + scd.getType());

    if (scd.getTeiidName() == null) {
        for (int i = 0; i < 3; i++) {
            try {
                String name = getUniqueTeiidName(scd, syndesisName);
                scd.setTeiidName(name);
                break;
            } catch (PersistenceException | DataIntegrityViolationException ignored) {
                //multiple pods are trying to assign a name simultaneously
                //if we try again, then we'll just pickup whatever someone else set
            }
        }
        if (scd.getTeiidName() == null) {
            throw new ResponseStatusException(HttpStatus.CONFLICT);
        }
    }

    //now that the name is set, we can create the properties
    this.metadata.registerDataSource(scd);
}
 
Example 8
@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());
}
 
Example 9
@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
		protected DataAccessException customTranslate(String task, 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());
}
 
Example 10
Source Project: cloudbreak   Source File: ClusterService.java    License: Apache License 2.0 6 votes vote down vote up
public Cluster saveWithRef(Cluster cluster) {
    Cluster savedCluster;
    try {
        long start = System.currentTimeMillis();
        if (cluster.getFileSystem() != null) {
            cluster.getFileSystem().setWorkspace(cluster.getWorkspace());
            fileSystemConfigService.pureSave(cluster.getFileSystem());
        }
        savedCluster = save(cluster);
        Gateway gateway = cluster.getGateway();
        if (gateway != null) {
            gateway.setCluster(savedCluster);
            gatewayService.save(gateway);
        }
        List<ClusterComponent> store = clusterComponentConfigProvider.store(cluster.getComponents(), savedCluster);
        savedCluster.setComponents(new HashSet<>(store));
        LOGGER.info("Cluster object saved in {} ms with cluster id {}", System.currentTimeMillis() - start, cluster.getId());
    } catch (DataIntegrityViolationException ex) {
        String msg = String.format("Error with resource [%s], %s", APIResourceType.CLUSTER, getProperSqlErrorMessage(ex));
        throw new BadRequestException(msg, ex);
    }
    return savedCluster;
}
 
Example 11
@Override
public Review createReview(Review body) {

    if (body.getProductId() < 1) throw new InvalidInputException("Invalid productId: " + body.getProductId());

    try {
        ReviewEntity entity = mapper.apiToEntity(body);
        ReviewEntity newEntity = repository.save(entity);

        LOG.debug("createReview: created a review entity: {}/{}", body.getProductId(), body.getReviewId());
        return mapper.entityToApi(newEntity);

    } catch (DataIntegrityViolationException dive) {
        throw new InvalidInputException("Duplicate key, Product Id: " + body.getProductId() + ", Review Id:" + body.getReviewId());
    }
}
 
Example 12
@Override
public Review createReview(Review body) {

    if (body.getProductId() < 1) throw new InvalidInputException("Invalid productId: " + body.getProductId());

    try {
        ReviewEntity entity = mapper.apiToEntity(body);
        ReviewEntity newEntity = repository.save(entity);

        LOG.debug("createReview: created a review entity: {}/{}", body.getProductId(), body.getReviewId());
        return mapper.entityToApi(newEntity);

    } catch (DataIntegrityViolationException dive) {
        throw new InvalidInputException("Duplicate key, Product Id: " + body.getProductId() + ", Review Id:" + body.getReviewId());
    }
}
 
Example 13
Source Project: cloudbreak   Source File: AccountTagService.java    License: Apache License 2.0 6 votes vote down vote up
public Map<String, String> generate(String accountId, EnvironmentDto environmentDto) {
    try {
        Map<String, String> accountTagsMap = accountTagRepository.findAllInAccount(accountId)
                .stream()
                .collect(Collectors.toMap(AccountTag::getTagKey, AccountTag::getTagValue));
        boolean internalTenant = entitlementService.internalTenant(environmentDto.getCreator(), accountId);

        CDPTagGenerationRequest request = CDPTagGenerationRequest.Builder.builder()
                .withCreatorCrn(environmentDto.getCreator())
                .withEnvironmentCrn(environmentDto.getResourceCrn())
                .withAccountId(environmentDto.getAccountId())
                .withPlatform(environmentDto.getCloudPlatform())
                .withResourceCrn(environmentDto.getResourceCrn())
                .withIsInternalTenant(internalTenant)
                .withUserName(getUserFromCrn(environmentDto.getCreator()))
                .withAccountTags(accountTagsMap)
                .build();
        return costTagging.generateAccountTags(request);
    } catch (DataIntegrityViolationException e) {
        throw new AccessDeniedException("Access denied", e);
    }
}
 
Example 14
@Override
public Review createReview(Review body) {

    if (body.getProductId() < 1) throw new InvalidInputException("Invalid productId: " + body.getProductId());

    try {
        ReviewEntity entity = mapper.apiToEntity(body);
        ReviewEntity newEntity = repository.save(entity);

        LOG.debug("createReview: created a review entity: {}/{}", body.getProductId(), body.getReviewId());
        return mapper.entityToApi(newEntity);

    } catch (DataIntegrityViolationException dive) {
        throw new InvalidInputException("Duplicate key, Product Id: " + body.getProductId() + ", Review Id:" + body.getReviewId());
    }
}
 
Example 15
@Override
public Review createReview(Review body) {

    if (body.getProductId() < 1) throw new InvalidInputException("Invalid productId: " + body.getProductId());

    try {
        ReviewEntity entity = mapper.apiToEntity(body);
        ReviewEntity newEntity = repository.save(entity);

        LOG.debug("createReview: created a review entity: {}/{}", body.getProductId(), body.getReviewId());
        return mapper.entityToApi(newEntity);

    } catch (DataIntegrityViolationException dive) {
        throw new InvalidInputException("Duplicate key, Product Id: " + body.getProductId() + ", Review Id:" + body.getReviewId());
    }
}
 
Example 16
/**
 * Updates a property.  The <b>alf_prop_root</b> entity is updated
 * to ensure concurrent modification is detected.
 * 
 * @return              Returns 1 always
 */
@Override
public int updateValue(Long key, Serializable value)
{
    // Remove all entries for the root
    PropertyRootEntity entity = getPropertyRoot(key);
    if (entity == null)
    {
        throw new DataIntegrityViolationException("No property root exists for ID " + key);
    }
    // Remove all links using the root
    deletePropertyLinks(key);
    // Create the new properties and update the cache
    createPropertyImpl(key, 0L, 0L, null, value);
    // Update the property root to detect concurrent modification
    updatePropertyRoot(entity);
    // Done
    if (logger.isDebugEnabled())
    {
        logger.debug(
                "Updated property: \n" +
                "   ID: " + key + "\n" +
                "   Value: " + value);
    }
    return 1;
}
 
Example 17
@Override
public Review createReview(Review body) {

    if (body.getProductId() < 1) throw new InvalidInputException("Invalid productId: " + body.getProductId());

    try {
        ReviewEntity entity = mapper.apiToEntity(body);
        ReviewEntity newEntity = repository.save(entity);

        LOG.debug("createReview: created a review entity: {}/{}", body.getProductId(), body.getReviewId());
        return mapper.entityToApi(newEntity);

    } catch (DataIntegrityViolationException dive) {
        throw new InvalidInputException("Duplicate key, Product Id: " + body.getProductId() + ", Review Id:" + body.getReviewId());
    }
}
 
Example 18
Source Project: apollo   Source File: NamespaceLockTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expected = ServiceException.class)
public void testDuplicateLock(){

  when(bizConfig.isNamespaceLockSwitchOff()).thenReturn(false);
  when(namespaceService.findOne(NAMESPACE_ID)).thenReturn(mockNamespace());
  when(namespaceLockService.findLock(NAMESPACE_ID)).thenReturn(null);
  when(namespaceLockService.tryLock(any())).thenThrow(DataIntegrityViolationException.class);

  namespaceLockAspect.acquireLock(NAMESPACE_ID, CURRENT_USER);

  verify(bizConfig).isNamespaceLockSwitchOff();
  verify(namespaceService).findOne(NAMESPACE_ID);
  verify(namespaceLockService, times(2)).findLock(NAMESPACE_ID);
  verify(namespaceLockService).tryLock(any());

}
 
Example 19
Source Project: OpenCue   Source File: AllocationDaoJdbc.java    License: Apache License 2.0 6 votes vote down vote up
public void deleteAllocation(AllocationInterface a) {
    if (getJdbcTemplate().queryForObject(
            "SELECT COUNT(1) FROM host WHERE pk_alloc=?", Integer.class,
            a.getAllocationId()) > 0) {
        throw new EntityRemovalError("allocation still contains hosts", a);
    }

    if (getJdbcTemplate().queryForObject(
            "SELECT b_default FROM alloc WHERE pk_alloc=?", Integer.class,
            a.getAllocationId()) > 0) {
        throw new EntityRemovalError("you cannot delete the default allocation", a);
    }

    /*
     * Allocations are logged in historical data so once they are used you
     * can't specifically delete them. They are disabled instead.
     */
    try {
        getJdbcTemplate().update("DELETE FROM alloc WHERE pk_alloc=?",
                a.getAllocationId());
    } catch (DataIntegrityViolationException e) {
        getJdbcTemplate().update("UPDATE alloc SET b_enabled = 0 WHERe pk_alloc = ?",
                a.getAllocationId());
    }
}
 
Example 20
Source Project: jeecg   Source File: TsBlackListController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 更新黑名单
 * 
 * @param ids
 * @return
 */
@RequestMapping(params = "doUpdate")
@ResponseBody
public AjaxJson doUpdate(TsBlackListEntity tsBlackList, HttpServletRequest request) {
	String message = null;
	AjaxJson j = new AjaxJson();
	message = "黑名单更新成功";
	TsBlackListEntity t = tsBlackListService.get(TsBlackListEntity.class, tsBlackList.getId());
	try {
		MyBeanUtils.copyBeanNotNull2Bean(tsBlackList, t);
		tsBlackListService.saveOrUpdate(t);
		systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);

	} catch(DataIntegrityViolationException ce){
		j.setSuccess(false);
		message = "该IP:"+tsBlackList.getIp()+"已存在!";

	}catch (Exception e) {
		e.printStackTrace();
		message = "黑名单更新失败";
		throw new BusinessException(e.getMessage());
	}
	j.setMsg(message);
	return j;
}
 
Example 21
Source Project: sdn-rx   Source File: ExceptionTranslationIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void exceptionsFromClientShouldBeTranslated(@Autowired Neo4jClient neo4jClient) {
	neo4jClient.query("CREATE (:SimplePerson {name: 'Tom'})").run();

	assertThatExceptionOfType(DataIntegrityViolationException.class)
		.isThrownBy(() -> neo4jClient.query("CREATE (:SimplePerson {name: 'Tom'})").run())
		.withMessageMatching(
			"Node\\(\\d+\\) already exists with label `SimplePerson` and property `name` = '[\\w\\s]+'; Error code 'Neo.ClientError.Schema.ConstraintValidationFailed'");
}
 
Example 22
Source Project: sdn-rx   Source File: ExceptionTranslationIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void exceptionsFromRepositoriesShouldBeTranslated(@Autowired SimplePersonRepository repository) {
	repository.save(new SimplePerson("Jerry"));

	assertThatExceptionOfType(DataIntegrityViolationException.class)
		.isThrownBy(() -> repository.save(new SimplePerson("Jerry")))
		.withMessageMatching(
			"Node\\(\\d+\\) already exists with label `SimplePerson` and property `name` = '[\\w\\s]+'; Error code 'Neo.ClientError.Schema.ConstraintValidationFailed'");
}
 
Example 23
Source Project: sdn-rx   Source File: ExceptionTranslationIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void exceptionsOnRepositoryBeansShouldBeTranslated(@Autowired CustomDAO customDAO) {
	ResultSummary summary = customDAO.createPerson();
	assertThat(summary.counters().nodesCreated()).isEqualTo(1L);

	assertThatExceptionOfType(DataIntegrityViolationException.class)
		.isThrownBy(() -> customDAO.createPerson())
		.withMessageMatching(
			"Node\\(\\d+\\) already exists with label `SimplePerson` and property `name` = '[\\w\\s]+'; Error code 'Neo.ClientError.Schema.ConstraintValidationFailed'");
}
 
Example 24
public void testErrorCodeTranslation() {
	SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES);

	SQLException badSqlEx = new SQLException("", "", 1);
	BadSqlGrammarException bsgex = (BadSqlGrammarException) sext.translate("task", "SQL", badSqlEx);
	assertEquals("SQL", bsgex.getSql());
	assertEquals(badSqlEx, bsgex.getSQLException());

	SQLException invResEx = new SQLException("", "", 4);
	InvalidResultSetAccessException irsex = (InvalidResultSetAccessException) sext.translate("task", "SQL", invResEx);
	assertEquals("SQL", irsex.getSql());
	assertEquals(invResEx, irsex.getSQLException());

	checkTranslation(sext, 5, DataAccessResourceFailureException.class);
	checkTranslation(sext, 6, DataIntegrityViolationException.class);
	checkTranslation(sext, 7, CannotAcquireLockException.class);
	checkTranslation(sext, 8, DeadlockLoserDataAccessException.class);
	checkTranslation(sext, 9, CannotSerializeTransactionException.class);
	checkTranslation(sext, 10, DuplicateKeyException.class);

	SQLException dupKeyEx = new SQLException("", "", 10);
	DataAccessException dksex = sext.translate("task", "SQL", dupKeyEx);
	assertTrue("Not instance of DataIntegrityViolationException",
			DataIntegrityViolationException.class.isAssignableFrom(dksex.getClass()));

	// Test fallback. We assume that no database will ever return this error code,
	// but 07xxx will be bad grammar picked up by the fallback SQLState translator
	SQLException sex = new SQLException("", "07xxx", 666666666);
	BadSqlGrammarException bsgex2 = (BadSqlGrammarException) sext.translate("task", "SQL2", sex);
	assertEquals("SQL2", bsgex2.getSql());
	assertEquals(sex, bsgex2.getSQLException());
}
 
Example 25
public void saveTemplate(EmailTemplate template) {
 //check that fields are set
 if (template == null) {
  throw new IllegalArgumentException("Template can't be null");
 }
 
 if (template.getKey() == null) {
  throw new IllegalArgumentException("Template key can't be null");
 }
 
 if (template.getOwner() == null) {
  throw new IllegalArgumentException("Template owner can't be null");
 }
 
 if (template.getSubject() == null) {
  throw new IllegalArgumentException("Template subject can't be null");
 }
 
 if (template.getMessage() == null) {
  throw new IllegalArgumentException("Template message can't be null");
 }
 
 String locale = template.getLocale(); 
 if (StringUtils.isBlank(locale)) {
  //For backward compatibility set it to default
  template.setLocale(EmailTemplate.DEFAULT_LOCALE);
 } 
 
   //update the modified date
   template.setLastModified(new Date());
   try {
 	  dao.save(template);
   }
   catch (DataIntegrityViolationException die) {
 	  throw new IllegalArgumentException("Key: " + template.getKey() + " and locale: " + template.getLocale() + " in use already", die);
   }
   log.info("saved template: " + template.getId());
}
 
Example 26
@Test
public void errorCodeTranslation() {
	SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES);

	SQLException badSqlEx = new SQLException("", "", 1);
	BadSqlGrammarException bsgex = (BadSqlGrammarException) sext.translate("task", "SQL", badSqlEx);
	assertEquals("SQL", bsgex.getSql());
	assertEquals(badSqlEx, bsgex.getSQLException());

	SQLException invResEx = new SQLException("", "", 4);
	InvalidResultSetAccessException irsex = (InvalidResultSetAccessException) sext.translate("task", "SQL", invResEx);
	assertEquals("SQL", irsex.getSql());
	assertEquals(invResEx, irsex.getSQLException());

	checkTranslation(sext, 5, DataAccessResourceFailureException.class);
	checkTranslation(sext, 6, DataIntegrityViolationException.class);
	checkTranslation(sext, 7, CannotAcquireLockException.class);
	checkTranslation(sext, 8, DeadlockLoserDataAccessException.class);
	checkTranslation(sext, 9, CannotSerializeTransactionException.class);
	checkTranslation(sext, 10, DuplicateKeyException.class);

	SQLException dupKeyEx = new SQLException("", "", 10);
	DataAccessException dksex = sext.translate("task", "SQL", dupKeyEx);
	assertTrue("Not instance of DataIntegrityViolationException",
			DataIntegrityViolationException.class.isAssignableFrom(dksex.getClass()));

	// Test fallback. We assume that no database will ever return this error code,
	// but 07xxx will be bad grammar picked up by the fallback SQLState translator
	SQLException sex = new SQLException("", "07xxx", 666666666);
	BadSqlGrammarException bsgex2 = (BadSqlGrammarException) sext.translate("task", "SQL2", sex);
	assertEquals("SQL2", bsgex2.getSql());
	assertEquals(sex, bsgex2.getSQLException());
}
 
Example 27
Source Project: cloudbreak   Source File: SqlUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static String getProperSqlErrorMessage(DataIntegrityViolationException dive) {
    Throwable cause = dive.getMostSpecificCause();
    if (cause instanceof PSQLException) {
        PSQLException ex = (PSQLException) cause;
        MessageCleaner messageCleaner = MessageCleaner.fromSqlState(ex.getSQLState());
        return messageCleaner.clean(ex.getLocalizedMessage());
    }
    return cause.getLocalizedMessage();
}
 
Example 28
Source Project: SO   Source File: SessionDao.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void createSessionDataLocation(SessionEntity sessionEntity) {
	try {
        super.sqlSession.insert("createSessionDataLocation", sessionEntity);
	} catch(DataIntegrityViolationException e) {
		log.error("createSessionDataLocation: error={}", e.getMessage());
	}
}
 
Example 29
@Test(expected = DataIntegrityViolationException.class)
public void testFailOnMaxAttemptsExceeded() {
    when(mockLifecycleRepository.save(any(LifecycleEntity.class))).thenThrow(new DataIntegrityViolationException("constraint violation"));

    try {
        service.saveLifecycle(application, version, lifecycle);
    } finally {
        verify(mockApplicationRepository, times(10)).findByName(eq("foobar"));
        verify(mockVersionRepository, times(10)).findByName(eq("1.0"));

        verify(mockLifecycleRepository, times(10)).save(any(LifecycleEntity.class));
    }
}
 
Example 30
@Override
@Nullable
protected DataAccessException doTranslate(String task, @Nullable String sql, SQLException ex) {
	// First, the getSQLState check...
	String sqlState = getSqlState(ex);
	if (sqlState != null && sqlState.length() >= 2) {
		String classCode = sqlState.substring(0, 2);
		if (logger.isDebugEnabled()) {
			logger.debug("Extracted SQL state class '" + classCode + "' from value '" + sqlState + "'");
		}
		if (BAD_SQL_GRAMMAR_CODES.contains(classCode)) {
			return new BadSqlGrammarException(task, (sql != null ? sql : ""), ex);
		}
		else if (DATA_INTEGRITY_VIOLATION_CODES.contains(classCode)) {
			return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex);
		}
		else if (DATA_ACCESS_RESOURCE_FAILURE_CODES.contains(classCode)) {
			return new DataAccessResourceFailureException(buildMessage(task, sql, ex), ex);
		}
		else if (TRANSIENT_DATA_ACCESS_RESOURCE_CODES.contains(classCode)) {
			return new TransientDataAccessResourceException(buildMessage(task, sql, ex), ex);
		}
		else if (CONCURRENCY_FAILURE_CODES.contains(classCode)) {
			return new ConcurrencyFailureException(buildMessage(task, sql, ex), ex);
		}
	}

	// For MySQL: exception class name indicating a timeout?
	// (since MySQL doesn't throw the JDBC 4 SQLTimeoutException)
	if (ex.getClass().getName().contains("Timeout")) {
		return new QueryTimeoutException(buildMessage(task, sql, ex), ex);
	}

	// Couldn't resolve anything proper - resort to UncategorizedSQLException.
	return null;
}