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.portfolio.shareaccounts.service.ShareAccountWritePlatformServiceJpaRepositoryImpl.java

@Override
public CommandProcessingResult createShareAccount(JsonCommand jsonCommand) {
    try {/*from w  ww  .  j av a 2s. c o m*/
        ShareAccount account = this.accountDataSerializer.validateAndCreate(jsonCommand);
        this.shareAccountRepository.save(account);
        generateAccountNumber(account);
        journalEntryWritePlatformService.createJournalEntriesForShares(
                populateJournalEntries(account, account.getPendingForApprovalSharePurchaseTransactions()));
        return new CommandProcessingResultBuilder() //
                .withCommandId(jsonCommand.commandId()) //
                .withEntityId(account.getId()) //
                .build();
    } catch (final DataIntegrityViolationException dve) {
        handleDataIntegrityIssues(jsonCommand, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleDataIntegrityIssues(jsonCommand, throwable, dve);
        return CommandProcessingResult.empty();
    }
}

From source file:com.gst.portfolio.shareaccounts.service.ShareAccountWritePlatformServiceJpaRepositoryImpl.java

@SuppressWarnings("unchecked")
@Override// w  w w. j  a v a2  s.  c o m
public CommandProcessingResult updateShareAccount(Long accountId, JsonCommand jsonCommand) {
    try {
        Date transactionDate = DateUtils.getDateOfTenant();
        ShareAccount account = this.shareAccountRepository.findOneWithNotFoundDetection(accountId);
        Map<String, Object> changes = this.accountDataSerializer.validateAndUpdate(jsonCommand, account);
        if (!changes.isEmpty()) {
            this.shareAccountRepository.save(account);
        }
        // since we are reverting all journal entries we need to add journal
        // entries for application request
        if (changes.containsKey("reversalIds")) {
            ArrayList<Long> reversalIds = (ArrayList<Long>) changes.get("reversalIds");
            this.journalEntryWritePlatformService.revertShareAccountJournalEntries(reversalIds,
                    transactionDate);
            journalEntryWritePlatformService.createJournalEntriesForShares(
                    populateJournalEntries(account, account.getPendingForApprovalSharePurchaseTransactions()));
            changes.remove("reversalIds");
        }
        return new CommandProcessingResultBuilder() //
                .withCommandId(jsonCommand.commandId()) //
                .withEntityId(accountId) //
                .with(changes) //
                .build();
    } catch (DataIntegrityViolationException dve) {
        handleDataIntegrityIssues(jsonCommand, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleDataIntegrityIssues(jsonCommand, throwable, dve);
        return CommandProcessingResult.empty();
    }
}

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

private CommandProcessingResult doTransactionForCashier(final Long cashierId, final CashierTxnType txnType,
        JsonCommand command) {//from  w w w. j  av  a  2  s  .c o  m
    try {
        final AppUser currentUser = this.context.authenticatedUser();

        final Cashier cashier = this.cashierRepository.findOne(cashierId);
        if (cashier == null) {
            throw new CashierNotFoundException(cashierId);
        }

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

        final String entityType = command.stringValueOfParameterNamed("entityType");
        final Long entityId = command.longValueOfParameterNamed("entityId");
        if (entityType != null) {
            if (entityType.equals("loan account")) {
                // TODO : Check if loan account exists
                // LoanAccount loan = null;
                // if (loan == null) { throw new
                // LoanAccountFoundException(entityId); }
            } else if (entityType.equals("savings account")) {
                // TODO : Check if loan account exists
                // SavingsAccount savingsaccount = null;
                // if (savingsaccount == null) { throw new
                // SavingsAccountNotFoundException(entityId); }

            }
            if (entityType.equals("client")) {
                // TODO: Check if client exists
                // Client client = null;
                // if (client == null) { throw new
                // ClientNotFoundException(entityId); }
            } else {
                // TODO : Invalid type handling
            }
        }

        final CashierTransaction cashierTxn = CashierTransaction.fromJson(cashier, command);
        cashierTxn.setTxnType(txnType.getId());

        this.cashierTxnRepository.save(cashierTxn);

        // Pass the journal entries
        FinancialActivityAccount mainVaultFinancialActivityAccount = this.financialActivityAccountRepositoryWrapper
                .findByFinancialActivityTypeWithNotFoundDetection(
                        FINANCIAL_ACTIVITY.CASH_AT_MAINVAULT.getValue());
        FinancialActivityAccount tellerCashFinancialActivityAccount = this.financialActivityAccountRepositoryWrapper
                .findByFinancialActivityTypeWithNotFoundDetection(FINANCIAL_ACTIVITY.CASH_AT_TELLER.getValue());
        GLAccount creditAccount = null;
        GLAccount debitAccount = null;
        if (txnType.equals(CashierTxnType.ALLOCATE)) {
            debitAccount = tellerCashFinancialActivityAccount.getGlAccount();
            creditAccount = mainVaultFinancialActivityAccount.getGlAccount();
        } else if (txnType.equals(CashierTxnType.SETTLE)) {
            debitAccount = mainVaultFinancialActivityAccount.getGlAccount();
            creditAccount = tellerCashFinancialActivityAccount.getGlAccount();
        }

        final Office cashierOffice = cashier.getTeller().getOffice();

        final Long time = System.currentTimeMillis();
        final String uniqueVal = String.valueOf(time) + currentUser.getId() + cashierOffice.getId();
        final String transactionId = Long.toHexString(Long.parseLong(uniqueVal));
        ClientTransaction clientTransaction = null;
        final Long shareTransactionId = null;

        final JournalEntry debitJournalEntry = JournalEntry.createNew(cashierOffice, null, // payment
                // detail
                debitAccount, "USD", // FIXME: Take currency code from the
                // transaction
                transactionId, false, // manual entry
                cashierTxn.getTxnDate(), JournalEntryType.DEBIT, cashierTxn.getTxnAmount(),
                cashierTxn.getTxnNote(), // Description
                null, null, null, // entity Type, entityId, reference number
                null, null, clientTransaction, shareTransactionId); // Loan and Savings Txn

        final JournalEntry creditJournalEntry = JournalEntry.createNew(cashierOffice, null, // payment
                // detail
                creditAccount, "USD", // FIXME: Take currency code from the
                // transaction
                transactionId, false, // manual entry
                cashierTxn.getTxnDate(), JournalEntryType.CREDIT, cashierTxn.getTxnAmount(),
                cashierTxn.getTxnNote(), // Description
                null, null, null, // entity Type, entityId, reference number
                null, null, clientTransaction, shareTransactionId); // Loan and Savings Txn

        this.glJournalEntryRepository.saveAndFlush(debitJournalEntry);
        this.glJournalEntryRepository.saveAndFlush(creditJournalEntry);

        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withEntityId(cashier.getId()) //
                .withSubEntityId(cashierTxn.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.portfolio.loanaccount.domain.LoanAccountDomainServiceJpa.java

private void saveLoanTransactionWithDataIntegrityViolationChecks(LoanTransaction newRepaymentTransaction) {
    try {/*  w ww  .ja  va 2s.com*/
        this.loanTransactionRepository.save(newRepaymentTransaction);
    } catch (DataIntegrityViolationException e) {
        final Throwable realCause = e.getCause();
        final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
        final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
                .resource("loan.transaction");
        if (realCause.getMessage().toLowerCase().contains("external_id_unique")) {
            baseDataValidator.reset().parameter("externalId").value(newRepaymentTransaction.getExternalId())
                    .failWithCode("value.must.be.unique");
        }
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                    "Validation errors exist.", dataValidationErrors);
        }
    }
}

From source file:com.gst.portfolio.loanaccount.domain.LoanAccountDomainServiceJpa.java

private void saveAndFlushLoanWithDataIntegrityViolationChecks(final Loan loan) {
    try {/*from w  w  w.  ja v  a  2s  .  c o m*/
        List<LoanRepaymentScheduleInstallment> installments = loan.getRepaymentScheduleInstallments();
        for (LoanRepaymentScheduleInstallment installment : installments) {
            if (installment.getId() == null) {
                this.repaymentScheduleInstallmentRepository.save(installment);
            }
        }
        this.loanRepositoryWrapper.saveAndFlush(loan);
    } catch (final DataIntegrityViolationException e) {
        final Throwable realCause = e.getCause();
        final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
        final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
                .resource("loan.transaction");
        if (realCause.getMessage().toLowerCase().contains("external_id_unique")) {
            baseDataValidator.reset().parameter("externalId").failWithCode("value.must.be.unique");
        }
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                    "Validation errors exist.", dataValidationErrors);
        }
    }
}

From source file:com.gst.portfolio.loanaccount.domain.LoanAccountDomainServiceJpa.java

@Override
public void saveLoanWithDataIntegrityViolationChecks(final Loan loan) {
    try {//from  w ww. ja  v a  2 s. c  o m
        List<LoanRepaymentScheduleInstallment> installments = loan.getRepaymentScheduleInstallments();
        for (LoanRepaymentScheduleInstallment installment : installments) {
            if (installment.getId() == null) {
                this.repaymentScheduleInstallmentRepository.save(installment);
            }
        }
        this.loanRepositoryWrapper.save(loan);
    } catch (final DataIntegrityViolationException e) {
        final Throwable realCause = e.getCause();
        final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
        final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
                .resource("loan.transaction");
        if (realCause.getMessage().toLowerCase().contains("external_id_unique")) {
            baseDataValidator.reset().parameter("externalId").failWithCode("value.must.be.unique");
        }
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                    "Validation errors exist.", dataValidationErrors);
        }
    }
}

