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.loanaccount.service.LoanWritePlatformServiceJpaRepositoryImpl.java

private void saveLoanWithDataIntegrityViolationChecks(final Loan loan) {
    try {/*from   ww  w . j a  v  a2  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:net.firejack.platform.core.store.BaseStore.java

protected boolean checkUniqueLookupException(DataIntegrityViolationException e) {
    return e.getCause() instanceof ConstraintViolationException
            && ((ConstraintViolationException) e.getCause()).getSQL().contains("opf_lookup")
            && ((ConstraintViolationException) e.getCause()).getSQLException().getMessage()
                    .startsWith("Duplicate entry");
}

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

@Transactional
@Override//ww w  . ja  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 ava  2 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')"),
        @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();
    }
}

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

@Override
public CommandProcessingResult allocateCashierToTeller(final Long tellerId, JsonCommand command) {
    try {//from  w w w  .j av  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   ww  w . j  av a 2 s  .c o 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//from  w ww . j a  v a2s  . c o 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 ww  .j a v  a2  s . c  om
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   w w w  . ja  v a2 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/*  ww  w.j  a  va2 s.  c o m*/
@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();
    }
}