Example usage for javax.persistence PersistenceException PersistenceException

List of usage examples for javax.persistence PersistenceException PersistenceException

Introduction

In this page you can find the example usage for javax.persistence PersistenceException PersistenceException.

Prototype

public PersistenceException(Throwable cause) 

Source Link

Document

Constructs a new PersistenceException exception with the specified cause.

Usage

From source file:com.impetus.client.redis.RedisClient.java

@Override
public Object find(Class entityClass, Object key) {
    Object result = null;//from w  w  w.  j a  v  a  2  s.  c  om
    Object connection = getConnection();
    try {
        result = fetch(entityClass, key, connection, null);
    } catch (InstantiationException e) {
        logger.error("Error during find by key:", e);
        throw new PersistenceException(e);
    } catch (IllegalAccessException e) {
        logger.error("Error during find by key:", e);
        throw new PersistenceException(e);
    } finally {
        onCleanup(connection);
    }

    return result;
}

From source file:com.impetus.kundera.ejb.EntityManagerImpl.java

@Override
public final <E> E merge(E e) {
    if (e == null) {
        throw new IllegalArgumentException("Entity must not be null.");
    }/*from w  w  w .  j a va2s.c om*/

    // Validate
    metadataManager.validate(e.getClass());

    try {

        List<EnhancedEntity> reachableEntities = entityResolver.resolve(e, CascadeType.MERGE,
                this.client.getType());

        // save each one
        for (EnhancedEntity o : reachableEntities) {
            log.debug("Merging @Entity >> " + o);

            EntityMetadata metadata = metadataManager.getEntityMetadata(o.getEntity().getClass());
            metadata.setDBType(this.client.getType());
            // TODO: throw OptisticLockException if wrong version and optimistic locking enabled

            // fire PreUpdate events
            eventDispatcher.fireEventListeners(metadata, o, PreUpdate.class);

            dataManager.merge(o, metadata);
            getIndexManager().update(metadata, o.getEntity());

            // fire PreUpdate events
            eventDispatcher.fireEventListeners(metadata, o, PostUpdate.class);
        }
    } catch (Exception exp) {
        throw new PersistenceException(exp);
    }

    return e;
}

From source file:com.impetus.kundera.metadata.MetadataManager.java

/**
 * Helper class to scan each @Entity class and build various relational annotation.
 * /*from  ww  w  .j av  a  2 s.c  o m*/
 * @param entity
 *            the entity
 */
