Example usage for org.springframework.dao DataIntegrityViolationException DataIntegrityViolationException

List of usage examples for org.springframework.dao DataIntegrityViolationException DataIntegrityViolationException

Introduction

In this page you can find the example usage for org.springframework.dao DataIntegrityViolationException DataIntegrityViolationException.

Prototype

public DataIntegrityViolationException(String msg) 

Source Link

Document

Constructor for DataIntegrityViolationException.

Usage

From source file:org.cloudfoundry.identity.uaa.oauth.token.UaaTokenStore.java

@Override
public String createAuthorizationCode(OAuth2Authentication authentication) {
    final int max_tries = 3;
    performExpirationClean();/* w w w  .  j  ava 2 s  .c o  m*/
    JdbcTemplate template = new JdbcTemplate(dataSource);
    int tries = 0;
    while ((tries++) <= max_tries) {
        try {
            String code = generator.generate();
            long expiresAt = System.currentTimeMillis() + getExpirationTime();
            String userId = authentication.getUserAuthentication() == null ? null
                    : ((UaaPrincipal) authentication.getUserAuthentication().getPrincipal()).getId();
            String clientId = authentication.getOAuth2Request().getClientId();
            SqlLobValue data = new SqlLobValue(serializeOauth2Authentication(authentication));
            int updated = template.update(SQL_INSERT_STATEMENT,
                    new Object[] { code, userId, clientId, expiresAt, data },
                    new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.NUMERIC, Types.BLOB });
            if (updated == 0) {
                throw new DataIntegrityViolationException("[oauth_code] Failed to insert code. Result was 0");
            }
            return code;
        } catch (DataIntegrityViolationException exists) {
            if (tries >= max_tries)
                throw exists;
        }
    }
    return null;
}

From source file:org.cloudfoundry.identity.uaa.provider.JdbcIdentityProviderProvisioning.java

protected void validate(IdentityProvider provider) {
    if (provider == null) {
        throw new NullPointerException("Provider can not be null.");
    }//  w w w.ja  v  a 2 s.  c  o m
    if (!StringUtils.hasText(provider.getIdentityZoneId())) {
        throw new DataIntegrityViolationException("Identity zone ID must be set.");
    }
    //ensure that SAML IDPs have reduntant fields synchronized
    if (OriginKeys.SAML.equals(provider.getType()) && provider.getConfig() != null) {
        SamlIdentityProviderDefinition saml = ObjectUtils.castInstance(provider.getConfig(),
                SamlIdentityProviderDefinition.class);
        saml.setIdpEntityAlias(provider.getOriginKey());
        saml.setZoneId(provider.getIdentityZoneId());
        provider.setConfig(saml);
    }
}

From source file:org.cloudfoundry.identity.uaa.provider.saml.idp.JdbcSamlServiceProviderProvisioning.java

protected void validate(SamlServiceProvider provider) {
    if (provider == null) {
        throw new NullPointerException("SAML Service Provider can not be null.");
    }/*from  w  ww  .  j  av  a2s  .c om*/
    if (!StringUtils.hasText(provider.getIdentityZoneId())) {
        throw new DataIntegrityViolationException("Identity zone ID must be set.");
    }
}

From source file:org.cloudfoundry.identity.uaa.scim.endpoints.ScimGroupEndpointsTests.java

