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:com.gst.infrastructure.dataqueries.service.ReadWriteNonCoreDataServiceImpl.java

@Transactional
@Override/* ww w  .j ava 2 s . c  o m*/
public CommandProcessingResult createNewDatatableEntry(final String dataTableName, final Long appTableId,
        final String json) {
    try {
        final String appTable = queryForApplicationTableName(dataTableName);
        final CommandProcessingResult commandProcessingResult = checkMainResourceExistsWithinScope(appTable,
                appTableId);

        final List<ResultsetColumnHeaderData> columnHeaders = this.genericDataService
                .fillResultsetColumnHeaders(dataTableName);

        final Type typeOfMap = new TypeToken<Map<String, String>>() {
        }.getType();
        final Map<String, String> dataParams = this.fromJsonHelper.extractDataMap(typeOfMap, json);

        final String sql = getAddSql(columnHeaders, dataTableName, getFKField(appTable), appTableId,
                dataParams);

        this.jdbcTemplate.update(sql);

        return commandProcessingResult; //

    } catch (final DataAccessException dve) {
        final Throwable cause = dve.getCause();
        final Throwable realCause = dve.getMostSpecificCause();
        if (realCause.getMessage().contains("Duplicate entry")
                || cause.getMessage().contains("Duplicate entry")) {
            throw new PlatformDataIntegrityException("error.msg.datatable.entry.duplicate",
                    "An entry already exists for datatable `" + dataTableName
                            + "` and application table with identifier `" + appTableId + "`.",
                    "dataTableName", dataTableName, appTableId);
        } else if (realCause.getMessage().contains("doesn't have a default value")
                || cause.getMessage().contains("doesn't have a default value")) {
            throw new PlatformDataIntegrityException(
                    "error.msg.datatable.no.value.provided.for.required.fields",
                    "No values provided for the datatable `" + dataTableName
                            + "` and application table with identifier `" + appTableId + "`.",
                    "dataTableName", dataTableName, appTableId);
        }

        logAsErrorUnexpectedDataIntegrityException(dve);
        throw new PlatformDataIntegrityException("error.msg.unknown.data.integrity.issue",
                "Unknown data integrity issue with resource.");
    } catch (final PersistenceException e) {
        final Throwable cause = e.getCause();
        if (cause.getMessage().contains("Duplicate entry")) {
            throw new PlatformDataIntegrityException("error.msg.datatable.entry.duplicate",
                    "An entry already exists for datatable `" + dataTableName
                            + "` and application table with identifier `" + appTableId + "`.",
                    "dataTableName", dataTableName, appTableId);
        } else if (cause.getMessage().contains("doesn't have a default value")) {
            throw new PlatformDataIntegrityException(
                    "error.msg.datatable.no.value.provided.for.required.fields",
                    "No values provided for the datatable `" + dataTableName
                            + "` and application table with identifier `" + appTableId + "`.",
                    "dataTableName", dataTableName, appTableId);
        }

        logAsErrorUnexpectedDataIntegrityException(e);
        throw new PlatformDataIntegrityException("error.msg.unknown.data.integrity.issue",
                "Unknown data integrity issue with resource.");

    }
}

From source file:com.gst.infrastructure.dataqueries.service.ReadWriteNonCoreDataServiceImpl.java