private void processRelations(Class<?> entity) {
    EntityMetadata metadata = getEntityMetadata(entity);

    for (Field f : entity.getDeclaredFields()) {

        // OneToOne
        if (f.isAnnotationPresent(OneToOne.class)) {
            // taking field's type as foreign entity, ignoring
            // "targetEntity"
            Class<?> targetEntity = f.getType();
            try {
                validate(targetEntity);
                OneToOne ann = f.getAnnotation(OneToOne.class);

                Relation relation = metadata.new Relation(f, targetEntity, null, ann.fetch(),
                        Arrays.asList(ann.cascade()), ann.optional(), ann.mappedBy(),
                        EntityMetadata.ForeignKey.ONE_TO_ONE);

                metadata.addRelation(f.getName(), relation);
            } catch (PersistenceException pe) {
                throw new PersistenceException("Error with @OneToOne in @Entity(" + entity.getName() + "."
                        + f.getName() + "), reason: " + pe.getMessage());
            }
        }

        // OneToMany
        else if (f.isAnnotationPresent(OneToMany.class)) {

            OneToMany ann = f.getAnnotation(OneToMany.class);

            Class<?> targetEntity = null;

            // resolve from generic parameters
            Type[] parameters = ReflectUtils.getTypeArguments(f);
            if (parameters != null) {
                if (parameters.length == 1) {
                    targetEntity = (Class<?>) parameters[0];
                } else {
                    throw new PersistenceException("How many parameters man?");
                }
            }
            // now, check annotations
            if (null != ann.targetEntity() && !ann.targetEntity().getSimpleName().equals("void")) {
                targetEntity = ann.targetEntity();
            }

            try {
                validate(targetEntity);
                Relation relation = metadata.new Relation(f, targetEntity, f.getType(), ann.fetch(),
                        Arrays.asList(ann.cascade()), Boolean.TRUE, ann.mappedBy(),
                        EntityMetadata.ForeignKey.ONE_TO_MANY);

                metadata.addRelation(f.getName(), relation);
            } catch (PersistenceException pe) {
                throw new PersistenceException("Error with @OneToMany in @Entity(" + entity.getName() + "."
                        + f.getName() + "), reason: " + pe.getMessage());
            }
        }

        // ManyToOne
        else if (f.isAnnotationPresent(ManyToOne.class)) {
            // taking field's type as foreign entity, ignoring
            // "targetEntity"
            Class<?> targetEntity = f.getType();
            try {
                validate(targetEntity);
                ManyToOne ann = f.getAnnotation(ManyToOne.class);

                Relation relation = metadata.new Relation(f, targetEntity, null, ann.fetch(),
                        Arrays.asList(ann.cascade()), ann.optional(), null, // mappedBy is null
                        EntityMetadata.ForeignKey.MANY_TO_ONE);

                metadata.addRelation(f.getName(), relation);
            } catch (PersistenceException pe) {
                throw new PersistenceException("Error with @OneToOne in @Entity(" + entity.getName() + "."
                        + f.getName() + "), reason: " + pe.getMessage());
            }
        }

        // ManyToMany
        else if (f.isAnnotationPresent(ManyToMany.class)) {

            ManyToMany ann = f.getAnnotation(ManyToMany.class);

            Class<?> targetEntity = null;

            // resolve from generic parameters
            Type[] parameters = ReflectUtils.getTypeArguments(f);
            if (parameters != null) {
                if (parameters.length == 1) {
                    targetEntity = (Class<?>) parameters[0];
                } else {
                    throw new PersistenceException("How many parameters man?");
                }
            }
            // now, check annotations
            if (null != ann.targetEntity() && !ann.targetEntity().getSimpleName().equals("void")) {
                targetEntity = ann.targetEntity();
            }

            try {
                validate(targetEntity);
                Relation relation = metadata.new Relation(f, targetEntity, f.getType(), ann.fetch(),
                        Arrays.asList(ann.cascade()), Boolean.TRUE, ann.mappedBy(),
                        EntityMetadata.ForeignKey.MANY_TO_MANY);

                metadata.addRelation(f.getName(), relation);
            } catch (PersistenceException pe) {
                throw new PersistenceException("Error with @OneToMany in @Entity(" + entity.getName() + "."
                        + f.getName() + "), reason: " + pe.getMessage());
            }
        }

    }
}

From source file:com.impetus.client.oraclenosql.OracleNoSQLClient.java

/**
 * Find by id.//  www. j a  va 2s.c o m
 * 
 * @param entityClass
 *            entity class
 * @param key
 *            primary key
 * @param columnsToSelect
 *            columns to select
 * @return the object
 */
private Object find(Class entityClass, Object key, List<String> columnsToSelect) {
    EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);
    MetamodelImpl metamodel = (MetamodelImpl) KunderaMetadataManager.getMetamodel(kunderaMetadata,
            entityMetadata.getPersistenceUnit());

    String idColumnName = ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName();
    Table schemaTable = tableAPI.getTable(entityMetadata.getTableName());

    PrimaryKey rowKey = schemaTable.createPrimaryKey();
    if (metamodel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType())) {
        readEmbeddable(key, columnsToSelect, entityMetadata, metamodel, schemaTable, rowKey,
                entityMetadata.getIdAttribute());
    } else {
        if (eligibleToFetch(columnsToSelect, idColumnName)) {
            NoSqlDBUtils.add(schemaTable.getField(idColumnName), rowKey, key, idColumnName);
        }
    }
    KunderaCoreUtils.printQuery("Fetch data from " + entityMetadata.getTableName() + " for PK " + key,
            showQuery);
    if (log.isDebugEnabled()) {
        log.debug("Fetching data from " + entityMetadata.getTableName() + " for PK " + key);
    }

    // Object entity = null;
    List entities = new ArrayList();
    Map<String, Object> relationMap = initialize(entityMetadata);

    try {
        Iterator<Row> rowsIter = tableAPI.tableIterator(rowKey, null, null);
        // iterator and build entity
        entities = scrollAndPopulate(key, entityMetadata, metamodel, schemaTable, rowsIter, relationMap,
                columnsToSelect);
    } catch (Exception e) {
        log.error("Error while finding data for Key " + key + ", Caused By :" + e + ".");
        throw new PersistenceException(e);
    }

    return entities.isEmpty() ? null : entities.get(0);
}

