Example usage for javax.persistence PersistenceException getCause

List of usage examples for javax.persistence PersistenceException getCause

Introduction

In this page you can find the example usage for javax.persistence PersistenceException 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:fr.xebia.demo.wicket.blog.service.GenericService.java

public void deleteById(Serializable id) throws ServiceException {
    try {/*from   w ww .j a  v a 2  s . c  o  m*/
        EntityManager entityManager = currentEntityManager();
        entityManager.getTransaction().begin();
        Object loadedEntity = entityManager.find(getObjectClass(), id);
        if (loadedEntity == null) {
            throw new ServiceException("Entity referenced by id " + id + " does not exist");
        }
        entityManager.remove(loadedEntity);
        commitTransaction();
    } catch (PersistenceException e) {
        logger.error(e.getCause(), e);
        rollbackTransaction();
        throw new ServiceException("Can't delete object", e);
    } finally {
        closeEntityManager();
    }
}

From source file:fr.xebia.demo.wicket.blog.service.GenericService.java

@SuppressWarnings("unchecked")
public List<T> search(final T exampleEntity) throws ServiceException {
    try {/*from  w  w w.j  a v a 2 s  . c o  m*/
        Validate.notNull(exampleEntity, "Example entity must not be null");
        logger.debug("Search: " + exampleEntity.toString());
        Session session = ((Session) currentEntityManager().getDelegate());
        Criteria criteria = session.createCriteria(getObjectClass());
        Example example = Example.create(exampleEntity);
        example.setPropertySelector(NOT_NULL_OR_EMPTY);
        example.ignoreCase();
        example.enableLike();
        logger.debug("Search example object: " + example.toString());
        criteria.add(example);
        criteria.setMaxResults(getMaxResults());
        criteria.setCacheable(true);
        return criteria.list();
    } catch (PersistenceException e) {
        logger.error(e.getCause(), e);
        throw new ServiceException("Can't search object list from database", e);
    } finally {
        closeEntityManager();
    }
}

From source file:fr.xebia.demo.wicket.blog.service.GenericService.java

public void delete(T entity) throws ServiceException {
    try {//from www. j  av a2s . co  m
        EntityManager entityManager = currentEntityManager();
        entityManager.getTransaction().begin();

        Serializable objectId = getObjectId(entity);
        if (objectId == null) {
            throw new ServiceException("Entity has no id");
        }
        T loadedEntity = entityManager.find(getObjectClass(), objectId);
        if (loadedEntity == null) {
            throw new ServiceException("Entity referenced by id " + objectId + " does not exist");
        }
        entityManager.remove(loadedEntity);

        commitTransaction();
    } catch (PersistenceException e) {
        logger.error(e.getCause(), e);
        rollbackTransaction();
        throw new ServiceException("Can't delete object", e);
    } finally {
        closeEntityManager();
    }
}