@Transactional
@Override/*from w w  w. ja v a 2  s.  c  o  m*/
public void updateDatatable(final String datatableName, final JsonCommand command) {

    try {
        this.context.authenticatedUser();
        this.fromApiJsonDeserializer.validateForUpdate(command.json());

        final JsonElement element = this.fromJsonHelper.parse(command.json());
        final JsonArray changeColumns = this.fromJsonHelper.extractJsonArrayNamed("changeColumns", element);
        final JsonArray addColumns = this.fromJsonHelper.extractJsonArrayNamed("addColumns", element);
        final JsonArray dropColumns = this.fromJsonHelper.extractJsonArrayNamed("dropColumns", element);
        final String apptableName = this.fromJsonHelper.extractStringNamed("apptableName", element);

        validateDatatableName(datatableName);

        final List<ResultsetColumnHeaderData> columnHeaderData = this.genericDataService
                .fillResultsetColumnHeaders(datatableName);
        final Map<String, ResultsetColumnHeaderData> mapColumnNameDefinition = new HashMap<>();
        for (final ResultsetColumnHeaderData columnHeader : columnHeaderData) {
            mapColumnNameDefinition.put(columnHeader.getColumnName(), columnHeader);
        }

        final boolean isConstraintApproach = this.configurationDomainService
                .isConstraintApproachEnabledForDatatables();

        if (!StringUtils.isBlank(apptableName)) {
            validateAppTable(apptableName);

            final String oldApptableName = queryForApplicationTableName(datatableName);
            if (!StringUtils.equals(oldApptableName, apptableName)) {
                final String oldFKName = oldApptableName.substring(2) + "_id";
                final String newFKName = apptableName.substring(2) + "_id";
                final String actualAppTableName = mapToActualAppTable(apptableName);
                final String oldConstraintName = datatableName.toLowerCase().replaceAll("\\s", "_") + "_"
                        + oldFKName;
                final String newConstraintName = datatableName.toLowerCase().replaceAll("\\s", "_") + "_"
                        + newFKName;
                StringBuilder sqlBuilder = new StringBuilder();

                if (mapColumnNameDefinition.containsKey("id")) {
                    sqlBuilder = sqlBuilder.append("ALTER TABLE `" + datatableName + "` ")
                            .append("DROP KEY `fk_" + oldFKName + "`,")
                            .append("DROP FOREIGN KEY `fk_" + oldConstraintName + "`,")
                            .append("CHANGE COLUMN `" + oldFKName + "` `" + newFKName
                                    + "` BIGINT(20) NOT NULL,")
                            .append("ADD KEY `fk_" + newFKName + "` (`" + newFKName + "`),")
                            .append("ADD CONSTRAINT `fk_" + newConstraintName + "` ")
                            .append("FOREIGN KEY (`" + newFKName + "`) ")
                            .append("REFERENCES `" + actualAppTableName + "` (`id`)");
                } else {
                    sqlBuilder = sqlBuilder.append("ALTER TABLE `" + datatableName + "` ")
                            .append("DROP FOREIGN KEY `fk_" + oldConstraintName + "`,")
                            .append("CHANGE COLUMN `" + oldFKName + "` `" + newFKName
                                    + "` BIGINT(20) NOT NULL,")
                            .append("ADD CONSTRAINT `fk_" + newConstraintName + "` ")
                            .append("FOREIGN KEY (`" + newFKName + "`) ")
                            .append("REFERENCES `" + actualAppTableName + "` (`id`)");
                }

                this.jdbcTemplate.execute(sqlBuilder.toString());

                deregisterDatatable(datatableName);
                registerDatatable(datatableName, apptableName);
            }
        }

        if (changeColumns == null && addColumns == null && dropColumns == null) {
            return;
        }

        if (dropColumns != null) {

            StringBuilder sqlBuilder = new StringBuilder("ALTER TABLE `" + datatableName + "`");
            final StringBuilder constrainBuilder = new StringBuilder();
            final List<String> codeMappings = new ArrayList<>();
            for (final JsonElement column : dropColumns) {
                parseDatatableColumnForDrop(column.getAsJsonObject(), sqlBuilder, datatableName,
                        constrainBuilder, codeMappings);
            }

            // Remove the first comma, right after ALTER TABLE `datatable`
            final int indexOfFirstComma = sqlBuilder.indexOf(",");
            if (indexOfFirstComma != -1) {
                sqlBuilder = sqlBuilder.deleteCharAt(indexOfFirstComma);
            }
            sqlBuilder.append(constrainBuilder);
            this.jdbcTemplate.execute(sqlBuilder.toString());
            deleteColumnCodeMapping(codeMappings);
        }
        if (addColumns != null) {

            StringBuilder sqlBuilder = new StringBuilder("ALTER TABLE `" + datatableName + "`");
            final StringBuilder constrainBuilder = new StringBuilder();
            final Map<String, Long> codeMappings = new HashMap<>();
            for (final JsonElement column : addColumns) {
                parseDatatableColumnForAdd(column.getAsJsonObject(), sqlBuilder,
                        datatableName.toLowerCase().replaceAll("\\s", "_"), constrainBuilder, codeMappings,
                        isConstraintApproach);
            }

            // Remove the first comma, right after ALTER TABLE `datatable`
            final int indexOfFirstComma = sqlBuilder.indexOf(",");
            if (indexOfFirstComma != -1) {
                sqlBuilder = sqlBuilder.deleteCharAt(indexOfFirstComma);
            }
            sqlBuilder.append(constrainBuilder);
            this.jdbcTemplate.execute(sqlBuilder.toString());
            registerColumnCodeMapping(codeMappings);
        }
        if (changeColumns != null) {

            StringBuilder sqlBuilder = new StringBuilder("ALTER TABLE `" + datatableName + "`");
            final StringBuilder constrainBuilder = new StringBuilder();
            final Map<String, Long> codeMappings = new HashMap<>();
            final List<String> removeMappings = new ArrayList<>();
            for (final JsonElement column : changeColumns) {
                // remove NULL values from column where mandatory is true
                removeNullValuesFromStringColumn(datatableName, column.getAsJsonObject(),
                        mapColumnNameDefinition);

                parseDatatableColumnForUpdate(column.getAsJsonObject(), mapColumnNameDefinition, sqlBuilder,
                        datatableName, constrainBuilder, codeMappings, removeMappings, isConstraintApproach);
            }

            // Remove the first comma, right after ALTER TABLE `datatable`
            final int indexOfFirstComma = sqlBuilder.indexOf(",");
            if (indexOfFirstComma != -1) {
                sqlBuilder = sqlBuilder.deleteCharAt(indexOfFirstComma);
            }
            sqlBuilder.append(constrainBuilder);
            try {
                this.jdbcTemplate.execute(sqlBuilder.toString());
                deleteColumnCodeMapping(removeMappings);
                registerColumnCodeMapping(codeMappings);
            } catch (final Exception e) {
                if (e.getMessage().contains("Error on rename")) {
                    throw new PlatformServiceUnavailableException(
                            "error.msg.datatable.column.update.not.allowed",
                            "One of the column name modification not allowed");
                }
                // handle all other exceptions in here

                // check if exception message contains the
                // "invalid use of null value" SQL exception message
                // throw a 503 HTTP error -
                // PlatformServiceUnavailableException
                if (e.getMessage().toLowerCase().contains("invalid use of null value")) {
                    throw new PlatformServiceUnavailableException(
                            "error.msg.datatable.column.update.not.allowed",
                            "One of the data table columns contains null values");
                }
            }
        }
    } catch (final DataIntegrityViolationException e) {
        final Throwable realCause = e.getCause();
        final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
        final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
                .resource("datatable");

        if (realCause.getMessage().toLowerCase().contains("unknown column")) {
            baseDataValidator.reset().parameter("name").failWithCode("does.not.exist");
        } else if (realCause.getMessage().toLowerCase().contains("can't drop")) {
            baseDataValidator.reset().parameter("name").failWithCode("does.not.exist");
        } else if (realCause.getMessage().toLowerCase().contains("duplicate column")) {
            baseDataValidator.reset().parameter("name").failWithCode("column.already.exists");
        }

        throwExceptionIfValidationWarningsExist(dataValidationErrors);
    } catch (final PersistenceException ee) {
        Throwable realCause = ExceptionUtils.getRootCause(ee.getCause());
        final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
        final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
                .resource("datatable");
        if (realCause.getMessage().toLowerCase().contains("duplicate column name")) {
            baseDataValidator.reset().parameter("name").failWithCode("duplicate.column.name");
        } else if (realCause.getMessage().contains("Table")
                && realCause.getMessage().contains("already exists")) {
            baseDataValidator.reset().parameter("datatableName").value(datatableName)
                    .failWithCode("datatable.already.exists");
        } else if (realCause.getMessage().contains("Column") && realCause.getMessage().contains("big")) {
            baseDataValidator.reset().parameter("column").failWithCode("length.too.big");
        } else if (realCause.getMessage().contains("Row") && realCause.getMessage().contains("large")) {
            baseDataValidator.reset().parameter("row").failWithCode("size.too.large");
        }

        throwExceptionIfValidationWarningsExist(dataValidationErrors);
    }
}