From source file:com.impetus.client.cassandra.pelops.PelopsClient.java

@Override
public void delete(Object entity, Object pKey) {
    if (!isOpen()) {
        throw new PersistenceException("PelopsClient is closed.");
    }/*from  www .  j a v a  2  s .  c om*/
    EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(entity.getClass());
    if (metadata.isCounterColumnType()) {
        ColumnPath path = new ColumnPath(metadata.getTableName());
        Cassandra.Client cassandra_client = Pelops
                .getDbConnPool(PelopsUtils.generatePoolName(getPersistenceUnit())).getConnection().getAPI();
        try {
            cassandra_client.remove_counter(ByteBuffer.wrap(pKey.toString().getBytes()), path,
                    consistencyLevel);
        } catch (InvalidRequestException ire) {
            log.error("Error during executing delete, Caused by :" + ire.getMessage());
            throw new PersistenceException(ire);
        } catch (UnavailableException ue) {
            log.error("Error during executing delete, Caused by :" + ue.getMessage());
            throw new PersistenceException(ue);
        } catch (TimedOutException toe) {
            log.error("Error during executing delete, Caused by :" + toe.getMessage());
            throw new PersistenceException(toe);
        } catch (TException te) {
            log.error("Error during executing delete, Caused by :" + te.getMessage());
            throw new PersistenceException(te);
        }
    } else {
        RowDeletor rowDeletor = Pelops.createRowDeletor(PelopsUtils.generatePoolName(getPersistenceUnit()));
        rowDeletor.deleteRow(metadata.getTableName(), pKey.toString(), consistencyLevel);

    }

    // Delete from Lucene if applicable
    getIndexManager().remove(metadata, entity, pKey.toString());

    // Delete from Inverted Index if applicable
    if (CassandraIndexHelper.isInvertedIndexingApplicable(metadata)) {
        handler.deleteRecordsFromIndexTable(entity, metadata, consistencyLevel);
    }
}

From source file:com.openmeap.model.ModelManagerImpl.java

private <T extends ModelEntity> void _delete(T entity, List<ProcessingEvent> events) {

    if (!getAuthorizer().may(Authorizer.Action.DELETE, entity)) {
        throw new PersistenceException(
                new AuthorizationException("The user logged in does not have permissions to DELETE "
                        + entity.getClass().getSimpleName() + " objects."));
    }/* ww w .  j  av a  2  s .c  o m*/
    modelService.delete(entity);
}

From source file:com.impetus.client.rdbms.HibernateClient.java

@Override
protected void onPersist(EntityMetadata metadata, Object entity, Object id,
        List<RelationHolder> relationHolders) {
    boolean proxyRemoved = removeKunderaProxies(metadata, entity, relationHolders);

    Transaction tx = null;// w  w w.j av a 2s . com

    s = getStatelessSession();
    tx = onBegin();
    try {
        if (!isUpdate) {
            id = s.insert(entity);

            // Update foreign Keys
            updateForeignKeys(metadata, id, relationHolders);
            onCommit(tx);/* tx.commit(); */
        } else {
            s.update(entity);

            if (proxyRemoved) {
                updateForeignKeys(metadata, id, relationHolders);
            }

            onCommit(tx);
        }
    }
    // TODO: Bad code, get rid of these exceptions, currently necessary for
    // handling many to one case
    catch (org.hibernate.exception.ConstraintViolationException e) {
        s.update(entity);
        log.info(e.getMessage());
        onCommit(tx);
        // tx.commit();
    } catch (HibernateException e) {
        log.error("Error while persisting object of {}, Caused by {}.", metadata.getEntityClazz(), e);
        throw new PersistenceException(e);
    }
}

