Example usage for org.springframework.dao DataIntegrityViolationException getMostSpecificCause

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

Introduction

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

Prototype

public Throwable getMostSpecificCause() 

Source Link

Document

Retrieve the most specific cause of this exception, that is, either the innermost cause (root cause) or this exception itself.

Usage

From source file:edu.isi.misd.scanner.network.registry.web.controller.UserRoleController.java

@RequestMapping(value = ENTITY_PATH, method = RequestMethod.PUT, consumes = HEADER_JSON_MEDIA_TYPE, produces = HEADER_JSON_MEDIA_TYPE)
public @ResponseBody UserRole updateUserRole(@RequestHeader(HEADER_LOGIN_NAME) String loginName,
        @PathVariable(ID_URL_PATH_VAR) Integer id, @RequestBody UserRole userRole) {
    // find the requested resource
    UserRole foundUserRole = userRoleRepository.findOne(id);
    // if the ID is not found then throw a ResourceNotFoundException (404)
    if (foundUserRole == null) {
        throw new ResourceNotFoundException(id);
    }/*from   ww w .j  a va2s . c o  m*/
    // if the ID in the request body is null, use the ID parsed from the URL
    // if the ID is found in the request body but does not match the ID in 
    // the current data, then throw a ConflictException (409)
    Integer updateID = userRole.getUserRoleId();
    if (updateID == null) {
        userRole.setUserRoleId(id);
    } else if (!userRole.getUserRoleId().equals(foundUserRole.getUserRoleId())) {
        throw new ConflictException(userRole.getUserRoleId(), foundUserRole.getUserRoleId());
    }

    // check that the user can perform the update
    if (!registryService.userCanManageStudy(loginName, userRole.getStudyRole().getStudy().getStudyId())) {
        throw new ForbiddenException(loginName, RegistryServiceConstants.MSG_STUDY_MANAGEMENT_ROLE_REQUIRED);
    }
    try {
        userRoleRepository.save(userRole);
    } catch (DataIntegrityViolationException e) {
        log.warn(e);
        throw new ConflictException(e.getMostSpecificCause());
    }
    // force the re-query to ensure a complete result view if updated
    return userRoleRepository.findOne(userRole.getUserRoleId());
}

