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.CommentService.java

@SuppressWarnings("unchecked")
public List<Comment> getCommentsForPostId(Long postId) throws ServiceException {
    try {//w  w  w  .  j a va2 s  .com
        Session session = ((Session) currentEntityManager().getDelegate());
        Criteria criteria = session.createCriteria(getObjectClass())
                .add(Expression.eq("approved", Boolean.TRUE)).add(Expression.eq("postId", postId))
                .addOrder(Order.desc("date")).setCacheable(false);
        return criteria.list();
    } catch (PersistenceException e) {
        logger.error(e.getCause(), e);
        throw new ServiceException("Can't get last posts", e);
    } finally {
        closeEntityManager();
    }
}

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

@SuppressWarnings("unchecked")
public List<Post> getLastPosts() throws ServiceException {
    try {/* w  w w.j  a  va  2s  .c  om*/
        Session session = ((Session) currentEntityManager().getDelegate());
        Criteria criteria = session.createCriteria(getObjectClass()).add(Expression.eq("status", "published"))
                .addOrder(Order.desc("date")).setMaxResults(POST_PER_PAGE).setCacheable(false);
        return criteria.list();
    } catch (PersistenceException e) {
        logger.error(e.getCause(), e);
        throw new ServiceException("Can't get last posts", e);
    } finally {
        closeEntityManager();
    }
}

From source file:org.appverse.web.framework.backend.persistence.services.integration.impl.test.UserRepositoryImplTest.java

@Override
@Test//from www .j av a  2 s . co  m
public void retrieveByFilter() throws Exception {
    UserDTO userDTORetrieved = userRepository.retrieve(userDTO);
    Assert.isNull(userDTORetrieved);
    persist();
    IntegrationDataFilter filter = new IntegrationDataFilter();
    filter.addStrictCondition("name", "name1");
    try {
        userDTORetrieved = userRepository.retrieve(filter);
    } catch (PersistenceException e) {
        if (!(e.getCause() instanceof NoResultException)) {
            throw e;
        }
    }
    Assert.isNull(userDTORetrieved);
    filter = new IntegrationDataFilter();
    filter.addStrictCondition("name", "name");
    userDTORetrieved = userRepository.retrieve(filter);
    Assert.notNull(userDTORetrieved);

}