From source file:com.alliander.osgp.acceptancetests.devicemanagement.CreateNewOrganisationSteps.java

@DomainStep("creating an organisation that already exists on the platform")
public void whenCreatingAnOrganisationThatAlreadyExistsOnThePlatform() throws Throwable {

    LOGGER.info("WHEN: \"creating an organisation that already exists on the platform\".");

    // Create the request
    final CreateOrganisationRequest request = new CreateOrganisationRequest();
    request.setOrganisation(this.organisationToBeAdded);

    // Expect the organisation being search, and found.
    MockitoAnnotations.initMocks(this);
    // Make sure that the adding organisation is authorized.
    when(this.organisationRepositoryMock.findByOrganisationIdentification(ORGANISATION_ROOT))
            .thenReturn(new Organisation(ORGANISATION_ROOT, ORGANISATION_ROOT, ORGANISATION_PREFIX,
                    PlatformFunctionGroup.ADMIN));

    // And that when saving the organisation an exception is thrown.
    when(this.organisationRepositoryMock.save(any(Organisation.class)))
            .thenThrow(new JpaSystemException(new PersistenceException("Duplicate entry")));

    try {// w  ww  .j a v a 2s .  c om
        this.adminDeviceManagementEndpoint.createOrganisation(ORGANISATION_ROOT, request);
    } catch (final OsgpException ex) {
        this.throwable = ex;
    }
}

From source file:com.impetus.kundera.ejb.EntityManagerImpl.java

@Override
public final void persist(Object e) {
    if (e == null) {
        throw new IllegalArgumentException("Entity must not be null.");
    }//  w  w w.  j a v a2s  .co m

    try {
        // validate
        metadataManager.validate(e.getClass());

        List<EnhancedEntity> reachableEntities = entityResolver.resolve(e, CascadeType.PERSIST,
                this.client.getType());

        // save each one
        for (EnhancedEntity o : reachableEntities) {
            log.debug("Persisting @Entity >> " + o);

            EntityMetadata metadata = metadataManager.getEntityMetadata(o.getEntity().getClass());
            metadata.setDBType(this.client.getType());
            // TODO: throw EntityExistsException if already exists

            // fire pre-persist events
            eventDispatcher.fireEventListeners(metadata, o, PrePersist.class);

            //TODO uncomment
            dataManager.persist(o, metadata);
            getIndexManager().write(metadata, o.getEntity());

            // fire post-persist events
            eventDispatcher.fireEventListeners(metadata, o, PostPersist.class);
        }
    } catch (Exception exp) {
        throw new PersistenceException(exp);
    }
}

From source file:icom.jpa.bdk.dao.LabelApplicationDAO.java

public LabelApplication concludeUpdateObject(ManagedIdentifiableProxy obj, DAOContext context,
        Projection proj) {//  w w  w . j a v  a2  s  .  c  o  m
    LabelApplicationUpdater updater = (LabelApplicationUpdater) context.getUpdater();
    try {
        BdkUserContextImpl userContext = (BdkUserContextImpl) obj.getPersistenceContext().getUserContext();
        BeeId id = getBeeId(obj.getObjectId().toString());
        String collabId = id.getId();
        String resourceType = id.getResourceType();
        PutMethod putMethod = preparePutMethod(resourceType, collabId, userContext.antiCSRF, Projection.EMPTY);
        LabelApplication bdkLabelApplication = (LabelApplication) bdkHttpUtil.execute(LabelApplication.class,
                putMethod, updater, userContext.httpClient);
        return bdkLabelApplication;
    } catch (Exception ex) {
        throw new PersistenceException(ex);
    }
}