@Test
public void testExceptionHandler() {
    Map<Class<? extends Exception>, HttpStatus> map = new HashMap<Class<? extends Exception>, HttpStatus>();
    map.put(IllegalArgumentException.class, HttpStatus.BAD_REQUEST);
    map.put(UnsupportedOperationException.class, HttpStatus.BAD_REQUEST);
    map.put(BadSqlGrammarException.class, HttpStatus.BAD_REQUEST);
    map.put(DataIntegrityViolationException.class, HttpStatus.BAD_REQUEST);
    map.put(HttpMessageConversionException.class, HttpStatus.BAD_REQUEST);
    map.put(HttpMediaTypeException.class, HttpStatus.BAD_REQUEST);
    endpoints.setStatuses(map);/* w  w  w  .  java  2s  . com*/
    endpoints.setMessageConverters(new HttpMessageConverter<?>[] { new ExceptionReportHttpMessageConverter() });

    MockHttpServletRequest request = new MockHttpServletRequest();
    validateView(endpoints.handleException(new ScimResourceNotFoundException(""), request),
            HttpStatus.NOT_FOUND);
    validateView(endpoints.handleException(new UnsupportedOperationException(""), request),
            HttpStatus.BAD_REQUEST);
    validateView(endpoints.handleException(new BadSqlGrammarException("", "", null), request),
            HttpStatus.BAD_REQUEST);
    validateView(endpoints.handleException(new IllegalArgumentException(""), request), HttpStatus.BAD_REQUEST);
    validateView(endpoints.handleException(new DataIntegrityViolationException(""), request),
            HttpStatus.BAD_REQUEST);
}

From source file:org.craftercms.social.services.impl.UGCServiceImpl.java

@Override
public UGC updateModerationStatus(ObjectId uGCId, ModerationStatus newStatus, String tenant, String profileId) {
    if (existsUGC(uGCId)) {
        UGC ugc = uGCRepository.findOne(uGCId);
        ugc.setModerationStatus(newStatus);
        ugc.setLastModifiedDate(new Date());
        //Audit call
        auditUGC(uGCId, AuditAction.MODERATE, tenant, profileId, null);
        return populateUGCWithProfile(save(ugc));
    } else {/*w w w .  j av a2 s. co m*/
        log.error("UGC {} does not exist", uGCId);
        throw new DataIntegrityViolationException("Parent UGC does not exist");
    }
}

From source file:org.craftercms.social.services.impl.UGCServiceImpl.java

@Override
public UGC newChildUgc(UGC ugc) throws PermissionDeniedException, AttachmentErrorException {

    if (!existsUGC(ugc.getParentId())) {
        log.error("Parent for {} does not exist", ugc);
        throw new DataIntegrityViolationException("Parent UGC does not exist");
    }//from  www . ja  v  a  2s  .c  o  m

    // attachments = scanFilesForVirus(ugc.getAttachmentsList());

    //ugc.setAnonymousFlag(ugc.isAnonymousFlag());
    // resolve and set the actions
    ugc.setActions(resolveUGCActions(ugc.getActions(), ugc.getParentId()));
    ugc.setModerationStatus(ModerationStatus.UNMODERATED);
    ugc.setCreatedDate(new Date());
    ugc.setLastModifiedDate(new Date());
    checkForModeration(ugc);

    //ugc.setAttachmentId(saveUGCAttachments(files));
    UGC ugcWithProfile = populateUGCWithProfile(save(ugc));
    ugcWithProfile.setAttachmentsList(
            getAttachmentsList(ugcWithProfile.getAttachmentId(), ugcWithProfile.getTenant()));
    //Audit call
    auditUGC(ugcWithProfile.getId(), AuditAction.CREATE, ugc.getTenant(), ugc.getProfileId(), null);
    return ugcWithProfile;
}

From source file:org.craftercms.social.services.impl.UGCServiceImpl.java

@Override
public UGC likeUGC(ObjectId ugcId, String tenant, String profileId) {
    if (existsUGC(ugcId)) {
        UGC ugc = uGCRepository.findOne(ugcId);
        if (userCan(AuditAction.LIKE, ugc, profileId)) {
            ugc.setLikeCount(ugc.getLikeCount() + 1);
            auditUGC(ugcId, AuditAction.LIKE, tenant, profileId, null);
            checkForModeration(ugc);/*ww w  .j  av a2  s .  c o m*/
            if (!userCan(AuditAction.DISLIKE, ugc, profileId)) {
                ugc.setOffenceCount(ugc.getOffenceCount() - 1);
                removeAuditUGC(ugcId, AuditAction.DISLIKE, tenant, profileId, null);
            }
            return populateUGCWithProfile(save(ugc));
        } else {
            ugc.setLikeCount(ugc.getLikeCount() - 1);
            removeAuditUGC(ugcId, AuditAction.LIKE, tenant, profileId, null);
            return populateUGCWithProfile(save(ugc));
        }
    } else {
        log.debug("UGC Id {} does not exist", ugcId);
        throw new DataIntegrityViolationException("UGC does not exist");
    }
}