From source file:org.apache.fineract.infrastructure.codes.service.CodeWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*  www  .  j a v  a  2  s  .c o  m*/
@CacheEvict(value = "codes", key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat('cv')")
public CommandProcessingResult createCode(final JsonCommand command) {

    try {
        this.context.authenticatedUser();

        this.fromApiJsonDeserializer.validateForCreate(command.json());

        final Code code = Code.fromJson(command);
        this.codeRepository.save(code);

        return new CommandProcessingResultBuilder().withCommandId(command.commandId())
                .withEntityId(code.getId()).build();
    } catch (final DataIntegrityViolationException dve) {
        handleCodeDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException ee) {
        Throwable throwable = ExceptionUtils.getRootCause(ee.getCause());
        handleCodeDataIntegrityIssues(command, throwable, ee);
        return CommandProcessingResult.empty();
    }
}

From source file:org.apache.fineract.infrastructure.codes.service.CodeWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*from w  w  w .  j a va 2  s . co  m*/
@CacheEvict(value = "codes", key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat('cv')")
public CommandProcessingResult updateCode(final Long codeId, final JsonCommand command) {

    try {
        this.context.authenticatedUser();

        this.fromApiJsonDeserializer.validateForUpdate(command.json());

        final Code code = retrieveCodeBy(codeId);
        final Map<String, Object> changes = code.update(command);

        if (!changes.isEmpty()) {
            this.codeRepository.save(code);
        }

        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withEntityId(codeId) //
                .with(changes) //
                .build();
    } catch (final DataIntegrityViolationException dve) {
        handleCodeDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException ee) {
        Throwable throwable = ExceptionUtils.getRootCause(ee.getCause());
        handleCodeDataIntegrityIssues(command, throwable, ee);
        return CommandProcessingResult.empty();
    }
}

From source file:org.apache.fineract.infrastructure.codes.service.CodeWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override//w ww.  ja v a  2  s  .co  m
@CacheEvict(value = "codes", key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat('cv')")
public CommandProcessingResult deleteCode(final Long codeId) {

    this.context.authenticatedUser();

    final Code code = retrieveCodeBy(codeId);
    if (code.isSystemDefined()) {
        throw new SystemDefinedCodeCannotBeChangedException();
    }

    try {
        this.codeRepository.delete(code);
        this.codeRepository.flush();
    } catch (final DataIntegrityViolationException e) {
        throw new PlatformDataIntegrityException("error.msg.cund.unknown.data.integrity.issue",
                "Unknown data integrity issue with resource: " + e.getMostSpecificCause());
    }
    return new CommandProcessingResultBuilder().withEntityId(codeId).build();
}

From source file:org.apache.fineract.infrastructure.dataexport.service.DataExportWritePlatformServiceImpl.java

/** 
 * Handle any SQL data integrity issue /*from   ww  w  .j  a v  a  2  s  .  com*/
 *
 * @param jsonCommand -- JsonCommand object
 * @param dve -- data integrity exception object
 * @return None
 **/
private void handleDataIntegrityIssues(final JsonCommand jsonCommand,
        final DataIntegrityViolationException dve) {
    final Throwable realCause = dve.getMostSpecificCause();

    if (realCause.getMessage().contains(DataExportApiConstants.NAME_PARAM_NAME)) {
        final String name = jsonCommand.stringValueOfParameterNamed(DataExportApiConstants.NAME_PARAM_NAME);
        throw new PlatformDataIntegrityException("error.msg.data.export.duplicate.name",
                "Data export with name `" + name + "` already exists", DataExportApiConstants.NAME_PARAM_NAME,
                name);
    }

    logger.error(dve.getMessage(), dve);

    throw new PlatformDataIntegrityException("error.msg.charge.unknown.data.integrity.issue",
            "Unknown data integrity issue with resource: " + realCause.getMessage());
}

From source file:org.apache.fineract.infrastructure.dataqueries.service.ReadWriteNonCoreDataServiceImpl.java

@Transactional
private void _registerDataTable(final String applicationTableName, final String dataTableName,
        final Integer category, final String permissionsSql) {

    validateAppTable(applicationTableName);
    assertDataTableExists(dataTableName);

    final String registerDatatableSql = "insert into x_registered_table (registered_table_name, application_table_name,category) values ('"
            + dataTableName + "', '" + applicationTableName + "', '" + category + "')";

    try {/*from www . ja va 2  s .c om*/

        final String[] sqlArray = { registerDatatableSql, permissionsSql };
        this.jdbcTemplate.batchUpdate(sqlArray);

        // add the registered table to the config if it is a ppi
        if (this.isSurveyCategory(category)) {
            this.jdbcTemplate.execute("insert into c_configuration (name, value, enabled ) values('"
                    + dataTableName + "', '0','0')");
        }

    }
    /***
     * Strangely, a Hibernate contraint violation exception is thrown
     ****/
    catch (final ConstraintViolationException cve) {
        final Throwable realCause = cve.getCause();
        // even if duplicate is only due to permission duplicate, okay to
        // show duplicate datatable error msg
        if (realCause.getMessage().contains("Duplicate entry")) {
            throw new PlatformDataIntegrityException("error.msg.datatable.registered",
                    "Datatable `" + dataTableName + "` is already registered against an application table.",
                    "dataTableName", dataTableName);
        }
    } catch (final DataIntegrityViolationException dve) {
        final Throwable realCause = dve.getMostSpecificCause();
        // even if duplicate is only due to permission duplicate, okay to
        // show duplicate datatable error msg
        if (realCause.getMessage().contains("Duplicate entry")) {
            throw new PlatformDataIntegrityException("error.msg.datatable.registered",
                    "Datatable `" + dataTableName + "` is already registered against an application table.",
                    "dataTableName", dataTableName);
        }
        logAsErrorUnexpectedDataIntegrityException(dve);
        throw new PlatformDataIntegrityException("error.msg.unknown.data.integrity.issue",
                "Unknown data integrity issue with resource.");
    }

}

From source file:org.apache.fineract.infrastructure.dataqueries.service.ReportWritePlatformServiceImpl.java

private void handleReportDataIntegrityIssues(final JsonCommand command,
        final DataIntegrityViolationException dve) {

    final Throwable realCause = dve.getMostSpecificCause();
    if (realCause.getMessage().contains("unq_report_name")) {
        final String name = command.stringValueOfParameterNamed("reportName");
        throw new PlatformDataIntegrityException("error.msg.report.duplicate.name",
                "A report with name '" + name + "' already exists", "name", name);
    }/*from  w  w w.j  av a 2s  .c  o  m*/

    logger.error(dve.getMessage(), dve);
    throw new PlatformDataIntegrityException("error.msg.report.unknown.data.integrity.issue",
            "Unknown data integrity issue with resource: " + realCause.getMessage());
}

From source file:org.apache.fineract.infrastructure.scheduledemail.service.EmailCampaignWritePlatformCommandHandlerImpl.java

private void handleDataIntegrityIssues(@SuppressWarnings("unused") final JsonCommand command,
        final DataIntegrityViolationException dve) {
    final Throwable realCause = dve.getMostSpecificCause();

    throw new PlatformDataIntegrityException("error.msg.scheduledemail.campaign.unknown.data.integrity.issue",
            "Unknown data integrity issue with resource: " + realCause.getMessage());
}

From source file:org.apache.fineract.organisation.office.service.OfficeWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*from w ww.  j a v  a2 s. c o  m*/
@Caching(evict = {
        @CacheEvict(value = "offices", key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat(#root.target.context.authenticatedUser().getOffice().getHierarchy()+'of')"),
        @CacheEvict(value = "officesForDropdown", key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat(#root.target.context.authenticatedUser().getOffice().getHierarchy()+'ofd')") })
public CommandProcessingResult createOffice(final JsonCommand command) {

    try {
        final AppUser currentUser = this.context.authenticatedUser();

        this.fromApiJsonDeserializer.validateForCreate(command.json());

        Long parentId = null;
        if (command.parameterExists("parentId")) {
            parentId = command.longValueOfParameterNamed("parentId");
        }

        final Office parent = validateUserPriviledgeOnOfficeAndRetrieve(currentUser, parentId);
        final Office office = Office.fromJson(parent, command);

        // pre save to generate id for use in office hierarchy
        this.officeRepositoryWrapper.save(office);

        office.generateHierarchy();

        this.officeRepositoryWrapper.save(office);

        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withEntityId(office.getId()) //
                .withOfficeId(office.getId()) //
                .build();
    } catch (final DataIntegrityViolationException dve) {
        handleOfficeDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleOfficeDataIntegrityIssues(command, throwable, dve);
        return CommandProcessingResult.empty();
    }
}

From source file:org.apache.fineract.organisation.office.service.OfficeWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*www . j  a v  a2 s . c  om*/
@Caching(evict = {
        @CacheEvict(value = "offices", key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat(#root.target.context.authenticatedUser().getOffice().getHierarchy()+'of')"),
        @CacheEvict(value = "officesForDropdown", key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat(#root.target.context.authenticatedUser().getOffice().getHierarchy()+'ofd')"),
        @CacheEvict(value = "officesById", key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat(#officeId)") })
public CommandProcessingResult updateOffice(final Long officeId, final JsonCommand command) {

    try {
        final AppUser currentUser = this.context.authenticatedUser();

        this.fromApiJsonDeserializer.validateForUpdate(command.json());

        Long parentId = null;
        if (command.parameterExists("parentId")) {
            parentId = command.longValueOfParameterNamed("parentId");
        }

        final Office office = validateUserPriviledgeOnOfficeAndRetrieve(currentUser, officeId);

        final Map<String, Object> changes = office.update(command);

        if (changes.containsKey("parentId")) {
            final Office parent = validateUserPriviledgeOnOfficeAndRetrieve(currentUser, parentId);
            office.update(parent);
        }

        if (!changes.isEmpty()) {
            this.officeRepositoryWrapper.saveAndFlush(office);
        }

        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withEntityId(office.getId()) //
                .withOfficeId(office.getId()) //
                .with(changes) //
                .build();
    } catch (final DataIntegrityViolationException dve) {
        handleOfficeDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleOfficeDataIntegrityIssues(command, throwable, dve);
        return CommandProcessingResult.empty();
    }
}