Example usage for org.springframework.dao DataIntegrityViolationException getCause

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

Introduction

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

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:com.gst.useradministration.service.RoleWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override//from  w  w w  . j  av  a2s .  c o  m
public CommandProcessingResult createRole(final JsonCommand command) {

    try {
        this.context.authenticatedUser();

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

        final Role entity = Role.fromJson(command);
        this.roleRepository.save(entity);

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

From source file:com.gst.portfolio.loanproduct.service.LoanProductWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*from  w w w .j av  a2  s.com*/
public CommandProcessingResult updateLoanProduct(final Long loanProductId, final JsonCommand command) {

    try {
        this.context.authenticatedUser();

        final LoanProduct product = this.loanProductRepository.findOne(loanProductId);
        if (product == null) {
            throw new LoanProductNotFoundException(loanProductId);
        }

        this.fromApiJsonDeserializer.validateForUpdate(command.json(), product);
        validateInputDates(command);

        if (anyChangeInCriticalFloatingRateLinkedParams(command, product)
                && this.loanRepositoryWrapper.doNonClosedLoanAccountsExistForProduct(product.getId())) {
            throw new LoanProductCannotBeModifiedDueToNonClosedLoansException(product.getId());
        }

        FloatingRate floatingRate = null;
        if (command.parameterExists("floatingRatesId")) {
            floatingRate = this.floatingRateRepository
                    .findOneWithNotFoundDetection(command.longValueOfParameterNamed("floatingRatesId"));
        }

        final Map<String, Object> changes = product.update(command, this.aprCalculator, floatingRate);

        if (changes.containsKey("fundId")) {
            final Long fundId = (Long) changes.get("fundId");
            final Fund fund = findFundByIdIfProvided(fundId);
            product.update(fund);
        }

        if (changes.containsKey("transactionProcessingStrategyId")) {
            final Long transactionProcessingStrategyId = (Long) changes.get("transactionProcessingStrategyId");
            final LoanTransactionProcessingStrategy loanTransactionProcessingStrategy = findStrategyByIdIfProvided(
                    transactionProcessingStrategyId);
            product.update(loanTransactionProcessingStrategy);
        }

        if (changes.containsKey("charges")) {
            final List<Charge> productCharges = assembleListOfProductCharges(command,
                    product.getCurrency().getCode());
            final boolean updated = product.update(productCharges);
            if (!updated) {
                changes.remove("charges");
            }
        }

        // accounting related changes
        final boolean accountingTypeChanged = changes.containsKey("accountingRule");
        final Map<String, Object> accountingMappingChanges = this.accountMappingWritePlatformService
                .updateLoanProductToGLAccountMapping(product.getId(), command, accountingTypeChanged,
                        product.getAccountingType());
        changes.putAll(accountingMappingChanges);

        if (!changes.isEmpty()) {
            this.loanProductRepository.saveAndFlush(product);
        }

        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withEntityId(loanProductId) //
                .with(changes) //
                .build();

    } catch (final DataIntegrityViolationException dve) {
        handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
        return new CommandProcessingResult(Long.valueOf(-1));
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleDataIntegrityIssues(command, throwable, dve);
        return CommandProcessingResult.empty();
    }

}

From source file:com.gst.useradministration.service.RoleWritePlatformServiceJpaRepositoryImpl.java

@Caching(evict = { @CacheEvict(value = "users", allEntries = true),
        @CacheEvict(value = "usersByUsername", allEntries = true) })
@Transactional//from   w w  w  .j  a v a  2s.  c  om
@Override
public CommandProcessingResult updateRole(final Long roleId, final JsonCommand command) {
    try {
        this.context.authenticatedUser();

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

        final Role role = this.roleRepository.findOne(roleId);
        if (role == null) {
            throw new RoleNotFoundException(roleId);
        }

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

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

From source file:com.gst.useradministration.service.AppUserWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override//ww  w .  jav a 2  s  . co m
@Caching(evict = { @CacheEvict(value = "users", allEntries = true),
        @CacheEvict(value = "usersByUsername", allEntries = true) })
public CommandProcessingResult createUser(final JsonCommand command) {

    try {
        this.context.authenticatedUser();

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

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

        final Office userOffice = this.officeRepositoryWrapper.findOneWithNotFoundDetection(officeId);

        final String[] roles = command.arrayValueOfParameterNamed("roles");
        final Set<Role> allRoles = assembleSetOfRoles(roles);

        AppUser appUser;

        final String staffIdParamName = "staffId";
        final Long staffId = command.longValueOfParameterNamed(staffIdParamName);

        Staff linkedStaff = null;
        if (staffId != null) {
            linkedStaff = this.staffRepositoryWrapper.findByOfficeWithNotFoundDetection(staffId,
                    userOffice.getId());
        }

        Collection<Client> clients = null;
        if (command.hasParameter(AppUserConstants.IS_SELF_SERVICE_USER)
                && command.booleanPrimitiveValueOfParameterNamed(AppUserConstants.IS_SELF_SERVICE_USER)
                && command.hasParameter(AppUserConstants.CLIENTS)) {
            JsonArray clientsArray = command.arrayOfParameterNamed(AppUserConstants.CLIENTS);
            Collection<Long> clientIds = new HashSet<>();
            for (JsonElement clientElement : clientsArray) {
                clientIds.add(clientElement.getAsLong());
            }
            clients = this.clientRepositoryWrapper.findAll(clientIds);
        }

        appUser = AppUser.fromJson(userOffice, linkedStaff, allRoles, clients, command);

        final Boolean sendPasswordToEmail = command.booleanObjectValueOfParameterNamed("sendPasswordToEmail");
        this.userDomainService.create(appUser, sendPasswordToEmail);

        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withEntityId(appUser.getId()) //
                .withOfficeId(userOffice.getId()) //
                .build();
    } catch (final DataIntegrityViolationException dve) {
        handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException | AuthenticationServiceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleDataIntegrityIssues(command, throwable, dve);
        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .build();
    } catch (final PlatformEmailSendException e) {
        final List<ApiParameterError> dataValidationErrors = new ArrayList<>();

        final String email = command.stringValueOfParameterNamed("email");
        final ApiParameterError error = ApiParameterError.parameterError("error.msg.user.email.invalid",
                "The parameter email is invalid.", "email", email);
        dataValidationErrors.add(error);

        throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                "Validation errors exist.", dataValidationErrors);
    }
}

From source file:com.gst.useradministration.service.AppUserWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*from   www .  j  av  a2s.  c o  m*/
@Caching(evict = { @CacheEvict(value = "users", allEntries = true),
        @CacheEvict(value = "usersByUsername", allEntries = true) })
public CommandProcessingResult updateUser(final Long userId, final JsonCommand command) {

    try {

        this.context.authenticatedUser(new CommandWrapperBuilder().updateUser(null).build());

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

        final AppUser userToUpdate = this.appUserRepository.findOne(userId);

        if (userToUpdate == null) {
            throw new UserNotFoundException(userId);
        }

        final AppUserPreviousPassword currentPasswordToSaveAsPreview = getCurrentPasswordToSaveAsPreview(
                userToUpdate, command);

        Collection<Client> clients = null;
        boolean isSelfServiceUser = userToUpdate.isSelfServiceUser();
        if (command.hasParameter(AppUserConstants.IS_SELF_SERVICE_USER)) {
            isSelfServiceUser = command
                    .booleanPrimitiveValueOfParameterNamed(AppUserConstants.IS_SELF_SERVICE_USER);
        }

        if (isSelfServiceUser && command.hasParameter(AppUserConstants.CLIENTS)) {
            JsonArray clientsArray = command.arrayOfParameterNamed(AppUserConstants.CLIENTS);
            Collection<Long> clientIds = new HashSet<>();
            for (JsonElement clientElement : clientsArray) {
                clientIds.add(clientElement.getAsLong());
            }
            clients = this.clientRepositoryWrapper.findAll(clientIds);
        }

        final Map<String, Object> changes = userToUpdate.update(command, this.platformPasswordEncoder, clients);

        if (changes.containsKey("officeId")) {
            final Long officeId = (Long) changes.get("officeId");
            final Office office = this.officeRepositoryWrapper.findOneWithNotFoundDetection(officeId);
            userToUpdate.changeOffice(office);
        }

        if (changes.containsKey("staffId")) {
            final Long staffId = (Long) changes.get("staffId");
            Staff linkedStaff = null;
            if (staffId != null) {
                linkedStaff = this.staffRepositoryWrapper.findByOfficeWithNotFoundDetection(staffId,
                        userToUpdate.getOffice().getId());
            }
            userToUpdate.changeStaff(linkedStaff);
        }

        if (changes.containsKey("roles")) {
            final String[] roleIds = (String[]) changes.get("roles");
            final Set<Role> allRoles = assembleSetOfRoles(roleIds);

            userToUpdate.updateRoles(allRoles);
        }

        if (!changes.isEmpty()) {
            this.appUserRepository.saveAndFlush(userToUpdate);

            if (currentPasswordToSaveAsPreview != null) {
                this.appUserPreviewPasswordRepository.save(currentPasswordToSaveAsPreview);
            }

        }

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

From source file:com.gst.organisation.teller.service.TellerWritePlatformServiceJpaImpl.java

@Override
@Transactional/*from  w  w w  . j  a  va  2 s  .  c om*/
public CommandProcessingResult deleteCashierAllocation(Long tellerId, Long cashierId, JsonCommand command) {
    try {
        final AppUser currentUser = this.context.authenticatedUser();
        final Cashier cashier = validateUserPriviledgeOnCashierAndRetrieve(currentUser, tellerId, cashierId);
        this.cashierRepository.delete(cashier);

    } catch (final DataIntegrityViolationException dve) {
        handleTellerDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleTellerDataIntegrityIssues(command, throwable, dve);
        return CommandProcessingResult.empty();
    }

    return new CommandProcessingResultBuilder() //
            .withEntityId(cashierId) //
            .build();
}

From source file:com.gst.organisation.teller.service.TellerWritePlatformServiceJpaImpl.java

@Override
@Transactional/*from   w  w  w.  jav a  2 s  .c  om*/
public CommandProcessingResult createTeller(JsonCommand command) {
    try {
        this.context.authenticatedUser();

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

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

        // final Office parent =
        // validateUserPriviledgeOnOfficeAndRetrieve(currentUser, officeId);
        final Office tellerOffice = this.officeRepositoryWrapper.findOneWithNotFoundDetection(officeId);
        final Teller teller = Teller.fromJson(tellerOffice, command);

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

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

From source file:com.gst.organisation.teller.service.TellerWritePlatformServiceJpaImpl.java

@Override
@Transactional/* w  ww  .  j a  va 2s  .co  m*/
public CommandProcessingResult modifyTeller(Long tellerId, JsonCommand command) {
    try {

        final Long officeId = command.longValueOfParameterNamed("officeId");
        final Office tellerOffice = this.officeRepositoryWrapper.findOneWithNotFoundDetection(officeId);
        final AppUser currentUser = this.context.authenticatedUser();

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

        final Teller teller = validateUserPriviledgeOnTellerAndRetrieve(currentUser, tellerId);

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

        if (!changes.isEmpty()) {
            this.tellerRepositoryWrapper.saveAndFlush(teller);
        }

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

From source file:com.gst.organisation.teller.service.TellerWritePlatformServiceJpaImpl.java

@Override
@Transactional// w  w w. j  ava 2  s.  c  o m
public CommandProcessingResult updateCashierAllocation(Long tellerId, Long cashierId, JsonCommand command) {
    try {
        final AppUser currentUser = this.context.authenticatedUser();

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

        final Long staffId = command.longValueOfParameterNamed("staffId");
        final Staff staff = this.staffRepository.findOne(staffId);
        if (staff == null) {
            throw new StaffNotFoundException(staffId);
        }

        final Cashier cashier = validateUserPriviledgeOnCashierAndRetrieve(currentUser, tellerId, cashierId);

        cashier.setStaff(staff);

        // TODO - check if staff office and teller office match

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

        if (!changes.isEmpty()) {
            this.cashierRepository.saveAndFlush(cashier);
        }

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

From source file:com.gst.organisation.teller.service.TellerWritePlatformServiceJpaImpl.java

@Override
public CommandProcessingResult allocateCashierToTeller(final Long tellerId, JsonCommand command) {
    try {//from  w  w w .ja v a 2 s .c  o  m
        this.context.authenticatedUser();
        Long hourStartTime;
        Long minStartTime;
        Long hourEndTime;
        Long minEndTime;
        String startTime = " ";
        String endTime = " ";
        final Teller teller = this.tellerRepositoryWrapper.findOneWithNotFoundDetection(tellerId);
        final Office tellerOffice = teller.getOffice();

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

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

        final Staff staff = this.staffRepository.findOne(staffId);
        if (staff == null) {
            throw new StaffNotFoundException(staffId);
        }
        final Boolean isFullDay = command.booleanObjectValueOfParameterNamed("isFullDay");
        if (!isFullDay) {
            hourStartTime = command.longValueOfParameterNamed("hourStartTime");
            minStartTime = command.longValueOfParameterNamed("minStartTime");

            if (minStartTime == 0)
                startTime = hourStartTime.toString() + ":" + minStartTime.toString() + "0";
            else
                startTime = hourStartTime.toString() + ":" + minStartTime.toString();

            hourEndTime = command.longValueOfParameterNamed("hourEndTime");
            minEndTime = command.longValueOfParameterNamed("minEndTime");
            if (minEndTime == 0)
                endTime = hourEndTime.toString() + ":" + minEndTime.toString() + "0";
            else
                endTime = hourEndTime.toString() + ":" + minEndTime.toString();

        }

        final Cashier cashier = Cashier.fromJson(tellerOffice, teller, staff, startTime, endTime, command);

        this.cashierRepository.save(cashier);

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