From source file:org.craftercms.social.services.impl.UGCServiceImpl.java

@Override
public UGC dislikeUGC(ObjectId ugcId, String tenant, String profileId) {
    if (existsUGC(ugcId)) {
        UGC ugc = uGCRepository.findOne(ugcId);
        if (userCan(AuditAction.DISLIKE, ugc, profileId)) {
            ugc.setOffenceCount(ugc.getOffenceCount() + 1);
            auditUGC(ugcId, AuditAction.DISLIKE, tenant, profileId, null);
            checkForModeration(ugc);// www.j ava2 s.c om
            if (!userCan(AuditAction.LIKE, ugc, profileId)) {
                ugc.setLikeCount(ugc.getLikeCount() - 1);
                removeAuditUGC(ugcId, AuditAction.LIKE, tenant, profileId, null);
            }
            return populateUGCWithProfile(save(ugc));
        } else {
            ugc.setOffenceCount(ugc.getOffenceCount() - 1);
            removeAuditUGC(ugcId, AuditAction.DISLIKE, tenant, profileId, null);
            return populateUGCWithProfile(save(ugc));
        }
    } else {
        log.debug("UGC Id {} does not exist", ugcId);
        throw new DataIntegrityViolationException("UGC does not exist");
    }
}

From source file:org.openlmis.core.upload.AbstractModelPersistenceHandlerTest.java

@Test
public void shouldThrowIncorrectDataLengthError() throws Exception {
    handler = new AbstractModelPersistenceHandler() {
        @Override//from  ww  w  .j  a  v  a2  s . co m
        protected BaseModel getExisting(BaseModel record) {
            return null;
        }

        @Override
        protected void save(BaseModel record) {
            throw new DataIntegrityViolationException("some error");
        }

    };

    handler.messageService = messageService;
    when(messageService.message("error.incorrect.length")).thenReturn("invalid data length");
    when(messageService.message("upload.record.error", "invalid data length", "1"))
            .thenReturn("final error message");

    expectedEx.expect(DataException.class);
    expectedEx.expectMessage("final error message");

    handler.execute(new TestImportable(), 2, new AuditFields(null));
}

From source file:org.springframework.data.document.mongodb.MongoTemplate.java

/**
 * Checks and handles any errors.//from  w w w .j  a  v a2s .  com
 * <p/>
 * TODO: current implementation logs errors - will be configurable to log warning, errors or
 * throw exception in later versions
 */
private void handleAnyWriteResultErrors(WriteResult wr, DBObject query, String operation) {
    if (WriteResultChecking.NONE == this.writeResultChecking) {
        return;
    }
    String error = wr.getError();
    int n = wr.getN();
    if (error != null) {
        String message = "Execution of '" + operation
                + (query == null ? "" : "' using '" + query.toString() + "' query") + " failed: " + error;
        if (WriteResultChecking.EXCEPTION == this.writeResultChecking) {
            throw new DataIntegrityViolationException(message);
        } else {
            LOGGER.error(message);
        }
    } else if (n == 0) {
        String message = "Execution of '" + operation
                + (query == null ? "" : "' using '" + query.toString() + "' query")
                + " did not succeed: 0 documents updated";
        if (WriteResultChecking.EXCEPTION == this.writeResultChecking) {
            throw new DataIntegrityViolationException(message);
        } else {
            LOGGER.warn(message);
        }
    }

}