From source file:org.apache.fineract.infrastructure.codes.service.CodeWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override//w w w.j  a v  a2 s  .c om
@CacheEvict(value = "codes", key = "T(org.apache.fineract.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:org.apache.fineract.infrastructure.codes.service.CodeWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override//from  w  ww  . j  a  va2s  .c o m
@CacheEvict(value = "codes", key = "T(org.apache.fineract.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:org.candlepin.resource.OwnerResource.java

/**
 * Removes an Owner//from   w w  w  .  ja  v a 2 s . co m
 *
 * @httpcode 404
 * @httpcode 200
 */
@DELETE
@Path("/{owner_key}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(notes = "Removes an Owner", value = "Delete Owner")
@ApiResponses({ @ApiResponse(code = 404, message = "Owner not found") })
public void deleteOwner(@PathParam("owner_key") String ownerKey,
        @QueryParam("revoke") @DefaultValue("true") boolean revoke) {
    Owner owner = findOwner(ownerKey);
    Event event = eventFactory.ownerDeleted(owner);

    try {
        ownerManager.cleanupAndDelete(owner, revoke);
    } catch (PersistenceException e) {
        if (e.getCause() instanceof ConstraintViolationException) {
            throw new ConflictException(e.getMessage(), e);
        } else {
            throw e;
        }
    }

    sink.queueEvent(event);
}

From source file:org.eclipse.jubula.client.core.persistence.Persistor.java

/**
 * @param s/*from  w ww  .j av  a 2 s.  co  m*/
 *            session, which contain the current persistent object
 * @param po
 *            object to delete
 * @throws PMException
 *             in case of failed rollback
 * @throws PMAlreadyLockedException
 *             in case of locked object
 * @throws PMDirtyVersionException
 *             in case of version conflict
 * @throws ProjectDeletedException
 *             if the project was deleted in another instance
 * @throws InterruptedException
 *             if the oepration was canceled
 */
public void deletePO(EntityManager s, IPersistentObject po) throws PMException, PMAlreadyLockedException,
        PMDirtyVersionException, ProjectDeletedException, InterruptedException {

    Validate.notNull(s);
    try {
        s.remove(po);
    } catch (PersistenceException e) {
        if (e.getCause() instanceof InterruptedException) {
            // Operation was canceled.
            throw new InterruptedException();
        }

        PersistenceManager.handleDBExceptionForMasterSession(po, e);
    }
}

From source file:org.eclipse.jubula.client.core.persistence.ProjectPM.java

/**
 * Check if the cause of the PersistenceException was a 
 * OperationCanceledException//from   w  ww.  j  a  v a2s  .  co m
 * @param e origonal exception
 * @return instance of OperationCanceledException if e was cause by it or
 * null.
 */
private static OperationCanceledException checkForCancel(PersistenceException e) {
    Throwable cause = e.getCause();
    while (cause != null) {
        if (cause instanceof OperationCanceledException) {
            return (OperationCanceledException) cause;
        }
        cause = cause.getCause();
    }
    return null;
}

From source file:org.eclipse.jubula.client.core.persistence.ProjectPM.java

/**
 * Handles a <code>PersistenceException</code>.
 * //from www.j  a v a 2  s .  c om
 * @param mapperList The Parameter Name mapping list.
 * @param s The session.
 * @param tx The transaction.
 * @param e The exception.
 * @throws PMException if the rollback of the transaction fails.
 * @throws InterruptedException if the cause of the given exception was 
 *                              that the operation was canceled.
 * @throws PMSaveException wrapper for the Persistence exception.
 */
private static void handlePersistenceException(List<INameMapper> mapperList, EntityManager s,
        EntityTransaction tx, PersistenceException e)
        throws PMException, InterruptedException, PMSaveException {

    if (tx != null) {
        Persistor.instance().rollbackTransaction(s, tx);
    }
    if (e.getCause() instanceof InterruptedException) {

        GeneralStorage.getInstance().reset();
        for (INameMapper mapper : mapperList) {
            mapper.clearAllNames();
        }
        // Operation was canceled.
        throw new InterruptedException();
    }
    String msg = Messages.CantAttachProject + StringConstants.DOT;
    throw new PMSaveException(msg + e.getMessage(), MessageIDs.E_ATTACH_PROJECT);
}

From source file:org.eclipse.jubula.client.core.persistence.ProjectPM.java

/**
 * Persists the given project to the DB. This is performed in a new session.
 * When this method returns, the project will not be attached to any session.
 * @param proj ProjectPO to be saved.//from  ww w .  j a  v a2  s  .  c  o  m
 * @param newProjectName
 *            name part of the ProjectNamePO. If there is no new name, this
 *            parameter must be null (same project, different version)
 * @param mapperList a List of INameMapper to persist names (Parameter).
 * @param compNameBindingList a List of Component Name mappers to persist 
 *                            names (Component).
 * @throws PMException in case of any db error
 * @throws ProjectDeletedException if project is already deleted
 * @throws InterruptedException if the operation is canceled
 */
public static void saveProject(IProjectPO proj, String newProjectName, List<INameMapper> mapperList,
        List<IWritableComponentNameMapper> compNameBindingList)
        throws PMException, ProjectDeletedException, InterruptedException {

    final EntityManager saveSession = Persistor.instance().openSession();
    EntityTransaction tx = null;
    try {
        tx = Persistor.instance().getTransaction(saveSession);

        saveSession.persist(proj);
        proj.setParentProjectId(proj.getId());

        saveSession.flush();
        if (newProjectName != null) {
            ProjectNameBP.getInstance().setName(saveSession, proj.getGuid(), newProjectName);
        }
        ProjectNameBP.getInstance().storeTransientNames(saveSession);
        for (INameMapper mapper : mapperList) {
            mapper.persist(saveSession, proj.getId());
        }
        for (IWritableComponentNameMapper compNameBinding : compNameBindingList) {
            CompNamePM.flushCompNames(saveSession, proj.getId(), compNameBinding);
        }
        Persistor.instance().commitTransaction(saveSession, tx);
        for (INameMapper mapper : mapperList) {
            mapper.updateStandardMapperAndCleanup(proj.getId());
        }
        for (IComponentNameMapper compNameCache : compNameBindingList) {
            compNameCache.getCompNameCache().updateStandardMapperAndCleanup(proj.getId());
        }
    } catch (PersistenceException e) {
        if (tx != null) {
            Persistor.instance().rollbackTransaction(saveSession, tx);
        }
        if (e.getCause() instanceof InterruptedException) {
            // Operation was canceled.
            throw new InterruptedException();
        }
        String msg = Messages.CantSaveProject + StringConstants.DOT;
        throw new PMSaveException(msg + e.getMessage(), MessageIDs.E_ATTACH_PROJECT);
    } catch (IncompatibleTypeException ite) {
        if (tx != null) {
            Persistor.instance().rollbackTransaction(saveSession, tx);
        }
        String msg = Messages.CantSaveProject + StringConstants.DOT;
        throw new PMSaveException(msg + ite.getMessage(), MessageIDs.E_ATTACH_PROJECT);
    } finally {
        Persistor.instance().dropSession(saveSession);
    }
}

From source file:org.opens.urlmanager.inhibitor.AEPersistenceInhibitor.java

public void inhibitPersistenceException(PersistenceException e) {
    LogFactory.getLog(AEPersistenceInhibitor.class).debug("Inhibiting persistence exception", e);
    if (e.getCause() instanceof ConstraintViolationException) {
        // TODO : create the appropriate exception with its appropriate HTTP error code
        throw new InternalErrorException("Constraint violation exception", e);
    } else if (e.getCause() instanceof SQLGrammarException) {
        throw new InternalErrorException("SQL grammar error", e);
    } else {//from  ww w  .j a  v a2  s  . c  o m
        throw new InternalErrorException("Persistence error : " + e.getMessage(), e);
    }
}