From source file:com.gisgraphy.domain.repository.OpenStreetMapDaoTest.java

@Test
public void testCouldNotSaveNonUniqueGID() {
    OpenStreetMap streetOSM = GisgraphyTestHelper.createOpenStreetMapForPeterMartinStreet();
    openStreetMapDao.save(streetOSM);/* w w  w. ja  v a  2s.  c om*/
    assertNotNull(openStreetMapDao.get(streetOSM.getId()));

    OpenStreetMap streetOSM2 = GisgraphyTestHelper.createOpenStreetMapForPeterMartinStreet();
    try {
        openStreetMapDao.save(streetOSM2);
        openStreetMapDao.flushAndClear();
        fail("we should not save street with non unique GID");
    } catch (DataIntegrityViolationException e) {
        assertTrue(
                "a ConstraintViolationException should be throw when saving an openstreetmap with a non unique gid ",
                e.getCause() instanceof ConstraintViolationException);
    }

}

From source file:com.gst.portfolio.client.service.ClientWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override//from   w w w.j  a  va 2  s .  com
public CommandProcessingResult deleteClient(final Long clientId) {
    try {
        final Client client = this.clientRepository.findOneWithNotFoundDetection(clientId);

        if (client.isNotPending()) {
            throw new ClientMustBePendingToBeDeletedException(clientId);
        }
        final List<Note> relatedNotes = this.noteRepository.findByClientId(clientId);
        this.noteRepository.deleteInBatch(relatedNotes);

        final ClientNonPerson clientNonPerson = this.clientNonPersonRepository.findOneByClientId(clientId);
        if (clientNonPerson != null)
            this.clientNonPersonRepository.delete(clientNonPerson);

        this.clientRepository.delete(client);
        this.clientRepository.flush();
        return new CommandProcessingResultBuilder() //
                .withOfficeId(client.officeId()) //
                .withClientId(clientId) //
                .withEntityId(clientId) //
                .build();
    } catch (DataIntegrityViolationException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        logger.error(throwable.getMessage());
        throw new PlatformDataIntegrityException("error.msg.client.unknown.data.integrity.issue",
                "Unknown data integrity issue with resource.");
    }
}

