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:free.fucks.initi.config.data.ExceptionPointCut.java

/**
 *
 * @param joinPoint/*from w  w  w .ja v  a 2  s.c o m*/
 * @return
 * @throws Throwable
 */
@Around("execution(* free.fucks.initi.service.*.insert*(..)) || "
        + "execution(* free.fucks.initi.service.*.update*(..)) || "
        + "execution(* free.fucks.initi.service.*.save*(..)) || "
        + "execution(* free.fucks.initi.service.*.remove*(..)) || "
        + "execution(* free.fucks.initi.service.*.delete*(..))")
public Object doHandleDataIntegrityViolationException(ProceedingJoinPoint joinPoint) throws Throwable {
    try {
        LOG.info("------> Caiu no ASPECT!");
        return joinPoint.proceed();
    } catch (DataIntegrityViolationException exception) {
        if (exception.getMostSpecificCause() instanceof PSQLException) {
            PSQLException currentException = (PSQLException) exception.getMostSpecificCause();

            if (currentException.getSQLState().equals(this.DUPLICATED_REGISTER_ERROR)) {
                //manipula a string de exception para pegar o nome do campo duplicado e 
                //gerar uma exception com uma mensagem mais amigavel ao usurio final.
                int start = currentException.getServerErrorMessage().getDetail().indexOf("Key (") + 5;
                int end = currentException.getServerErrorMessage().getDetail().indexOf(")=(");

                String fieldError = currentException.getServerErrorMessage().getDetail().substring(start, end);

                throw new DataIntegrityViolationException(
                        "O campo " + fieldsMessageSource.getMessage(fieldError, null, Locale.getDefault())
                                + " j existe.");
            }
        }
    } catch (AccessDeniedException exception) {
        throw new AccessDeniedException(
                fieldsMessageSource.getMessage(ACCESS_DENIED_EXCEPTION_MESSAGE, null, Locale.getDefault()));
    } catch (Exception exception) {
        return exception;
    }
    return null;
}

From source file:br.fucks.initial.config.data.ExceptionPointCut.java

/**
 *
 * @param joinPoint/*from w  w  w. j av  a 2  s  .co m*/
 * @return
 * @throws Throwable
 */
@Around("execution(* br.org.pti.credential.service.*.insert*(..)) || "
        + "execution(* br.org.pti.credential.service.*.update*(..)) || "
        + "execution(* br.org.pti.credential.service.*.save*(..)) || "
        + "execution(* br.org.pti.credential.service.*.remove*(..)) || "
        + "execution(* br.org.pti.credential.service.*.delete*(..))")
public Object doHandleDataIntegrityViolationException(ProceedingJoinPoint joinPoint) throws Throwable {
    try {
        return joinPoint.proceed();
    } catch (DataIntegrityViolationException exception) {
        if (exception.getMostSpecificCause() instanceof PSQLException) {
            PSQLException currentException = (PSQLException) exception.getMostSpecificCause();

            if (currentException.getSQLState().equals(this.DUPLICATED_REGISTER_ERROR)) {
                //manipula a string de exception para pegar o nome do campo duplicado e 
                //gerar uma exception com uma mensagem mais amigavel ao usurio final.
                int start = currentException.getServerErrorMessage().getDetail().indexOf("Key (") + 5;
                int end = currentException.getServerErrorMessage().getDetail().indexOf(")=(");

                String fieldError = currentException.getServerErrorMessage().getDetail().substring(start, end);

                throw new DataIntegrityViolationException(
                        "O campo " + fieldsMessageSource.getMessage(fieldError, null, Locale.getDefault())
                                + " j existe.");
            }
            if (currentException.getSQLState().equals(this.FOREING_KEY_REFERENCED_ERROR)) {
                //manipula a string de exception para pegar o nome do campo duplicado e 
                //gerar uma exception com uma mensagem mais amigavel ao usurio final.
                int start = currentException.getServerErrorMessage().getDetail().indexOf("table ") + 7;
                int end = currentException.getServerErrorMessage().getDetail().indexOf("\".");

                String fieldReference = currentException.getServerErrorMessage().getMessage().substring(
                        currentException.getServerErrorMessage().getMessage().indexOf("on table \"") + 10,
                        currentException.getServerErrorMessage().getMessage().indexOf("\" violates"));
                String fieldReferenceOn = currentException.getServerErrorMessage().getDetail().substring(start,
                        end);

                throw new DataIntegrityViolationException("No  possvel excluir o <b>"
                        + fieldsMessageSource.getMessage(fieldReference, null, Locale.getDefault())
                        + "</b> pois o registro ainda  referenciado em <b>'"
                        + fieldsMessageSource.getMessage(fieldReferenceOn, null, Locale.getDefault())
                        + "'</b>.");
            }
        }
    } catch (AccessDeniedException exception) {
        throw new AccessDeniedException(
                fieldsMessageSource.getMessage(ACCESS_DENIED_EXCEPTION_MESSAGE, null, Locale.getDefault()));
    } catch (Exception exception) {
        return exception;
    }
    return null;
}

