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.infrastructure.dataqueries.service.ReportWritePlatformServiceImpl.java

@Transactional
@Override/*from w w w  .  j a  v a  2s  .c om*/
public CommandProcessingResult createReport(final JsonCommand command) {

    try {
        this.context.authenticatedUser();

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

        final Report report = Report.fromJson(command, this.readReportingService.getAllowedReportTypes());
        final Set<ReportParameterUsage> reportParameterUsages = assembleSetOfReportParameterUsages(report,
                command);
        report.update(reportParameterUsages);

        this.reportRepository.save(report);

        final Permission permission = new Permission("report", report.getReportName(), "READ");
        this.permissionRepository.save(permission);

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

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

@Transactional
@Override// ww w .  ja  va 2  s  .  c o  m
@CacheEvict(value = "charges", key = "T(com.gst.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:com.gst.infrastructure.dataqueries.service.ReportWritePlatformServiceImpl.java

@Transactional
@Override/*from  w w w .  j  a va 2  s  . c  om*/
public CommandProcessingResult updateReport(final Long reportId, final JsonCommand command) {

    try {
        this.context.authenticatedUser();

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

        final Report report = this.reportRepository.findOne(reportId);
        if (report == null) {
            throw new ReportNotFoundException(reportId);
        }

        final Map<String, Object> changes = report.update(command,
                this.readReportingService.getAllowedReportTypes());

        if (changes.containsKey("reportParameters")) {
            final Set<ReportParameterUsage> reportParameterUsages = assembleSetOfReportParameterUsages(report,
                    command);
            final boolean updated = report.update(reportParameterUsages);
            if (!updated) {
                changes.remove("reportParameters");
            }
        }

        if (!changes.isEmpty()) {
            this.reportRepository.saveAndFlush(report);
        }

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

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

@Transactional
@Override/*ww  w.  j a v a  2s . c  om*/
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.portfolio.charge.service.ChargeWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*  w  ww.  ja  v  a  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 www  .  j  ava 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.infrastructure.hooks.service.HookWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*from  w  w w. j  a  v a2  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:py.una.pol.karaku.controller.KarakuAdvancedController.java

/**
 * {@inheritDoc}//from   w  w w  .  j  a va2s  . co m
 * <p>
 * Esta implementacin captura las excepciones del tipo
 * {@link UniqueConstraintException} y las excepciones del tipo
 * {@link DataIntegrityViolationException} y intenta generar un mensaje de
 * error pertinente.
 * </p>
 * 
 */
@Override
public boolean handleException(final Exception e) {

    if (e instanceof UniqueConstraintException) {
        UniqueConstraintException unique = (UniqueConstraintException) e;
        if (unique.getFields().size() == 1) {
            String field = unique.getFields().get(0);
            controllerHelper.addWarnMessage(field, getMessage("FIELD_DUPLICATE"),
                    getMessage("FIELD_DUPLICATE_DETAIL"));
        }
        if (unique.getFields().size() > 1) {
            controllerHelper.addGlobalWarnMessage(getMessage("FIELDS_DUPLICATED"),
                    getMessage("FIELDS_DUPLICATED_DETAIL", unique.getFields().toArray()));
        }
        return true;

    } else if (e instanceof DataIntegrityViolationException) {

        // TODO: buscar una solucion mas generica para este caso, de
        // identificar excepciones causadas por constraints de foreign keys

        DataIntegrityViolationException integrityException = (DataIntegrityViolationException) e;

        /* controlar que su causa sea del tipo constraintException */
        if (integrityException.getCause() instanceof ConstraintViolationException) {

            /* controlar que el constraint sea de fk */
            ConstraintViolationException constraintException = (ConstraintViolationException) integrityException
                    .getCause();

            if (constraintException.getConstraintName().startsWith("fk")) {
                controllerHelper.createGlobalFacesMessage(FacesMessage.SEVERITY_WARN, "ENTITY_REQUIRED_DETAIL");
                return true;
            }
        }
    }
    return false;
}

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

@Transactional
@Override//from   ww  w .ja va 2 s .c o  m
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//from   www  .j  ava2 s  .  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();
    }
}