From source file:com.gst.portfolio.savings.service.FixedDepositProductWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*from  ww w.  j  a va2  s  . c  o m*/
public CommandProcessingResult update(final Long productId, final JsonCommand command) {

    try {
        this.context.authenticatedUser();
        this.fromApiJsonDataValidator.validateForFixedDepositUpdate(command.json());

        final FixedDepositProduct product = this.fixedDepositProductRepository.findOne(productId);
        if (product == null) {
            throw new FixedDepositProductNotFoundException(productId);
        }
        product.setHelpers(this.chartAssembler);

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

        if (changes.containsKey(chargesParamName)) {
            final Set<Charge> savingsProductCharges = this.depositProductAssembler
                    .assembleListOfSavingsProductCharges(command, product.currency().getCode());
            final boolean updated = product.update(savingsProductCharges);
            if (!updated) {
                changes.remove(chargesParamName);
            }
        }

        if (changes.containsKey(taxGroupIdParamName)) {
            final TaxGroup taxGroup = this.depositProductAssembler.assembleTaxGroup(command);
            product.setTaxGroup(taxGroup);
            if (product.withHoldTax() && product.getTaxGroup() == null) {
                final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
                final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
                        .resource(FIXED_DEPOSIT_PRODUCT_RESOURCE_NAME);
                final Long taxGroupId = null;
                baseDataValidator.reset().parameter(taxGroupIdParamName).value(taxGroupId).notBlank();
                throw new PlatformApiDataValidationException(dataValidationErrors);
            }
        }

        // accounting related changes
        final boolean accountingTypeChanged = changes.containsKey(accountingRuleParamName);
        final Map<String, Object> accountingMappingChanges = this.accountMappingWritePlatformService
                .updateSavingsProductToGLAccountMapping(product.getId(), command, accountingTypeChanged,
                        product.getAccountingType(), DepositAccountType.FIXED_DEPOSIT);
        changes.putAll(accountingMappingChanges);

        if (!changes.isEmpty()) {
            this.fixedDepositProductRepository.save(product);
        }

        return new CommandProcessingResultBuilder() //
                .withEntityId(product.getId()) //
                .with(changes).build();
    } catch (final DataAccessException e) {
        handleDataIntegrityIssues(command, e.getMostSpecificCause(), e);
        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.savings.service.RecurringDepositProductWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/* w  w  w. ja  va2s . c o m*/
public CommandProcessingResult update(final Long productId, final JsonCommand command) {

    try {
        this.context.authenticatedUser();
        this.fromApiJsonDataValidator.validateForRecurringDepositUpdate(command.json());

        final RecurringDepositProduct product = this.recurringDepositProductRepository.findOne(productId);
        if (product == null) {
            throw new RecurringDepositProductNotFoundException(productId);
        }
        product.setHelpers(this.chartAssembler);

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

        if (changes.containsKey(chargesParamName)) {
            final Set<Charge> savingsProductCharges = this.depositProductAssembler
                    .assembleListOfSavingsProductCharges(command, product.currency().getCode());
            final boolean updated = product.update(savingsProductCharges);
            if (!updated) {
                changes.remove(chargesParamName);
            }
        }

        if (changes.containsKey(taxGroupIdParamName)) {
            final TaxGroup taxGroup = this.depositProductAssembler.assembleTaxGroup(command);
            product.setTaxGroup(taxGroup);
            if (product.withHoldTax() && product.getTaxGroup() == null) {
                final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
                final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
                        .resource(RECURRING_DEPOSIT_PRODUCT_RESOURCE_NAME);
                final Long taxGroupId = null;
                baseDataValidator.reset().parameter(taxGroupIdParamName).value(taxGroupId).notBlank();
                throw new PlatformApiDataValidationException(dataValidationErrors);
            }
        }

        // accounting related changes
        final boolean accountingTypeChanged = changes.containsKey(accountingRuleParamName);
        final Map<String, Object> accountingMappingChanges = this.accountMappingWritePlatformService
                .updateSavingsProductToGLAccountMapping(product.getId(), command, accountingTypeChanged,
                        product.getAccountingType(), DepositAccountType.RECURRING_DEPOSIT);
        changes.putAll(accountingMappingChanges);

        if (!changes.isEmpty()) {
            this.recurringDepositProductRepository.save(product);
        }

        return new CommandProcessingResultBuilder() //
                .withEntityId(product.getId()) //
                .with(changes).build();
    } catch (final DataAccessException e) {
        handleDataIntegrityIssues(command, e.getMostSpecificCause(), e);
        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.savings.service.SavingsProductWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/* ww  w .jav a  2  s  .  com*/
public CommandProcessingResult update(final Long productId, final JsonCommand command) {

    try {
        this.context.authenticatedUser();
        final SavingsProduct product = this.savingProductRepository.findOne(productId);
        if (product == null) {
            throw new SavingsProductNotFoundException(productId);
        }

        this.fromApiJsonDataValidator.validateForUpdate(command.json(), product);

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

        if (changes.containsKey(chargesParamName)) {
            final Set<Charge> savingsProductCharges = this.savingsProductAssembler
                    .assembleListOfSavingsProductCharges(command, product.currency().getCode());
            final boolean updated = product.update(savingsProductCharges);
            if (!updated) {
                changes.remove(chargesParamName);
            }
        }

        if (changes.containsKey(taxGroupIdParamName)) {
            final TaxGroup taxGroup = this.savingsProductAssembler.assembleTaxGroup(command);
            product.setTaxGroup(taxGroup);
            if (product.withHoldTax() && product.getTaxGroup() == null) {
                final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
                final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
                        .resource(SAVINGS_PRODUCT_RESOURCE_NAME);
                final Long taxGroupId = null;
                baseDataValidator.reset().parameter(taxGroupIdParamName).value(taxGroupId).notBlank();
                throw new PlatformApiDataValidationException(dataValidationErrors);
            }
        }

        // accounting related changes
        final boolean accountingTypeChanged = changes.containsKey(accountingRuleParamName);
        final Map<String, Object> accountingMappingChanges = this.accountMappingWritePlatformService
                .updateSavingsProductToGLAccountMapping(product.getId(), command, accountingTypeChanged,
                        product.getAccountingType(), DepositAccountType.SAVINGS_DEPOSIT);
        changes.putAll(accountingMappingChanges);

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

        return new CommandProcessingResultBuilder() //
                .withEntityId(product.getId()) //
                .with(changes).build();
    } catch (final DataAccessException e) {
        handleDataIntegrityIssues(command, e.getMostSpecificCause(), e);
        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.EntityDatatableChecksWritePlatformServiceImpl.java

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

    try {
        this.context.authenticatedUser();

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

        // check if the datatable is linked to the entity

        String datatableName = command.stringValueOfParameterNamed("datatableName");
        DatatableData datatableData = this.readWriteNonCoreDataService.retrieveDatatable(datatableName);

        if (datatableData == null) {
            throw new DatatableNotFoundException(datatableName);
        }

        final String entity = command.stringValueOfParameterNamed("entity");
        final String foreignKeyColumnName = EntityTables.getForeignKeyColumnNameOnDatatable(entity);
        final boolean columnExist = datatableData.hasColumn(foreignKeyColumnName);

        logger.info(datatableData.getRegisteredTableName() + "has column " + foreignKeyColumnName + " ? "
                + columnExist);

        if (!columnExist) {
            throw new EntityDatatableCheckNotSupportedException(datatableData.getRegisteredTableName(), entity);
        }

        final Long productId = command.longValueOfParameterNamed("productId");
        final Long status = command.longValueOfParameterNamed("status");

        List<EntityDatatableChecks> entityDatatableCheck = null;
        if (productId == null) {
            entityDatatableCheck = this.entityDatatableChecksRepository
                    .findByEntityStatusAndDatatableIdAndNoProduct(entity, status, datatableName);
            if (!entityDatatableCheck.isEmpty()) {
                throw new EntityDatatableCheckAlreadyExistsException(entity, status, datatableName);
            }
        } else {
            if (entity.equals("m_loan")) {
                // if invalid loan product id, throws exception
                this.loanProductReadPlatformService.retrieveLoanProduct(productId);
            } else if (entity.equals("m_savings_account")) {
                // if invalid savings product id, throws exception
                this.savingsProductReadPlatformService.retrieveOne(productId);
            } else {
                throw new EntityDatatableCheckNotSupportedException(entity, productId);
            }
            entityDatatableCheck = this.entityDatatableChecksRepository
                    .findByEntityStatusAndDatatableIdAndProductId(entity, status, datatableName, productId);
            if (!entityDatatableCheck.isEmpty()) {
                throw new EntityDatatableCheckAlreadyExistsException(entity, status, datatableName, productId);
            }
        }

        final EntityDatatableChecks check = EntityDatatableChecks.fromJson(command);

        this.entityDatatableChecksRepository.saveAndFlush(check);

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

From source file:org.tomitribe.tribestream.registryng.repository.Repository.java

public OpenApiDocument insert(final Swagger swagger) {

    final OpenApiDocument document = new OpenApiDocument();
    document.setName(swagger.getInfo().getTitle());
    document.setVersion(swagger.getInfo().getVersion());

    final Swagger clone = createShallowCopy(swagger);
    clone.setPaths(null);/*from  w  ww  .  j  a v  a  2s .co  m*/
    document.setSwagger(clone);

    final String username = getUser();

    Date now = new Date();
    document.setCreatedAt(now);
    document.setUpdatedAt(now);
    document.setCreatedBy(username);
    document.setUpdatedBy(username);
    em.persist(document);
    try {
        em.flush();
    } catch (PersistenceException e) {
        if (e.getCause() != null && ConstraintViolationException.class.isInstance(e.getCause())) {
            throw new DuplicatedSwaggerException(e);
        } else {
            throw e;
        }
    }

    // Store the endpoints in a separate table
    if (swagger.getPaths() != null) {
        for (Map.Entry<String, Path> stringPathEntry : swagger.getPaths().entrySet()) {
            final String path = stringPathEntry.getKey();
            final Path pathObject = stringPathEntry.getValue();
            for (Map.Entry<HttpMethod, Operation> httpMethodOperationEntry : pathObject.getOperationMap()
                    .entrySet()) {
                final String verb = httpMethodOperationEntry.getKey().name().toUpperCase();
                final Operation operation = httpMethodOperationEntry.getValue();

                Endpoint endpoint = new Endpoint();
                endpoint.setApplication(document);
                endpoint.setPath(path);
                endpoint.setVerb(verb);
                endpoint.setOperation(operation);

                em.persist(endpoint);
                em.flush();
                searchEngine.indexEndpoint(endpoint);
            }
        }
    } else {
        searchEngine.indexApplication(document);
    }

    return document;
}

From source file:net.navasoft.madcoin.backend.model.controller.impl.AcceptingProviderDataAccess.java

/**
 * Creates the./*www  .j  av a 2 s  . c  om*/
 * 
 * @param workRequestsXServiceProviders
 *            the work requests x service providers
 * @return the work requests x service providers
 * @throws PreexistingEntityException
 *             the preexisting entity exception
 * @since 2/09/2014, 09:31:45 PM
 */
@Override
@Transactional(propagation = Propagation.REQUIRED)
public WorkRequestsXServiceProviders create(WorkRequestsXServiceProviders workRequestsXServiceProviders)
        throws PreexistingEntityException {
    try {
        preConstruct(workRequestsXServiceProviders);
        entityManager.persist(workRequestsXServiceProviders);
        workRequestsXServiceProviders = getByLogicalId(
                workRequestsXServiceProviders.getWorkRequestsXServiceProvidersPK());
        postConstruct(workRequestsXServiceProviders);
        storage.clean();
        return workRequestsXServiceProviders;
    } catch (PersistenceException e) {
        throw new AlreadyOnSourceException(e.getCause().getCause().getMessage());
    }
}

From source file:net.navasoft.madcoin.backend.model.controller.impl.EndUsersDataAccess.java

/**
 * Creates the./*w  w w.j  av a  2 s .c  o  m*/
 * 
 * @param entity
 *            the entity
 * @return the end users
 * @since 2/09/2014, 09:31:48 PM
 */
@Override
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { RollbackException.class,
        ConstraintViolationException.class, JDBCException.class })
public EndUsers create(EndUsers entity) {
    try {
        AppUsers super_user = new AppUsers();
        super_user.setCreatedOn(Calendar.getInstance().getTime());
        super_user = appUsersDao.create(super_user);
        AppUserXStatus statusRef = new AppUserXStatus();
        statusRef.setIdUser(super_user);
        statusRef.setIdUserStatus(new UserStatus(7));
        statusRef = userStatusDao.create(statusRef);
        entity.getEndUsersPK().setIdEndUser(super_user.getIdApplicationUsers());
        entity.setAppUsers(super_user);
        preConstruct(entity);
        entityManager.persist(entity);
        entityManager.flush();
        entity = getByLogicalId(entity.getNormalizedId());
        postConstruct(entity);
    } catch (PersistenceException e) {
        throw new AlreadyOnSourceException(e.getCause().getCause().getMessage());
    } catch (PreexistingEntityException e) {
        throw new AlreadyOnSourceException(e.getMessage());
    }
    return entity;
}