From source file:com.gst.portfolio.floatingrates.service.FloatingRateWritePlatformServiceImpl.java

@Transactional
@Override/*from www. j  a  v a2 s . c  om*/
public CommandProcessingResult createFloatingRate(final JsonCommand command) {
    try {
        this.fromApiJsonDeserializer.validateForCreate(command.json());
        final AppUser currentUser = this.context.authenticatedUser();
        final FloatingRate newFloatingRate = FloatingRate.createNew(currentUser, command);
        this.floatingRateRepository.save(newFloatingRate);
        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withEntityId(newFloatingRate.getId()) //
                .build();
    } catch (final DataIntegrityViolationException dve) {
        handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleDataIntegrityIssues(command, throwable, dve);
        return CommandProcessingResult.empty();
    }
}

From source file:com.gst.portfolio.floatingrates.service.FloatingRateWritePlatformServiceImpl.java

@Transactional
@Override//from w ww .  ja va  2s.c om
public CommandProcessingResult updateFloatingRate(final JsonCommand command) {
    try {
        final FloatingRate floatingRateForUpdate = this.floatingRateRepository
                .findOneWithNotFoundDetection(command.entityId());
        this.fromApiJsonDeserializer.validateForUpdate(command.json(), floatingRateForUpdate);
        final AppUser currentUser = this.context.authenticatedUser();
        final Map<String, Object> changes = floatingRateForUpdate.update(command, currentUser);

        if (!changes.isEmpty()) {
            this.floatingRateRepository.save(floatingRateForUpdate);
        }

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

From source file:com.gst.organisation.provisioning.service.ProvisioningCategoryWritePlatformServiceJpaRepositoryImpl.java

@Override
public CommandProcessingResult createProvisioningCateogry(JsonCommand command) {
    try {//from  ww  w. j av  a2 s .  c  o  m
        this.fromApiJsonDeserializer.validateForCreate(command.json());
        final ProvisioningCategory provisioningCategory = ProvisioningCategory.fromJson(command);
        this.provisioningCategoryRepository.save(provisioningCategory);
        return new CommandProcessingResultBuilder().withCommandId(command.commandId())
                .withEntityId(provisioningCategory.getId()).build();
    } catch (final DataIntegrityViolationException dve) {
        handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleDataIntegrityIssues(command, throwable, dve);
        return CommandProcessingResult.empty();
    }
}

From source file:com.gst.portfolio.fund.service.FundWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*  ww w . j a v  a  2s .c  om*/
@CacheEvict(value = "funds", key = "T(com.gst.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat('fn')")
public CommandProcessingResult createFund(final JsonCommand command) {

    try {
        this.context.authenticatedUser();

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

        final Fund fund = Fund.fromJson(command);

        this.fundRepository.save(fund);

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

From source file:com.gst.organisation.provisioning.service.ProvisioningCategoryWritePlatformServiceJpaRepositoryImpl.java

@Override
public CommandProcessingResult updateProvisioningCategory(final Long categoryId, JsonCommand command) {
    try {/*ww  w  . j  a  va 2s  . c  o m*/
        this.fromApiJsonDeserializer.validateForUpdate(command.json());
        final ProvisioningCategory provisioningCategoryForUpdate = this.provisioningCategoryRepository
                .findOne(categoryId);
        if (provisioningCategoryForUpdate == null) {
            throw new ProvisioningCategoryNotFoundException(categoryId);
        }
        final Map<String, Object> changes = provisioningCategoryForUpdate.update(command);
        if (!changes.isEmpty()) {
            this.provisioningCategoryRepository.save(provisioningCategoryForUpdate);
        }
        return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(categoryId)
                .with(changes).build();
    } catch (final DataIntegrityViolationException dve) {
        handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleDataIntegrityIssues(command, throwable, dve);
        return CommandProcessingResult.empty();
    }
}

From source file:com.gst.portfolio.fund.service.FundWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override//  w w w. ja v a2 s. c om
@CacheEvict(value = "funds", key = "T(com.gst.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat('fn')")
public CommandProcessingResult updateFund(final Long fundId, final JsonCommand command) {

    try {
        this.context.authenticatedUser();

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

        final Fund fund = this.fundRepository.findOne(fundId);
        if (fund == null) {
            throw new FundNotFoundException(fundId);
        }

        final Map<String, Object> changes = fund.update(command);
        if (!changes.isEmpty()) {
            this.fundRepository.saveAndFlush(fund);
        }

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

From source file:com.gst.organisation.staff.service.StaffWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/* www . ja v  a 2s  .co  m*/
public CommandProcessingResult createStaff(final JsonCommand command) {

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

        final Long officeId = command.longValueOfParameterNamed("officeId");

        final Office staffOffice = this.officeRepositoryWrapper.findOneWithNotFoundDetection(officeId);
        final Staff staff = Staff.fromJson(staffOffice, command);

        this.staffRepository.save(staff);

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

From source file:com.gst.infrastructure.codes.service.CodeWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override//w w  w .  j  a  v a 2  s. c  om
@CacheEvict(value = "codes", key = "T(com.gst.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();
    }
}