From source file:com.gst.portfolio.group.service.GroupingTypesWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override//  ww  w.j a va2  s. co  m
public CommandProcessingResult deleteGroup(final Long groupId) {
    try {

        final Group groupForDelete = this.groupRepository.findOneWithNotFoundDetection(groupId);

        if (groupForDelete.isNotPending()) {
            throw new GroupMustBePendingToBeDeletedException(groupId);
        }

        final List<Note> relatedNotes = this.noteRepository.findByGroupId(groupId);
        this.noteRepository.deleteInBatch(relatedNotes);

        this.groupRepository.delete(groupForDelete);
        this.groupRepository.flush();
        return new CommandProcessingResultBuilder() //
                .withOfficeId(groupForDelete.getId()) //
                .withGroupId(groupForDelete.officeId()) //
                .withEntityId(groupForDelete.getId()) //
                .build();
    } catch (DataIntegrityViolationException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        logger.error(throwable.getMessage());
        throw new PlatformDataIntegrityException("error.msg.group.unknown.data.integrity.issue",
                "Unknown data integrity issue with resource.");
    }
}

From source file:com.gst.portfolio.group.service.GroupingTypesWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*from ww  w. j  a va2 s . co m*/
public CommandProcessingResult activateGroupOrCenter(final Long groupId, final JsonCommand command) {

    try {
        this.fromApiJsonDeserializer.validateForActivation(command,
                GroupingTypesApiConstants.GROUP_RESOURCE_NAME);

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

        final Group group = this.groupRepository.findOneWithNotFoundDetection(groupId);

        if (group.isGroup()) {
            validateGroupRulesBeforeActivation(group);
        }

        final LocalDate activationDate = command.localDateValueOfParameterNamed("activationDate");

        validateOfficeOpeningDateisAfterGroupOrCenterOpeningDate(group.getOffice(), group.getGroupLevel(),
                activationDate);

        group.activate(currentUser, activationDate);

        this.groupRepository.saveAndFlush(group);

        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withOfficeId(group.officeId()) //
                .withGroupId(groupId) //
                .withEntityId(groupId) //
                .build();
    } catch (final DataIntegrityViolationException dve) {
        handleGroupDataIntegrityIssues(command, dve.getMostSpecificCause(), dve, GroupTypes.GROUP);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleGroupDataIntegrityIssues(command, throwable, dve, GroupTypes.GROUP);
        return CommandProcessingResult.empty();
    }
}