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:org.apache.fineract.organisation.staff.service.StaffWritePlatformServiceJpaRepositoryImpl.java

private void handleStaffDataIntegrityIssues(final JsonCommand command,
        final DataIntegrityViolationException dve) {
    final Throwable realCause = dve.getMostSpecificCause();

    if (realCause.getMessage().contains("external_id")) {

        final String externalId = command.stringValueOfParameterNamed("externalId");
        throw new PlatformDataIntegrityException("error.msg.staff.duplicate.externalId",
                "Staff with externalId `" + externalId + "` already exists", "externalId", externalId);
    } else if (realCause.getMessage().contains("display_name")) {
        final String lastname = command.stringValueOfParameterNamed("lastname");
        String displayName = lastname;
        if (!StringUtils.isBlank(displayName)) {
            final String firstname = command.stringValueOfParameterNamed("firstname");
            displayName = lastname + ", " + firstname;
        }/*from w  w  w  . j a v  a 2 s. c om*/
        throw new PlatformDataIntegrityException("error.msg.staff.duplicate.displayName",
                "A staff with the given display name '" + displayName + "' already exists", "displayName",
                displayName);
    }

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

From source file:org.apache.fineract.organisation.teller.service.TellerWritePlatformServiceJpaImpl.java

@Override
public CommandProcessingResult allocateCashierToTeller(final Long tellerId, JsonCommand command) {
    try {// w  w  w.  j  a  v  a 2 s .c  om
        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.cashierTransactionDataValidator.validateCashierAllowedDateAndTime(cashier, teller);

        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();
    }
}

From source file:org.apache.fineract.portfolio.charge.service.ChargeWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*from   w w  w  .  ja v  a2 s  .co  m*/
@CacheEvict(value = "charges", key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat('ch')")
public CommandProcessingResult createCharge(final JsonCommand command) {
    try {
        this.context.authenticatedUser();
        this.fromApiJsonDeserializer.validateForCreate(command.json());

        // Retrieve linked GLAccount for Client charges (if present)
        final Long glAccountId = command.longValueOfParameterNamed(ChargesApiConstants.glAccountIdParamName);

        GLAccount glAccount = null;
        if (glAccountId != null) {
            glAccount = this.gLAccountRepository.findOneWithNotFoundDetection(glAccountId);
        }

        final Long taxGroupId = command.longValueOfParameterNamed(ChargesApiConstants.taxGroupIdParamName);
        TaxGroup taxGroup = null;
        if (taxGroupId != null) {
            taxGroup = this.taxGroupRepository.findOneWithNotFoundDetection(taxGroupId);
        }

        final Charge charge = Charge.fromJson(command, glAccount, taxGroup);
        this.chargeRepository.save(charge);

        // check if the office specific products are enabled. If yes, then
        // save this savings product against a specific office
        // i.e. this savings product is specific for this office.
        fineractEntityAccessUtil.checkConfigurationAndAddProductResrictionsForUserOffice(
                FineractEntityAccessType.OFFICE_ACCESS_TO_CHARGES, charge.getId());

        return new CommandProcessingResultBuilder().withCommandId(command.commandId())
                .withEntityId(charge.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:org.apache.fineract.portfolio.charge.service.ChargeWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override//www  .ja  v  a  2 s  .co  m
@CacheEvict(value = "charges", key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat('ch')")
public CommandProcessingResult updateCharge(final Long chargeId, final JsonCommand command) {

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

        final Charge chargeForUpdate = this.chargeRepository.findOne(chargeId);
        if (chargeForUpdate == null) {
            throw new ChargeNotFoundException(chargeId);
        }

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

        this.fromApiJsonDeserializer.validateChargeTimeNCalculationType(chargeForUpdate.getChargeTimeType(),
                chargeForUpdate.getChargeCalculation());

        // MIFOSX-900: Check if the Charge has been active before and now is
        // deactivated:
        if (changes.containsKey("active")) {
            // IF the key exists then it has changed (otherwise it would
            // have been filtered), so check current state:
            if (!chargeForUpdate.isActive()) {
                // TODO: Change this function to only check the mappings!!!
                final Boolean isChargeExistWithLoans = isAnyLoanProductsAssociateWithThisCharge(chargeId);
                final Boolean isChargeExistWithSavings = isAnySavingsProductsAssociateWithThisCharge(chargeId);

                if (isChargeExistWithLoans || isChargeExistWithSavings) {
                    throw new ChargeCannotBeUpdatedException(
                            "error.msg.charge.cannot.be.updated.it.is.used.in.loan",
                            "This charge cannot be updated, it is used in loan");
                }
            }
        } else if ((changes.containsKey("feeFrequency") || changes.containsKey("feeInterval"))
                && chargeForUpdate.isLoanCharge()) {
            final Boolean isChargeExistWithLoans = isAnyLoanProductsAssociateWithThisCharge(chargeId);
            if (isChargeExistWithLoans) {
                throw new ChargeCannotBeUpdatedException(
                        "error.msg.charge.frequency.cannot.be.updated.it.is.used.in.loan",
                        "This charge frequency cannot be updated, it is used in loan");
            }
        }

        // Has account Id been changed ?
        if (changes.containsKey(ChargesApiConstants.glAccountIdParamName)) {
            final Long newValue = command.longValueOfParameterNamed(ChargesApiConstants.glAccountIdParamName);
            GLAccount newIncomeAccount = null;
            if (newValue != null) {
                newIncomeAccount = this.gLAccountRepository.findOneWithNotFoundDetection(newValue);
            }
            chargeForUpdate.setAccount(newIncomeAccount);
        }

        if (changes.containsKey(ChargesApiConstants.taxGroupIdParamName)) {
            final Long newValue = command.longValueOfParameterNamed(ChargesApiConstants.taxGroupIdParamName);
            TaxGroup taxGroup = null;
            if (newValue != null) {
                taxGroup = this.taxGroupRepository.findOneWithNotFoundDetection(newValue);
            }
            chargeForUpdate.setTaxGroup(taxGroup);
        }

        if (!changes.isEmpty()) {
            this.chargeRepository.save(chargeForUpdate);
        }

        return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(chargeId)
                .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:org.apache.fineract.portfolio.client.service.ClientWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*from w  w w  .  j a  va  2 s.  c  o m*/
public CommandProcessingResult createClient(final JsonCommand command) {

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

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

        final GlobalConfigurationPropertyData configuration = this.configurationReadPlatformService
                .retrieveGlobalConfiguration("Enable-Address");

        final Boolean isAddressEnabled = configuration.isEnabled();

        final Boolean isStaff = command.booleanObjectValueOfParameterNamed(ClientApiConstants.isStaffParamName);

        final Long officeId = command.longValueOfParameterNamed(ClientApiConstants.officeIdParamName);

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

        final Long groupId = command.longValueOfParameterNamed(ClientApiConstants.groupIdParamName);

        Group clientParentGroup = null;
        if (groupId != null) {
            clientParentGroup = this.groupRepository.findOne(groupId);
            if (clientParentGroup == null) {
                throw new GroupNotFoundException(groupId);
            }
        }

        Staff staff = null;
        final Long staffId = command.longValueOfParameterNamed(ClientApiConstants.staffIdParamName);
        if (staffId != null) {
            staff = this.staffRepository.findByOfficeHierarchyWithNotFoundDetection(staffId,
                    clientOffice.getHierarchy());
        }

        CodeValue gender = null;
        final Long genderId = command.longValueOfParameterNamed(ClientApiConstants.genderIdParamName);
        if (genderId != null) {
            gender = this.codeValueRepository
                    .findOneByCodeNameAndIdWithNotFoundDetection(ClientApiConstants.GENDER, genderId);
        }

        CodeValue clientType = null;
        final Long clientTypeId = command.longValueOfParameterNamed(ClientApiConstants.clientTypeIdParamName);
        if (clientTypeId != null) {
            clientType = this.codeValueRepository
                    .findOneByCodeNameAndIdWithNotFoundDetection(ClientApiConstants.CLIENT_TYPE, clientTypeId);
        }

        CodeValue clientClassification = null;
        final Long clientClassificationId = command
                .longValueOfParameterNamed(ClientApiConstants.clientClassificationIdParamName);
        if (clientClassificationId != null) {
            clientClassification = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection(
                    ClientApiConstants.CLIENT_CLASSIFICATION, clientClassificationId);
        }

        final Long savingsProductId = command
                .longValueOfParameterNamed(ClientApiConstants.savingsProductIdParamName);
        if (savingsProductId != null) {
            SavingsProduct savingsProduct = this.savingsProductRepository.findOne(savingsProductId);
            if (savingsProduct == null) {
                throw new SavingsProductNotFoundException(savingsProductId);
            }
        }

        final Integer legalFormParamValue = command
                .integerValueOfParameterNamed(ClientApiConstants.legalFormIdParamName);
        boolean isEntity = false;
        Integer legalFormValue = null;
        if (legalFormParamValue != null) {
            LegalForm legalForm = LegalForm.fromInt(legalFormParamValue);
            if (legalForm != null) {
                legalFormValue = legalForm.getValue();
                isEntity = legalForm.isEntity();
            }
        }

        final Client newClient = Client.createNew(currentUser, clientOffice, clientParentGroup, staff,
                savingsProductId, gender, clientType, clientClassification, legalFormValue, command);
        this.clientRepository.save(newClient);
        boolean rollbackTransaction = false;
        if (newClient.isActive()) {
            validateParentGroupRulesBeforeClientActivation(newClient);
            runEntityDatatableCheck(newClient.getId());
            final CommandWrapper commandWrapper = new CommandWrapperBuilder().activateClient(null).build();
            rollbackTransaction = this.commandProcessingService.validateCommand(commandWrapper, currentUser);
        }

        this.clientRepository.save(newClient);
        if (newClient.isActive()) {
            this.businessEventNotifierService.notifyBusinessEventWasExecuted(BUSINESS_EVENTS.CLIENTS_ACTIVATE,
                    constructEntityMap(BUSINESS_ENTITY.CLIENT, newClient));
        }
        if (newClient.isAccountNumberRequiresAutoGeneration()) {
            AccountNumberFormat accountNumberFormat = this.accountNumberFormatRepository
                    .findByAccountType(EntityAccountType.CLIENT);
            newClient.updateAccountNo(accountNumberGenerator.generate(newClient, accountNumberFormat));
            this.clientRepository.save(newClient);
        }

        final Locale locale = command.extractLocale();
        final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);
        CommandProcessingResult result = openSavingsAccount(newClient, fmt);
        if (result.getSavingsId() != null) {
            this.clientRepository.save(newClient);

        }

        if (isEntity) {
            extractAndCreateClientNonPerson(newClient, command);
        }

        if (isAddressEnabled) {
            this.addressWritePlatformService.addNewClientAddress(newClient, command);
        }

        if (command.parameterExists(ClientApiConstants.datatables)) {
            this.entityDatatableChecksWritePlatformService.saveDatatables(
                    StatusEnum.CREATE.getCode().longValue(), EntityTables.CLIENT.getName(), newClient.getId(),
                    null, command.arrayOfParameterNamed(ClientApiConstants.datatables));
        }

        this.entityDatatableChecksWritePlatformService.runTheCheck(newClient.getId(),
                EntityTables.CLIENT.getName(), StatusEnum.CREATE.getCode().longValue(),
                EntityTables.CLIENT.getForeignKeyColumnNameOnDatatable());
        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withOfficeId(clientOffice.getId()) //
                .withClientId(newClient.getId()) //
                .withGroupId(groupId) //
                .withEntityId(newClient.getId()) //
                .withSavingsId(result.getSavingsId())//
                .setRollbackTransaction(rollbackTransaction)//
                .setRollbackTransaction(result.isRollbackTransaction())//
                .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:org.apache.fineract.portfolio.client.service.ClientWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override//from   ww  w  . j  a va2 s.  c  om
public CommandProcessingResult updateClient(final Long clientId, final JsonCommand command) {

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

        final Client clientForUpdate = this.clientRepository.findOneWithNotFoundDetection(clientId);
        final String clientHierarchy = clientForUpdate.getOffice().getHierarchy();

        this.context.validateAccessRights(clientHierarchy);

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

        if (changes.containsKey(ClientApiConstants.staffIdParamName)) {

            final Long newValue = command.longValueOfParameterNamed(ClientApiConstants.staffIdParamName);
            Staff newStaff = null;
            if (newValue != null) {
                newStaff = this.staffRepository.findByOfficeHierarchyWithNotFoundDetection(newValue,
                        clientForUpdate.getOffice().getHierarchy());
            }
            clientForUpdate.updateStaff(newStaff);
        }

        if (changes.containsKey(ClientApiConstants.genderIdParamName)) {

            final Long newValue = command.longValueOfParameterNamed(ClientApiConstants.genderIdParamName);
            CodeValue gender = null;
            if (newValue != null) {
                gender = this.codeValueRepository
                        .findOneByCodeNameAndIdWithNotFoundDetection(ClientApiConstants.GENDER, newValue);
            }
            clientForUpdate.updateGender(gender);
        }

        if (changes.containsKey(ClientApiConstants.savingsProductIdParamName)) {
            if (clientForUpdate.isActive()) {
                throw new ClientActiveForUpdateException(clientId,
                        ClientApiConstants.savingsProductIdParamName);
            }
            SavingsProduct savingsProduct = null;
            final Long savingsProductId = command
                    .longValueOfParameterNamed(ClientApiConstants.savingsProductIdParamName);
            if (savingsProductId != null) {
                savingsProduct = this.savingsProductRepository.findOne(savingsProductId);
                if (savingsProduct == null) {
                    throw new SavingsProductNotFoundException(savingsProductId);
                }
            }
            clientForUpdate.updateSavingsProduct(savingsProductId);
        }

        if (changes.containsKey(ClientApiConstants.genderIdParamName)) {
            final Long newValue = command.longValueOfParameterNamed(ClientApiConstants.genderIdParamName);
            CodeValue newCodeVal = null;
            if (newValue != null) {
                newCodeVal = this.codeValueRepository
                        .findOneByCodeNameAndIdWithNotFoundDetection(ClientApiConstants.GENDER, newValue);
            }
            clientForUpdate.updateGender(newCodeVal);
        }

        if (changes.containsKey(ClientApiConstants.clientTypeIdParamName)) {
            final Long newValue = command.longValueOfParameterNamed(ClientApiConstants.clientTypeIdParamName);
            CodeValue newCodeVal = null;
            if (newValue != null) {
                newCodeVal = this.codeValueRepository
                        .findOneByCodeNameAndIdWithNotFoundDetection(ClientApiConstants.CLIENT_TYPE, newValue);
            }
            clientForUpdate.updateClientType(newCodeVal);
        }

        if (changes.containsKey(ClientApiConstants.clientClassificationIdParamName)) {
            final Long newValue = command
                    .longValueOfParameterNamed(ClientApiConstants.clientClassificationIdParamName);
            CodeValue newCodeVal = null;
            if (newValue != null) {
                newCodeVal = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection(
                        ClientApiConstants.CLIENT_CLASSIFICATION, newValue);
            }
            clientForUpdate.updateClientClassification(newCodeVal);
        }

        if (!changes.isEmpty()) {
            this.clientRepository.saveAndFlush(clientForUpdate);
        }

        if (changes.containsKey(ClientApiConstants.legalFormIdParamName)) {
            Integer legalFormValue = clientForUpdate.getLegalForm();
            boolean isChangedToEntity = false;
            if (legalFormValue != null) {
                LegalForm legalForm = LegalForm.fromInt(legalFormValue);
                if (legalForm != null)
                    isChangedToEntity = legalForm.isEntity();
            }

            if (isChangedToEntity) {
                extractAndCreateClientNonPerson(clientForUpdate, command);
            } else {
                final ClientNonPerson clientNonPerson = this.clientNonPersonRepository
                        .findOneByClientId(clientForUpdate.getId());
                if (clientNonPerson != null)
                    this.clientNonPersonRepository.delete(clientNonPerson);
            }
        }

        final ClientNonPerson clientNonPersonForUpdate = this.clientNonPersonRepository
                .findOneByClientId(clientId);
        if (clientNonPersonForUpdate != null) {
            final JsonElement clientNonPersonElement = command
                    .jsonElement(ClientApiConstants.clientNonPersonDetailsParamName);
            final Map<String, Object> clientNonPersonChanges = clientNonPersonForUpdate
                    .update(JsonCommand.fromExistingCommand(command, clientNonPersonElement));

            if (clientNonPersonChanges.containsKey(ClientApiConstants.constitutionIdParamName)) {

                final Long newValue = this.fromApiJsonHelper
                        .extractLongNamed(ClientApiConstants.constitutionIdParamName, clientNonPersonElement);
                CodeValue constitution = null;
                if (newValue != null) {
                    constitution = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection(
                            ClientApiConstants.CLIENT_NON_PERSON_CONSTITUTION, newValue);
                }
                clientNonPersonForUpdate.updateConstitution(constitution);
            }

            if (clientNonPersonChanges.containsKey(ClientApiConstants.mainBusinessLineIdParamName)) {

                final Long newValue = this.fromApiJsonHelper.extractLongNamed(
                        ClientApiConstants.mainBusinessLineIdParamName, clientNonPersonElement);
                CodeValue mainBusinessLine = null;
                if (newValue != null) {
                    mainBusinessLine = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection(
                            ClientApiConstants.CLIENT_NON_PERSON_MAIN_BUSINESS_LINE, newValue);
                }
                clientNonPersonForUpdate.updateMainBusinessLine(mainBusinessLine);
            }

            if (!clientNonPersonChanges.isEmpty()) {
                this.clientNonPersonRepository.saveAndFlush(clientNonPersonForUpdate);
            }

            changes.putAll(clientNonPersonChanges);
        } else {
            final Integer legalFormParamValue = command
                    .integerValueOfParameterNamed(ClientApiConstants.legalFormIdParamName);
            boolean isEntity = false;
            if (legalFormParamValue != null) {
                final LegalForm legalForm = LegalForm.fromInt(legalFormParamValue);
                if (legalForm != null) {
                    isEntity = legalForm.isEntity();
                }
            }
            if (isEntity) {
                extractAndCreateClientNonPerson(clientForUpdate, command);
            }
        }
        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withOfficeId(clientForUpdate.officeId()) //
                .withClientId(clientId) //
                .withEntityId(clientId) //
                .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:org.apache.fineract.portfolio.fund.service.FundWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override//from w  w  w  .j av  a 2  s  .c om
@CacheEvict(value = "funds", key = "T(org.apache.fineract.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:org.apache.fineract.portfolio.fund.service.FundWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*w  w w.j  a va2  s  .c  om*/
@CacheEvict(value = "funds", key = "T(org.apache.fineract.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:org.apache.fineract.portfolio.loanaccount.service.LoanApplicationWritePlatformServiceJpaRepositoryImpl.java

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

    final Throwable realCause = dve.getMostSpecificCause();
    if (realCause.getMessage().contains("loan_account_no_UNIQUE")) {

        final String accountNo = command.stringValueOfParameterNamed("accountNo");
        throw new PlatformDataIntegrityException("error.msg.loan.duplicate.accountNo",
                "Loan with accountNo `" + accountNo + "` already exists", "accountNo", accountNo);
    } else if (realCause.getMessage().contains("loan_externalid_UNIQUE")) {

        final String externalId = command.stringValueOfParameterNamed("externalId");
        throw new PlatformDataIntegrityException("error.msg.loan.duplicate.externalId",
                "Loan with externalId `" + externalId + "` already exists", "externalId", externalId);
    }/*from   ww  w .  ja  v  a2  s.  c  o  m*/

    logAsErrorUnexpectedDataIntegrityException(dve);
    throw new PlatformDataIntegrityException("error.msg.unknown.data.integrity.issue",
            "Unknown data integrity issue with resource.");
}

From source file:org.mifosplatform.infrastructure.configuration.service.ConfigurationWritePlatformServiceJpaRepositoryImpl.java

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

    final Throwable realCause = dve.getMostSpecificCause();
    if (realCause.getMessage().contains("name_config")) {
        final String username = command.stringValueOfParameterNamed(ConfigurationConstants.NAME);
        final StringBuilder defaultMessageBuilder = new StringBuilder("Name with").append(username)
                .append(" already exists.");
        throw new PlatformDataIntegrityException("error.msg.smtp.duplicate.name",
                defaultMessageBuilder.toString(), "username", username);
    }//w  w w .j  a v  a2 s.  com

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