org.springframework.dao.DataIntegrityViolationException Java Examples

The following examples show how to use org.springframework.dao.DataIntegrityViolationException. 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: ReviewServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 6 votes vote down vote up
@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 #2
Source File: CmRestController.java    From oneops with 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 #3
Source File: HibernateInterceptorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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: TsBlackListController.java    From jeecg with 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 #5
Source File: DatabaseStepsTests.java    From vividus with 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 #6
Source File: AccountTagService.java    From cloudbreak with 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 File: DatabaseSteps.java    From vividus with 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 #8
Source File: CourseManagementAdministrationHibernateImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
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 #9
Source File: AllocationDaoJdbc.java    From OpenCue with 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 #10
Source File: NamespaceLockTest.java    From apollo with 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 #11
Source File: ReviewServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 6 votes vote down vote up
@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
Source File: TeiidOpenShiftClient.java    From syndesis with 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 #13
Source File: AbstractPropertyValueDAOImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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 #14
Source File: SQLErrorCodeSQLExceptionTranslatorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #15
Source File: SQLErrorCodeSQLExceptionTranslatorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #16
Source File: ReviewServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 6 votes vote down vote up
@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 #17
Source File: ClusterService.java    From cloudbreak with 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 #18
Source File: ReviewServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 6 votes vote down vote up
@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 #19
Source File: ReviewServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 6 votes vote down vote up
@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 #20
Source File: AccountTagService.java    From cloudbreak with 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 #21
Source File: SQLErrorCodeSQLExceptionTranslatorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #22
Source File: SQLErrorCodeSQLExceptionTranslatorTests.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
public void testCustomExceptionTranslation() {
	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
	try {
		customTranslation.setExceptionClass(String.class);
		fail("Should have thrown IllegalArgumentException");
	}
	catch (IllegalArgumentException ex) {
		// expected
	}
}
 
Example #23
Source File: ModelValidatorImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void validateDeleteProperty(final String tenantDomain, final PropertyDefinition propDef)
{
    final QName propName = propDef.getName();

    // We need a separate transaction to do the qname delete "check"
    transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>()
    {
        @Override
        public Void execute() throws Throwable
        {
            return TenantUtil.runAsTenant(new TenantRunAsWork<Void>()
            {
                @Override
                public Void doWork() throws Exception
                {
                    try
                    {
                        // The property QName may not have been created in the database if no
                        // properties have been created that use it, so check first and then
                        // try to delete it.
                        if(qnameDAO.getQName(propName) != null)
                        {
                            qnameDAO.deleteQName(propName);
                        }
                    }
                    catch(DataIntegrityViolationException e)
                    {
                        // catch data integrity violation e.g. foreign key constraint exception
                        logger.debug(e);
                        throw new ModelInUseException("Failed to validate property delete, property " + propName + " is in use");
                    }

                    return null;
                }
            }, tenantDomain);
        }
    }, false, true);
}
 
Example #24
Source File: AbstractContentDataDAOImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Pair<Long, ContentData> getContentData(Long id)
{
    if (id == null)
    {
        throw new IllegalArgumentException("Cannot look up ContentData by null ID.");
    }
    Pair<Long, ContentData> entityPair = contentDataCache.getByKey(id);
    if (entityPair == null)
    {
        throw new DataIntegrityViolationException("No ContentData value exists for ID " + id);
    }
    return entityPair;
}
 
Example #25
Source File: H2LogSourceProvider.java    From logsniffer with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void deleteSource(final LogSource<? extends LogRawAccess<? extends LogInputStream>> source)
		throws ReferenceIntegrityException {
	try {
		jdbcTemplate.update("DELETE FROM LOG_SOURCES WHERE ID=?", source.getId());
		logger.info("Deleted source with id: {}", source.getId());
	} catch (final DataIntegrityViolationException e) {
		logger.info("Deleting source with id {} failed due to references", source.getId());
		throw new ReferenceIntegrityException(LogSource.class, e);
	}
}
 
Example #26
Source File: AbstractQNameDAOImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Pair<Long, QName> getQName(Long id)
{
    if (id == null)
    {
        throw new IllegalArgumentException("Cannot look up entity by null ID.");
    }
    Pair<Long, QName> entityPair = qnameCache.getByKey(id);
    if (entityPair == null)
    {
        throw new DataIntegrityViolationException("No qname exists for ID " + id);
    }
    return entityPair;
}
 
Example #27
Source File: RestExceptionHandler.java    From spring-boot-exception-handling with MIT License 5 votes vote down vote up
/**
 * Handle DataIntegrityViolationException, inspects the cause for different DB causes.
 *
 * @param ex the DataIntegrityViolationException
 * @return the ApiError 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 #28
Source File: GeneratorIdentityService.java    From jhipster-online with Apache License 2.0 5 votes vote down vote up
/**
 * Try to create a new GeneratorIdentity.
 *
 * @param guid The guid of the new GeneratorIdentity.
 */
@Transactional(propagation = Propagation.REQUIRES_NEW, timeout = 5)
public void tryToCreateGeneratorIdentity(String guid) {
    Optional<GeneratorIdentity> generatorIdentity = generatorIdentityRepository.findFirstByGuidEquals(guid);
    if (!generatorIdentity.isPresent()) {
        // Try to create the GeneratorIdentity in a separate transaction, to manage concurrent access issues
        try {
            save(new GeneratorIdentity().guid(guid));;
        } catch (DataIntegrityViolationException dve) {
            log.info("Could not create GeneratorIdentity {} - it was already created", guid);
        }
    }
}
 
Example #29
Source File: EmailTemplateServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
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 #30
Source File: AbstractQNameDAOImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Pair<Long, String> getNamespace(Long id)
{
    if (id == null)
    {
        throw new IllegalArgumentException("Cannot look up entity by null ID.");
    }
    Pair<Long, String> entityPair = namespaceCache.getByKey(id);
    if (entityPair == null)
    {
        throw new DataIntegrityViolationException("No namespace exists for ID " + id);
    }
    return entityPair;
}