From source file:com.gst.infrastructure.codes.service.CodeWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*www . j  a  va 2  s . c  om*/
@CacheEvict(value = "codes", key = "T(com.gst.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat('cv')")
public CommandProcessingResult createCode(final JsonCommand command) {

    try {
        this.context.authenticatedUser();

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

        final Code code = Code.fromJson(command);
        this.codeRepository.save(code);

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

From source file:com.gst.infrastructure.codes.service.CodeWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override//from   w  w  w  .j a  v a  2s . c  o m
@CacheEvict(value = "codes", key = "T(com.gst.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat('cv')")
public CommandProcessingResult updateCode(final Long codeId, final JsonCommand command) {

    try {
        this.context.authenticatedUser();

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

        final Code code = retrieveCodeBy(codeId);
        final Map<String, Object> changes = code.update(command);

        if (!changes.isEmpty()) {
            this.codeRepository.save(code);
        }

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

From source file:com.gst.infrastructure.accountnumberformat.service.AccountNumberFormatWritePlatformServiceJpaRepositoryImpl.java

@Override
@Transactional//from   ww w.  j a  v  a 2  s  . com
public CommandProcessingResult createAccountNumberFormat(JsonCommand command) {
    try {
        this.accountNumberFormatDataValidator.validateForCreate(command.json());

        final Integer accountTypeId = command
                .integerValueSansLocaleOfParameterNamed(AccountNumberFormatConstants.accountTypeParamName);
        final EntityAccountType entityAccountType = EntityAccountType.fromInt(accountTypeId);

        final Integer prefixTypeId = command
                .integerValueSansLocaleOfParameterNamed(AccountNumberFormatConstants.prefixTypeParamName);
        AccountNumberPrefixType accountNumberPrefixType = null;
        if (prefixTypeId != null) {
            accountNumberPrefixType = AccountNumberPrefixType.fromInt(prefixTypeId);
        }

        AccountNumberFormat accountNumberFormat = new AccountNumberFormat(entityAccountType,
                accountNumberPrefixType);

        this.accountNumberFormatRepository.save(accountNumberFormat);

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

From source file:com.gst.infrastructure.accountnumberformat.service.AccountNumberFormatWritePlatformServiceJpaRepositoryImpl.java

@Override
@Transactional/*  w w  w  .j a  va2 s.  c  o m*/
public CommandProcessingResult updateAccountNumberFormat(Long accountNumberFormatId, JsonCommand command) {
    try {

        final AccountNumberFormat accountNumberFormatForUpdate = this.accountNumberFormatRepository
                .findOneWithNotFoundDetection(accountNumberFormatId);
        EntityAccountType accountType = accountNumberFormatForUpdate.getAccountType();

        this.accountNumberFormatDataValidator.validateForUpdate(command.json(), accountType);

        final Map<String, Object> actualChanges = new LinkedHashMap<>(9);

        if (command.isChangeInIntegerSansLocaleParameterNamed(AccountNumberFormatConstants.prefixTypeParamName,
                accountNumberFormatForUpdate.getPrefixEnum())) {
            final Integer newValue = command
                    .integerValueSansLocaleOfParameterNamed(AccountNumberFormatConstants.prefixTypeParamName);
            final AccountNumberPrefixType accountNumberPrefixType = AccountNumberPrefixType.fromInt(newValue);
            actualChanges.put(AccountNumberFormatConstants.prefixTypeParamName, accountNumberPrefixType);
            accountNumberFormatForUpdate.setPrefix(accountNumberPrefixType);
        }

        if (!actualChanges.isEmpty()) {
            this.accountNumberFormatRepository.saveAndFlush(accountNumberFormatForUpdate);
        }

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

From source file:com.healthcit.cacure.web.controller.question.ExternalQuestionElementEditController.java

/**
 * Process data entered by user//from   ww  w .j  a v a2s  . c  om
 * @param question
 * @param formId
 * @return
 */
@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.POST)
public ModelAndView onSubmit(@ModelAttribute(COMMAND_NAME) ExternalQuestionElement qElement,
        BindingResult result, @ModelAttribute(LOOKUP_DATA) Map lookupData, SessionStatus status,
        HttpServletRequest req) {

    validateEditOperation(qElement);

    log.debug("QuestionElement: " + qElement.toString());

    log.debug(qElement.toString());

    Long formId;
    try {
        if (qElement.isNew()) {
            formId = getFormId();
            qElement = (ExternalQuestionElement) qaManager.addNewFormElement(qElement, formId);
        } else {
            formId = qElement.getForm().getId();
            qElement = (ExternalQuestionElement) qaManager.updateFormElement(qElement);

        }

    } catch (PersistenceException e) {
        Throwable t = e.getCause();
        if (t instanceof GenericJDBCException) {
            String message = ((GenericJDBCException) t).getSQLException().getNextException().getMessage();
            if (message.indexOf("short name already exists") > -1) {
                result.rejectValue("question.shortName", "notunique.shortName", "Short name is not unique");
                return new ModelAndView("questionEdit");
            } else {
                throw e;
            }
        } else {
            throw e;
        }
    }
    qElement.setCategories(prepareCategories(req, lookupData));
    //      TODO Save 2 times is not good idea. We clear constraints by second update (see implementation)
    //      Changes to attached to session object save automatically. So categories are seved
    //      qaManager.updateFormElement(qElement);

    // after question is saved - return to question listing
    return new ModelAndView(new RedirectView(Constants.QUESTION_LISTING_URI + "?formId=" + formId, true));
}

From source file:com.gst.accounting.financialactivityaccount.service.FinancialActivityAccountWritePlatformServiceImpl.java

@Override
public CommandProcessingResult createFinancialActivityAccountMapping(JsonCommand command) {
    try {/*from w ww.  ja v a2  s  .com*/

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

        final Integer financialActivityId = command.integerValueSansLocaleOfParameterNamed(
                FinancialActivityAccountsJsonInputParams.FINANCIAL_ACTIVITY_ID.getValue());
        final Long accountId = command
                .longValueOfParameterNamed(FinancialActivityAccountsJsonInputParams.GL_ACCOUNT_ID.getValue());
        final GLAccount glAccount = glAccountRepositoryWrapper.findOneWithNotFoundDetection(accountId);
        FinancialActivityAccount financialActivityAccount = FinancialActivityAccount.createNew(glAccount,
                financialActivityId);

        validateFinancialActivityAndAccountMapping(financialActivityAccount);
        this.financialActivityAccountRepository.save(financialActivityAccount);
        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withEntityId(financialActivityAccount.getId()) //
                .build();
    } catch (DataIntegrityViolationException dataIntegrityViolationException) {
        handleFinancialActivityAccountDataIntegrityIssues(command,
                dataIntegrityViolationException.getMostSpecificCause(), dataIntegrityViolationException);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException ee) {
        Throwable throwable = ExceptionUtils.getRootCause(ee.getCause());
        handleFinancialActivityAccountDataIntegrityIssues(command, throwable, ee);
        return CommandProcessingResult.empty();
    }
}

From source file:com.healthcit.cacure.web.controller.question.TableElementEditController.java

/**
 * Process data entered by user/*from  w  ww  .  ja v  a 2  s .c  o  m*/
 * @param question
 * @param formId
 * @return
 */
@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.POST)
public ModelAndView onSubmit(@ModelAttribute(COMMAND_NAME) TableElement table, BindingResult result,
        @ModelAttribute(LOOKUP_DATA) Map lookupData, SessionStatus status, HttpServletRequest req) {

    validateEditOperation(table);
    boolean isNew = table.isNew();
    Long formId = null;

    try {
        if (table.isNew()) {
            formId = getFormId();
            qaManager.addNewFormElement(table, formId);
        } else {
            qaManager.updateFormElement(table);
            formId = table.getForm().getId();
        }
    } catch (PersistenceException e) {
        Throwable t = e.getCause();
        if (t instanceof GenericJDBCException) {
            String message = ((GenericJDBCException) t).getSQLException().getNextException().getMessage();
            if (isNew) {
                table.resetId();
                table.getDescriptionList().clear();
            }
            if (message.indexOf("A table with the same short name already exists") > -1) {
                int beginIndex = message.indexOf('[');
                int endIndex = message.indexOf(']');
                String shortName = message.substring(beginIndex + 1, endIndex);
                Object[] params = { shortName };
                result.rejectValue("tableShortName", "notunique.shortName", params, "Short name is not unique");
                return new ModelAndView("questionTableEdit");
            }
            if (message.indexOf("A question with the same short name already exists") > -1) {
                int beginIndex = message.indexOf('[');
                int endIndex = message.indexOf(']');
                String shortName = message.substring(beginIndex + 1, endIndex);
                Object[] params = { shortName };
                result.reject("notunique.shortName", params, "Short name is not unique");
                return new ModelAndView("questionTableEdit");
            } else {
                throw e;
            }
        } else {
            throw e;
        }
    }

    table.setCategories(prepareCategories(req, lookupData));
    //      TODO Save 2 times is not good idea. We clear constraints by second update (see implementation)
    //      Changes to attached to session object save automatically. So categories are seved
    //      qaManager.updateFormElement(table);

    // after question is saved - return to question listing
    return new ModelAndView(new RedirectView(Constants.QUESTION_LISTING_URI + "?formId=" + formId, true));
}