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.useradministration.service.RoleWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override//w  w  w.  j ava 2s . c om
public CommandProcessingResult createRole(final JsonCommand command) {

    try {
        this.context.authenticatedUser();

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

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

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

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

@Transactional
@Override//from  w  w  w  .  j  a  va 2  s  .com
public CommandProcessingResult addClientIdentifier(final Long clientId, final JsonCommand command) {

    this.context.authenticatedUser();
    final ClientIdentifierCommand clientIdentifierCommand = this.clientIdentifierCommandFromApiJsonDeserializer
            .commandFromApiJson(command.json());
    clientIdentifierCommand.validateForCreate();

    final String documentKey = clientIdentifierCommand.getDocumentKey();
    String documentTypeLabel = null;
    Long documentTypeId = null;
    try {
        final Client client = this.clientRepository.findOneWithNotFoundDetection(clientId);

        final CodeValue documentType = this.codeValueRepository
                .findOneWithNotFoundDetection(clientIdentifierCommand.getDocumentTypeId());
        documentTypeId = documentType.getId();
        documentTypeLabel = documentType.label();

        final ClientIdentifier clientIdentifier = ClientIdentifier.fromJson(client, documentType, command);

        this.clientIdentifierRepository.save(clientIdentifier);

        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withOfficeId(client.officeId()) //
                .withClientId(clientId) //
                .withEntityId(clientIdentifier.getId()) //
                .build();
    } catch (final DataIntegrityViolationException dve) {
        handleClientIdentifierDataIntegrityViolation(documentTypeLabel, documentTypeId, documentKey,
                dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleClientIdentifierDataIntegrityViolation(documentTypeLabel, documentTypeId, documentKey, throwable,
                dve);
        return CommandProcessingResult.empty();
    }
}

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

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

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

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

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

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

From source file:com.gst.portfolio.charge.service.ChargeWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*  www  . j  a va  2 s  .  c  o  m*/
@CacheEvict(value = "charges", key = "T(com.gst.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:com.gst.portfolio.client.service.ClientIdentifierWritePlatformServiceJpaRepositoryImpl.java

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

    this.context.authenticatedUser();
    final ClientIdentifierCommand clientIdentifierCommand = this.clientIdentifierCommandFromApiJsonDeserializer
            .commandFromApiJson(command.json());
    clientIdentifierCommand.validateForUpdate();

    String documentTypeLabel = null;
    String documentKey = null;
    Long documentTypeId = clientIdentifierCommand.getDocumentTypeId();
    try {
        CodeValue documentType = null;

        final Client client = this.clientRepository.findOneWithNotFoundDetection(clientId);
        final ClientIdentifier clientIdentifierForUpdate = this.clientIdentifierRepository
                .findOne(identifierId);
        if (clientIdentifierForUpdate == null) {
            throw new ClientIdentifierNotFoundException(identifierId);
        }

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

        if (changes.containsKey("documentTypeId")) {
            documentType = this.codeValueRepository.findOneWithNotFoundDetection(documentTypeId);
            if (documentType == null) {
                throw new CodeValueNotFoundException(documentTypeId);
            }

            documentTypeId = documentType.getId();
            documentTypeLabel = documentType.label();
            clientIdentifierForUpdate.update(documentType);
        }

        if (changes.containsKey("documentTypeId") && changes.containsKey("documentKey")) {
            documentTypeId = clientIdentifierCommand.getDocumentTypeId();
            documentKey = clientIdentifierCommand.getDocumentKey();
        } else if (changes.containsKey("documentTypeId") && !changes.containsKey("documentKey")) {
            documentTypeId = clientIdentifierCommand.getDocumentTypeId();
            documentKey = clientIdentifierForUpdate.documentKey();
        } else if (!changes.containsKey("documentTypeId") && changes.containsKey("documentKey")) {
            documentTypeId = clientIdentifierForUpdate.documentTypeId();
            documentKey = clientIdentifierForUpdate.documentKey();
        }

        if (!changes.isEmpty()) {
            this.clientIdentifierRepository.saveAndFlush(clientIdentifierForUpdate);
        }

        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withOfficeId(client.officeId()) //
                .withClientId(clientId) //
                .withEntityId(identifierId) //
                .with(changes) //
                .build();
    } catch (final DataIntegrityViolationException dve) {
        handleClientIdentifierDataIntegrityViolation(documentTypeLabel, documentTypeId, documentKey,
                dve.getMostSpecificCause(), dve);
        return new CommandProcessingResult(Long.valueOf(-1));
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleClientIdentifierDataIntegrityViolation(documentTypeLabel, documentTypeId, documentKey, throwable,
                dve);
        return CommandProcessingResult.empty();
    }
}

From source file:com.gst.accounting.rule.service.AccountingRuleWritePlatformServiceJpaRepositoryImpl.java

/**
 * @param command/*from  w w  w  . j  a v  a2s .  c o  m*/
 * @param dve
 */
private void handleAccountingRuleIntegrityIssues(final JsonCommand command,
        final DataIntegrityViolationException dve) {
    final Throwable realCause = dve.getMostSpecificCause();
    if (realCause.getMessage().contains("accounting_rule_name_unique")) {
        throw new AccountingRuleDuplicateException(
                command.stringValueOfParameterNamed(AccountingRuleJsonInputParams.NAME.getValue()));
    } else if (realCause.getMessage().contains("UNIQUE_ACCOUNT_RULE_TAGS")) {
        throw new AccountingRuleDuplicateException();
    }

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

From source file:com.gst.infrastructure.hooks.service.HookWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override//from   w ww .j a  v  a  2 s  . c o  m
@CacheEvict(value = "hooks", allEntries = true)
public CommandProcessingResult createHook(final JsonCommand command) {

    try {
        this.context.authenticatedUser();

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

        final HookTemplate template = retrieveHookTemplateBy(
                command.stringValueOfParameterNamed(nameParamName));
        final String configJson = command.jsonFragment(configParamName);
        final Set<HookConfiguration> config = assembleConfig(command.mapValueOfParameterNamed(configJson),
                template);
        final JsonArray events = command.arrayOfParameterNamed(eventsParamName);
        final Set<HookResource> allEvents = assembleSetOfEvents(events);
        Template ugdTemplate = null;
        if (command.hasParameter(templateIdParamName)) {
            final Long ugdTemplateId = command.longValueOfParameterNamed(templateIdParamName);
            ugdTemplate = this.ugdTemplateRepository.findOne(ugdTemplateId);
            if (ugdTemplate == null) {
                throw new TemplateNotFoundException(ugdTemplateId);
            }
        }
        final Hook hook = Hook.fromJson(command, template, config, allEvents, ugdTemplate);

        validateHookRules(template, config, allEvents);

        this.hookRepository.save(hook);

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

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

@Transactional
@Override/*  w  w  w. j  ava2  s.c om*/
public CommandProcessingResult createLoanProduct(final JsonCommand command) {

    try {

        this.context.authenticatedUser();

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

        final Fund fund = findFundByIdIfProvided(command.longValueOfParameterNamed("fundId"));

        final Long transactionProcessingStrategyId = command
                .longValueOfParameterNamed("transactionProcessingStrategyId");
        final LoanTransactionProcessingStrategy loanTransactionProcessingStrategy = findStrategyByIdIfProvided(
                transactionProcessingStrategyId);

        final String currencyCode = command.stringValueOfParameterNamed("currencyCode");
        final List<Charge> charges = assembleListOfProductCharges(command, currencyCode);

        FloatingRate floatingRate = null;
        if (command.parameterExists("floatingRatesId")) {
            floatingRate = this.floatingRateRepository
                    .findOneWithNotFoundDetection(command.longValueOfParameterNamed("floatingRatesId"));
        }
        final LoanProduct loanproduct = LoanProduct.assembleFromJson(fund, loanTransactionProcessingStrategy,
                charges, command, this.aprCalculator, floatingRate);
        loanproduct.updateLoanProductInRelatedClasses();

        this.loanProductRepository.save(loanproduct);

        // save accounting mappings
        this.accountMappingWritePlatformService.createLoanProductToGLAccountMapping(loanproduct.getId(),
                command);
        // 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_LOAN_PRODUCTS, loanproduct.getId());

        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withEntityId(loanproduct.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:com.gst.infrastructure.hooks.service.HookWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*ww  w .j av  a2s . c o m*/
@CacheEvict(value = "hooks", allEntries = true)
public CommandProcessingResult updateHook(final Long hookId, final JsonCommand command) {

    try {
        this.context.authenticatedUser();

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

        final Hook hook = retrieveHookBy(hookId);
        final HookTemplate template = hook.getHookTemplate();
        final Map<String, Object> changes = hook.update(command);

        if (!changes.isEmpty()) {

            if (changes.containsKey(templateIdParamName)) {
                final Long ugdTemplateId = command.longValueOfParameterNamed(templateIdParamName);
                final Template ugdTemplate = this.ugdTemplateRepository.findOne(ugdTemplateId);
                if (ugdTemplate == null) {
                    changes.remove(templateIdParamName);
                    throw new TemplateNotFoundException(ugdTemplateId);
                }
                hook.updateUgdTemplate(ugdTemplate);
            }

            if (changes.containsKey(eventsParamName)) {
                final Set<HookResource> events = assembleSetOfEvents(
                        command.arrayOfParameterNamed(eventsParamName));
                final boolean updated = hook.updateEvents(events);
                if (!updated) {
                    changes.remove(eventsParamName);
                }
            }

            if (changes.containsKey(configParamName)) {
                final String configJson = command.jsonFragment(configParamName);
                final Set<HookConfiguration> config = assembleConfig(
                        command.mapValueOfParameterNamed(configJson), template);
                final boolean updated = hook.updateConfig(config);
                if (!updated) {
                    changes.remove(configParamName);
                }
            }

            this.hookRepository.saveAndFlush(hook);
        }

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

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

@Transactional
@Override/*from  w w  w  .  java 2 s. c o  m*/
public CommandProcessingResult updateLoanProduct(final Long loanProductId, final JsonCommand command) {

    try {
        this.context.authenticatedUser();

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

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

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

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

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

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

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

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

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

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

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

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

}