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

@Override
public CommandProcessingResult applyAddtionalShares(final Long accountId, JsonCommand jsonCommand) {
    try {/*from ww  w .j av a  2s  .c om*/
        ShareAccount account = this.shareAccountRepository.findOneWithNotFoundDetection(accountId);
        Map<String, Object> changes = this.accountDataSerializer.validateAndApplyAddtionalShares(jsonCommand,
                account);
        ShareAccountTransaction transaction = null;
        if (!changes.isEmpty()) {
            this.shareAccountRepository.save(account);
            transaction = (ShareAccountTransaction) changes
                    .get(ShareAccountApiConstants.additionalshares_paramname);
            transaction = account.getShareAccountTransaction(transaction);
            if (transaction != null) {
                changes.clear();
                changes.put(ShareAccountApiConstants.additionalshares_paramname, transaction.getId());
                Set<ShareAccountTransaction> transactions = new HashSet<>();
                transactions.add(transaction);
                this.journalEntryWritePlatformService
                        .createJournalEntriesForShares(populateJournalEntries(account, transactions));
            }
        }

        return new CommandProcessingResultBuilder() //
                .withCommandId(jsonCommand.commandId()) //
                .withEntityId(accountId) //
                .with(changes) //
                .build();
    } catch (final DataIntegrityViolationException dve) {
        handleDataIntegrityIssues(jsonCommand, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    }
}

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

@SuppressWarnings("unchecked")
@Override/* w w  w. jav a  2 s  . co m*/
public CommandProcessingResult approveAdditionalShares(Long accountId, JsonCommand jsonCommand) {

    try {
        ShareAccount account = this.shareAccountRepository.findOneWithNotFoundDetection(accountId);
        Map<String, Object> changes = this.accountDataSerializer.validateAndApproveAddtionalShares(jsonCommand,
                account);
        if (!changes.isEmpty()) {
            this.shareAccountRepository.save(account);
            ArrayList<Long> transactionIds = (ArrayList<Long>) changes
                    .get(ShareAccountApiConstants.requestedshares_paramname);
            Long totalSubscribedShares = new Long(0);
            if (transactionIds != null) {
                Set<ShareAccountTransaction> transactions = new HashSet<>();
                for (Long id : transactionIds) {
                    ShareAccountTransaction transaction = account.retrievePurchasedShares(id);
                    transactions.add(transaction);
                    totalSubscribedShares += transaction.getTotalShares();
                }
                this.journalEntryWritePlatformService
                        .createJournalEntriesForShares(populateJournalEntries(account, transactions));
            }
            if (!totalSubscribedShares.equals(new Long(0))) {
                ShareProduct shareProduct = account.getShareProduct();
                shareProduct.addSubscribedShares(totalSubscribedShares);
                this.shareProductRepository.save(shareProduct);
            }
        }
        return new CommandProcessingResultBuilder() //
                .withCommandId(jsonCommand.commandId()) //
                .withEntityId(accountId) //
                .with(changes) //
                .build();
    } catch (DataIntegrityViolationException dve) {
        handleDataIntegrityIssues(jsonCommand, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    }
}

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

@Override
public CommandProcessingResult approveShareAccount(Long accountId, JsonCommand jsonCommand) {

    try {/*from  w  ww . ja v  a2  s  . c o  m*/
        ShareAccount account = this.shareAccountRepository.findOneWithNotFoundDetection(accountId);
        Map<String, Object> changes = this.accountDataSerializer.validateAndApprove(jsonCommand, account);
        if (!changes.isEmpty()) {
            this.shareAccountRepository.save(account);
            final String noteText = jsonCommand.stringValueOfParameterNamed("note");
            if (StringUtils.isNotBlank(noteText)) {
                final Note note = Note.shareNote(account, noteText);
                changes.put("note", noteText);
                this.noteRepository.save(note);
            }
        }
        Set<ShareAccountTransaction> transactions = account.getShareAccountTransactions();
        Set<ShareAccountTransaction> journalTransactions = new HashSet<>();
        Long totalSubsribedShares = new Long(0);

        for (ShareAccountTransaction transaction : transactions) {
            if (transaction.isActive() && transaction.isPurchasTransaction()) {
                journalTransactions.add(transaction);
                totalSubsribedShares += transaction.getTotalShares();
            }
        }
        ShareProduct shareProduct = account.getShareProduct();
        shareProduct.addSubscribedShares(totalSubsribedShares);
        this.shareProductRepository.save(shareProduct);

        this.journalEntryWritePlatformService
                .createJournalEntriesForShares(populateJournalEntries(account, journalTransactions));
        return new CommandProcessingResultBuilder() //
                .withCommandId(jsonCommand.commandId()) //
                .withEntityId(accountId) //
                .with(changes) //
                .build();
    } catch (DataIntegrityViolationException dve) {
        handleDataIntegrityIssues(jsonCommand, dve.getMostSpecificCause(), 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) {/* w  ww .  j  a  v  a  2s .co  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.accounting.journalentry.service.JournalEntryWritePlatformServiceJpaRepositoryImpl.java

private void handleJournalEntryDataIntegrityIssues(final DataIntegrityViolationException dve) {
    final Throwable realCause = dve.getMostSpecificCause();
    logger.error(dve.getMessage(), dve);
    throw new PlatformDataIntegrityException("error.msg.glJournalEntry.unknown.data.integrity.issue",
            "Unknown data integrity issue with resource Journal Entry: " + realCause.getMessage());
}

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

@Transactional
@Override//from   w ww. j  a  va2 s .c  o m
public CommandProcessingResult activateClient(final Long clientId, final JsonCommand command) {
    try {
        this.fromApiJsonDeserializer.validateActivation(command);

        final Client client = this.clientRepository.findOneWithNotFoundDetection(clientId, true);
        validateParentGroupRulesBeforeClientActivation(client);
        final Locale locale = command.extractLocale();
        final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);
        final LocalDate activationDate = command.localDateValueOfParameterNamed("activationDate");

        runEntityDatatableCheck(clientId);

        final AppUser currentUser = this.context.authenticatedUser();
        client.activate(currentUser, fmt, activationDate);
        CommandProcessingResult result = openSavingsAccount(client, fmt);
        this.clientRepository.saveAndFlush(client);
        this.businessEventNotifierService.notifyBusinessEventWasExecuted(BUSINESS_EVENTS.CLIENTS_ACTIVATE,
                constructEntityMap(BUSINESS_ENTITY.CLIENT, client));
        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withOfficeId(client.officeId()) //
                .withClientId(clientId) //
                .withEntityId(clientId) //
                .withSavingsId(result.getSavingsId())//
                .setRollbackTransaction(result.isRollbackTransaction())//
                .build();
    } catch (final DataIntegrityViolationException dve) {
        handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    }
}

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

@Transactional
@Override//from   w w  w .  j av a  2s .  c  o 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();
    }
}

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

@Transactional
@Override/*  w w  w  . j a  v a  2  s .  c  o  m*/
public CommandProcessingResult closeClient(final Long clientId, final JsonCommand command) {
    try {

        final AppUser currentUser = this.context.authenticatedUser();
        this.fromApiJsonDeserializer.validateClose(command);

        final Client client = this.clientRepository.findOneWithNotFoundDetection(clientId);
        final LocalDate closureDate = command
                .localDateValueOfParameterNamed(ClientApiConstants.closureDateParamName);
        final Long closureReasonId = command
                .longValueOfParameterNamed(ClientApiConstants.closureReasonIdParamName);

        final CodeValue closureReason = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection(
                ClientApiConstants.CLIENT_CLOSURE_REASON, closureReasonId);

        if (ClientStatus.fromInt(client.getStatus()).isClosed()) {
            final String errorMessage = "Client is already closed.";
            throw new InvalidClientStateTransitionException("close", "is.already.closed", errorMessage);
        } else if (ClientStatus.fromInt(client.getStatus()).isUnderTransfer()) {
            final String errorMessage = "Cannot Close a Client under Transfer";
            throw new InvalidClientStateTransitionException("close", "is.under.transfer", errorMessage);
        }

        if (client.isNotPending() && client.getActivationLocalDate().isAfter(closureDate)) {
            final String errorMessage = "The client closureDate cannot be before the client ActivationDate.";
            throw new InvalidClientStateTransitionException("close", "date.cannot.before.client.actvation.date",
                    errorMessage, closureDate, client.getActivationLocalDate());
        }
        entityDatatableChecksWritePlatformService.runTheCheck(clientId, EntityTables.CLIENT.getName(),
                StatusEnum.CLOSE.getCode().longValue(),
                EntityTables.CLIENT.getForeignKeyColumnNameOnDatatable());

        final List<Loan> clientLoans = this.loanRepositoryWrapper.findLoanByClientId(clientId);
        for (final Loan loan : clientLoans) {
            final LoanStatusMapper loanStatus = new LoanStatusMapper(loan.status().getValue());
            if (loanStatus.isOpen() || loanStatus.isPendingApproval() || loanStatus.isAwaitingDisbursal()) {
                final String errorMessage = "Client cannot be closed because of non-closed loans.";
                throw new InvalidClientStateTransitionException("close", "loan.non-closed", errorMessage);
            } else if (loanStatus.isClosed() && loan.getClosedOnDate().after(closureDate.toDate())) {
                final String errorMessage = "The client closureDate cannot be before the loan closedOnDate.";
                throw new InvalidClientStateTransitionException("close", "date.cannot.before.loan.closed.date",
                        errorMessage, closureDate, loan.getClosedOnDate());
            } else if (loanStatus.isOverpaid()) {
                final String errorMessage = "Client cannot be closed because of overpaid loans.";
                throw new InvalidClientStateTransitionException("close", "loan.overpaid", errorMessage);
            }
        }
        final List<SavingsAccount> clientSavingAccounts = this.savingsRepositoryWrapper
                .findSavingAccountByClientId(clientId);

        for (final SavingsAccount saving : clientSavingAccounts) {
            if (saving.isActive() || saving.isSubmittedAndPendingApproval() || saving.isApproved()) {
                final String errorMessage = "Client cannot be closed because of non-closed savings account.";
                throw new InvalidClientStateTransitionException("close", "non-closed.savings.account",
                        errorMessage);
            }
        }

        client.close(currentUser, closureReason, closureDate.toDate());
        this.clientRepository.saveAndFlush(client);
        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withClientId(clientId) //
                .withEntityId(clientId) //
                .build();
    } catch (final DataIntegrityViolationException dve) {
        handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    }
}

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

private CommandProcessingResult updateGroupingType(final Long groupId, final JsonCommand command,
        final GroupTypes groupingType) {

    try {//from w ww . j  a va 2s. co m
        this.context.authenticatedUser();
        final Group groupForUpdate = this.groupRepository.findOneWithNotFoundDetection(groupId);
        final Long officeId = groupForUpdate.officeId();
        final Office groupOffice = groupForUpdate.getOffice();
        final String groupHierarchy = groupOffice.getHierarchy();

        this.context.validateAccessRights(groupHierarchy);

        final LocalDate activationDate = command
                .localDateValueOfParameterNamed(GroupingTypesApiConstants.activationDateParamName);

        validateOfficeOpeningDateisAfterGroupOrCenterOpeningDate(groupOffice, groupForUpdate.getGroupLevel(),
                activationDate);

        final Map<String, Object> actualChanges = groupForUpdate.update(command);

        if (actualChanges.containsKey(GroupingTypesApiConstants.staffIdParamName)) {
            final Long newValue = command.longValueOfParameterNamed(GroupingTypesApiConstants.staffIdParamName);

            Staff newStaff = null;
            if (newValue != null) {
                newStaff = this.staffRepository.findByOfficeHierarchyWithNotFoundDetection(newValue,
                        groupHierarchy);
            }
            groupForUpdate.updateStaff(newStaff);
        }

        final GroupLevel groupLevel = this.groupLevelRepository.findOne(groupForUpdate.getGroupLevel().getId());

        /*
         * Ignoring parentId param, if group for update is super parent.
         * TODO Need to check: Ignoring is correct or need throw unsupported
         * param
         */
        if (!groupLevel.isSuperParent()) {

            Long parentId = null;
            final Group presentParentGroup = groupForUpdate.getParent();

            if (presentParentGroup != null) {
                parentId = presentParentGroup.getId();
            }

            if (command.isChangeInLongParameterNamed(GroupingTypesApiConstants.centerIdParamName, parentId)) {

                final Long newValue = command
                        .longValueOfParameterNamed(GroupingTypesApiConstants.centerIdParamName);
                actualChanges.put(GroupingTypesApiConstants.centerIdParamName, newValue);
                Group newParentGroup = null;
                if (newValue != null) {
                    newParentGroup = this.groupRepository.findOneWithNotFoundDetection(newValue);

                    if (!newParentGroup.isOfficeIdentifiedBy(officeId)) {
                        final String errorMessage = "Group and parent group must have the same office";
                        throw new InvalidOfficeException("group", "attach.to.parent.group", errorMessage);
                    }
                    /*
                     * If Group is not super parent then validate group
                     * level's parent level is same as group parent's level
                     * this check makes sure new group is added at immediate
                     * next level in hierarchy
                     */

                    if (!groupForUpdate.getGroupLevel()
                            .isIdentifiedByParentId(newParentGroup.getGroupLevel().getId())) {
                        final String errorMessage = "Parent group's level is  not equal to child level's parent level ";
                        throw new InvalidGroupLevelException("add", "invalid.level", errorMessage);
                    }
                }

                groupForUpdate.setParent(newParentGroup);

                // Parent has changed, re-generate 'Hierarchy' as parent is
                // changed
                groupForUpdate.generateHierarchy();

            }
        }

        /*
         * final Set<Client> clientMembers = assembleSetOfClients(officeId,
         * command); List<String> changes =
         * groupForUpdate.updateClientMembersIfDifferent(clientMembers); if
         * (!changes.isEmpty()) {
         * actualChanges.put(GroupingTypesApiConstants
         * .clientMembersParamName, changes); }
         */

        this.groupRepository.saveAndFlush(groupForUpdate);

        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withOfficeId(groupForUpdate.officeId()) //
                .withGroupId(groupForUpdate.getId()) //
                .withEntityId(groupForUpdate.getId()) //
                .with(actualChanges) //
                .build();

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

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

@Transactional
@Override//from w w w .j av a 2 s  .  co 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 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();
    }
}