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.cassandra.CassandraClientBase.java

/**
 * Find.//from  w w  w  . j  ava  2s. c o m
 * 
 * @param clazz
 *            the clazz
 * @param metadata
 *            the metadata
 * @param rowId
 *            the row id
 * @param relationNames
 *            the relation names
 * @return the object
 */
private final Object find(Class<?> clazz, EntityMetadata metadata, Object rowId, List<String> relationNames) {

    List<Object> result = null;
    try {
        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
                .getMetamodel(metadata.getPersistenceUnit());

        EntityType entityType = metaModel.entity(clazz);

        List<ManagedType> subTypes = ((AbstractManagedType) entityType).getSubManagedType();

        if (!subTypes.isEmpty()) {
            for (ManagedType subEntity : subTypes) {
                EntityMetadata subEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                        subEntity.getJavaType());
                result = populate(clazz, subEntityMetadata, rowId, subEntityMetadata.getRelationNames(),
                        metaModel);
                if (result != null && !result.isEmpty()) {
                    break;
                }
            }
        } else {
            result = populate(clazz, metadata, rowId, relationNames, metaModel);
        }
    } catch (Exception e) {
        log.error("Error while retrieving records from database for entity {} and key {}, Caused by: .", clazz,
                rowId, e);

        throw new PersistenceException(e);
    }

    return result != null && !result.isEmpty() ? result.get(0) : null;
}

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

public void sendEmail(ManagedIdentifiableProxy obj, BeeId sentFolderId) {
    String resourceType = getResourceType();
    resourceType += "/send";
    if (obj != null && obj.isDirty()) {
        EmailDraftUpdater emailDraftUpdater = new EmailDraftUpdater();
        DAOContext context = new DAOContext(emailDraftUpdater);
        EmailMessageContentUpdater emailMessageContentUpdater = new EmailMessageContentUpdater();
        emailDraftUpdater.setContentUpdater(emailMessageContentUpdater);
        context.setChildUpdater(emailMessageContentUpdater);
        updateObjectState(obj, context);
        String params = null;//from   w w  w  .ja  v a  2  s  . co  m
        String uploadScopeId = context.getUploadScopeId();
        if (uploadScopeId != null) {
            params = "uploadscope=scope" + uploadScopeId;
        }
        if (sentFolderId != null) {
            if (params == null) {
                params += "sent_folder=" + sentFolderId.getId();
            } else {
                params += "&sent_folder=" + sentFolderId.getId();
            }
        }
        try {
            BdkUserContextImpl userContext = (BdkUserContextImpl) obj.getPersistenceContext().getUserContext();
            PostMethod postMethod = preparePostMethod(resourceType, userContext.antiCSRF, params);
            bdkHttpUtil.execute(postMethod, emailDraftUpdater, userContext.httpClient);
        } catch (Exception ex) {
            throw new PersistenceException(ex);
        }
    } else if (obj != null && obj.isNew()) {
        EmailMessageContentUpdater emailMessageContentUpdater = new EmailMessageContentUpdater();
        DAOContext context = new DAOContext(emailMessageContentUpdater);
        updateEmailMessageContentState(obj, context);
        String params = null;
        String uploadScopeId = context.getUploadScopeId();
        if (uploadScopeId != null) {
            params = "uploadscope=scope" + uploadScopeId;
        }
        if (sentFolderId != null) {
            if (params == null) {
                params += "sent_folder=" + sentFolderId.getId();
            } else {
                params += "&sent_folder=" + sentFolderId.getId();
            }
        }
        try {
            BdkUserContextImpl userContext = (BdkUserContextImpl) obj.getPersistenceContext().getUserContext();
            PostMethod postMethod = preparePostMethod(resourceType, userContext.antiCSRF, params);
            bdkHttpUtil.execute(postMethod, emailMessageContentUpdater, userContext.httpClient);
        } catch (Exception ex) {
            throw new PersistenceException(ex);
        }
    } else if (obj == null) {
        throw new PersistenceException("Message must have manged proxy");
    }
    assignEnumConstant(obj.getPojoObject(), UnifiedMessageInfo.Attributes.editMode.name(),
            BeanHandler.getBeanPackageName(), IcomBeanEnumeration.UnifiedMessageEditModeEnum.name(),
            MessageMode.DeliveredCopy.name());
    obj.resetReady();
}

From source file:com.impetus.client.neo4j.Neo4JClient.java

/**
 * Returns instance of {@link BatchInserter}.
 * /*from   w ww .j av  a  2 s  . c om*/
 * @return the batch inserter
 */
protected BatchInserter getBatchInserter() {
    PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata()
            .getPersistenceUnitMetadata(getPersistenceUnit());
    Properties props = puMetadata.getProperties();

    // Datastore file path
    String datastoreFilePath = (String) props.get(PersistenceProperties.KUNDERA_DATASTORE_FILE_PATH);
    if (StringUtils.isEmpty(datastoreFilePath)) {
        throw new PersistenceException(
                "For Neo4J, it's mandatory to specify kundera.datastore.file.path property in persistence.xml");
    }

    // Shut down Graph DB, at a time only one service may have lock on DB
    // file
    if (factory.getConnection() != null) {
        factory.getConnection().shutdown();
    }

    BatchInserter inserter = null;

    // Create Batch inserter with configuration if specified
    Neo4JSchemaMetadata nsmd = Neo4JPropertyReader.nsmd;
    ClientProperties cp = nsmd != null ? nsmd.getClientProperties() : null;
    if (cp != null) {
        DataStore dataStore = nsmd != null ? nsmd.getDataStore() : null;
        Properties properties = dataStore != null && dataStore.getConnection() != null
                ? dataStore.getConnection().getProperties()
                : null;

        if (properties != null) {
            Map<String, String> config = new HashMap<String, String>((Map) properties);
            inserter = BatchInserters.inserter(datastoreFilePath, config);
        }
    }

    // Create Batch inserter without configuration if not provided
    if (inserter == null) {
        inserter = BatchInserters.inserter(datastoreFilePath);
    }
    return inserter;
}

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

/**
 * Method to execute cql query and return back entity/enhance entities.
 * /* w  ww  .j a  va  2  s  .  co m*/
 * @param cqlQuery
 *            cql query to be executed.
 * @param clazz
 *            entity class.
 * @param relationalField
 *            collection for relational fields.
 * @return list of objects.
 * 
 */
public List executeQuery(String cqlQuery, Class clazz, List<String> relationalField) {
    IThriftPool thrift = Pelops.getDbConnPool(PelopsUtils.generatePoolName(getPersistenceUnit()));
    // thrift.get
    IPooledConnection connection = thrift.getConnection();
    try {
        org.apache.cassandra.thrift.Cassandra.Client thriftClient = connection.getAPI();

        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(clazz);
        CqlResult result = null;
        List returnedEntities = null;
        try {
            result = thriftClient.execute_cql_query(ByteBufferUtil.bytes(cqlQuery),
                    org.apache.cassandra.thrift.Compression.NONE);
            if (result != null && (result.getRows() != null || result.getRowsSize() > 0)) {
                returnedEntities = new ArrayList<Object>(result.getRowsSize());
                Iterator<CqlRow> iter = result.getRowsIterator();
                while (iter.hasNext()) {
                    CqlRow row = iter.next();
                    String rowKey = Bytes.toUTF8(row.getKey());
                    ThriftRow thriftRow = null;
                    if (entityMetadata.isCounterColumnType()) {
                        log.info("Native query is not permitted on counter column returning null ");
                        return null;
                    } else {
                        thriftRow = handler.new ThriftRow(rowKey, entityMetadata.getTableName(),
                                row.getColumns(), null, null, null);
                    }

                    Object entity = handler.fromColumnThriftRow(clazz, entityMetadata, thriftRow,
                            relationalField, relationalField != null && !relationalField.isEmpty());
                    if (entity != null) {
                        returnedEntities.add(entity);
                    }
                }
            }
        } catch (InvalidRequestException e) {
            log.error("Error while executing native CQL query Caused by:" + e.getLocalizedMessage());
            throw new PersistenceException(e);
        } catch (UnavailableException e) {
            log.error("Error while executing native CQL query Caused by:" + e.getLocalizedMessage());
            throw new PersistenceException(e);
        } catch (TimedOutException e) {
            log.error("Error while executing native CQL query Caused by:" + e.getLocalizedMessage());
            throw new PersistenceException(e);
        } catch (SchemaDisagreementException e) {
            log.error("Error while executing native CQL query Caused by:" + e.getLocalizedMessage());
            throw new PersistenceException(e);
        } catch (TException e) {
            log.error("Error while executing native CQL query Caused by:" + e.getLocalizedMessage());
            throw new PersistenceException(e);
        } catch (Exception e) {
            log.error("Error while executing native CQL query Caused by:" + e.getLocalizedMessage());
            throw new PersistenceException(e);
        }
        return returnedEntities;
    } finally {
        try {
            if (connection != null) {
                connection.release();
            }
        } catch (Exception e) {
            log.warn("Releasing connection for native CQL query failed", e);
        }
    }
}

From source file:org.appverse.web.framework.backend.persistence.services.integration.impl.live.JPAPersistenceService.java

@SuppressWarnings("unchecked")
@Override//  www . j ava  2s  .c  om
public T retrieve(final T beanP) throws Exception {
    logger.trace(PersistenceMessageBundle.MSG_DAO_RETRIEVEBYBEAN, new Object[] { beanP, this.BEAN_PK_NAME });
    Object beanId;
    try {
        beanId = PropertyUtils.getProperty(beanP, this.BEAN_PK_NAME);
        return (T) em.find(beanP.getClass(), beanId);
    } catch (final Exception e) {
        logger.error(PersistenceMessageBundle.MSG_DAO_RETRIEVEBYBEAN,
                new Object[] { beanP, this.BEAN_PK_NAME });
        throw new PersistenceException(PersistenceMessageBundle.MSG_DAO_RETRIEVEBYBEAN);
    }
}

From source file:com.impetus.kundera.client.cassandra.dsdriver.DSClient.java

/**
 * Populate composite id./*from  www  .j  ava2 s  .  co  m*/
 * 
 * @param metadata
 *            the metadata
 * @param entity
 *            the entity
 * @param columnName
 *            the column name
 * @param row
 *            the row
 * @param metaModel
 *            the meta model
 * @param attribute
 *            the attribute
 * @param entityClazz
 *            the entity clazz
 * @param dataType
 *            the data type
 * @return the object
 */
private Object populateCompositeId(EntityMetadata metadata, Object entity, String columnName, Row row,
        MetamodelImpl metaModel, Attribute attribute, Class<?> entityClazz, DataType dataType) {
    Class javaType = ((AbstractAttribute) attribute).getBindableJavaType();

    if (metaModel.isEmbeddable(javaType)) {
        EmbeddableType compoundKey = metaModel.embeddable(javaType);
        Object compoundKeyObject = null;
        try {
            Set<Attribute> attributes = compoundKey.getAttributes();
            entity = KunderaCoreUtils.initialize(entityClazz, entity);

            for (Attribute compoundAttribute : attributes) {
                compoundKeyObject = compoundKeyObject == null ? getCompoundKey(attribute, entity)
                        : compoundKeyObject;

                if (metaModel.isEmbeddable(((AbstractAttribute) compoundAttribute).getBindableJavaType())) {
                    Object compoundObject = populateCompositeId(metadata, compoundKeyObject, columnName, row,
                            metaModel, compoundAttribute, javaType, dataType);
                    PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), compoundObject);
                } else if (((AbstractAttribute) compoundAttribute).getJPAColumnName().equals(columnName)) {
                    DSClientUtilities.assign(row, compoundKeyObject, null, dataType.getName(), null, columnName,
                            (Field) compoundAttribute.getJavaMember(), metaModel);
                    PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), compoundKeyObject);
                    break;
                }
            }
        } catch (IllegalArgumentException iaex) {
            // ignore as it might not represented within entity.
            // No need for any logger message
        } catch (Exception e) {
            log.error("Error while retrieving data, Caused by: .", e);
            throw new PersistenceException(e);
        }
    }
    return entity;
}

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

/**
 * Populate tf row.// w w  w  .  jav a2 s  .  c  o m
 * 
 * @param entity
 *            the entity
 * @param id
 *            the id
 * @param metadata
 *            the metadata
 * @return the pelops data handler n. thrift row
 * @throws Exception
 *             the exception
 */
private PelopsDataHandler.ThriftRow populateTfRow(Object entity, String id, EntityMetadata metadata)
        throws Exception {

    String columnFamily = metadata.getTableName();

    if (!isOpen()) {
        throw new PersistenceException("PelopsClient is closed.");
    }

    // PelopsDataHandler handler = dataHandler != null ? dataHandler : new
    // PelopsDataHandler(;
    PelopsDataHandler.ThriftRow tf = handler.toThriftRow(entity, id, metadata, columnFamily);
    timestamp = handler.getTimestamp();
    return tf;
}

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

/**
 * Populate embedded object./*from  w  w w .  j  av  a2 s.c o  m*/
 * 
 * @param sc
 *            the sc
 * @param m
 *            the m
 * @return the object
 * @throws Exception
 *             the exception
 */
Object populateEmbeddedObject(SuperColumn sc, EntityMetadata m) throws Exception {
    Field embeddedCollectionField = null;
    Object embeddedObject = null;
    String scName = PropertyAccessorFactory.STRING.fromBytes(String.class, sc.getName());
    String scNamePrefix = null;

    // Get a name->field map for super-columns
    Map<String, Field> columnNameToFieldMap = new HashMap<String, Field>();
    Map<String, Field> superColumnNameToFieldMap = new HashMap<String, Field>();
    MetadataUtils.populateColumnAndSuperColumnMaps(m, columnNameToFieldMap, superColumnNameToFieldMap);

    // If this super column is variable in number (name#sequence format)
    if (scName.indexOf(Constants.EMBEDDED_COLUMN_NAME_DELIMITER) != -1) {
        StringTokenizer st = new StringTokenizer(scName, Constants.EMBEDDED_COLUMN_NAME_DELIMITER);
        if (st.hasMoreTokens()) {
            scNamePrefix = st.nextToken();
        }

        embeddedCollectionField = superColumnNameToFieldMap.get(scNamePrefix);
        Class<?> embeddedClass = PropertyAccessorHelper.getGenericClass(embeddedCollectionField);

        // must have a default no-argument constructor
        try {
            embeddedClass.getConstructor();
        } catch (NoSuchMethodException nsme) {
            throw new PersistenceException(embeddedClass.getName()
                    + " is @Embeddable and must have a default no-argument constructor.");
        }
        embeddedObject = embeddedClass.newInstance();

        for (Column column : sc.getColumns()) {
            String name = PropertyAccessorFactory.STRING.fromBytes(String.class, column.getName());
            byte[] value = column.getValue();
            if (value == null) {
                continue;
            }
            Field columnField = columnNameToFieldMap.get(name);
            PropertyAccessorHelper.set(embeddedObject, columnField, value);
        }

    } else {
        Field superColumnField = superColumnNameToFieldMap.get(scName);
        Class superColumnClass = superColumnField.getType();
        embeddedObject = superColumnClass.newInstance();

        for (Column column : sc.getColumns()) {
            String name = PropertyAccessorFactory.STRING.fromBytes(String.class, column.getName());
            byte[] value = column.getValue();

            if (value == null) {
                continue;
            }
            // set value of the field in the bean
            Field columnField = columnNameToFieldMap.get(name);
            PropertyAccessorHelper.set(embeddedObject, columnField, value);

        }
    }
    return embeddedObject;
}

From source file:com.impetus.client.cassandra.CassandraClientBase.java

/**
 * Execute scalar query./* w  w w.  j  ava  2 s. c om*/
 * 
 * @param cqlQuery
 *            the cql query
 * @return the list
 */
public List executeScalarQuery(String cqlQuery) {
    CqlResult cqlResult = null;
    List results = new ArrayList();
    try {
        if (log.isDebugEnabled()) {
            log.debug("Executing query {}.", cqlQuery);
        }
        cqlResult = (CqlResult) executeCQLQuery(cqlQuery, true);

        if (cqlResult != null && (cqlResult.getRows() != null || cqlResult.getRowsSize() > 0)) {
            results = new ArrayList<Object>(cqlResult.getRowsSize());
            Iterator<CqlRow> iter = cqlResult.getRowsIterator();
            while (iter.hasNext()) {
                Map<String, Object> entity = new HashMap<String, Object>();

                CqlRow row = iter.next();
                for (Column column : row.getColumns()) {
                    if (column != null) {
                        String thriftColumnName = PropertyAccessorFactory.STRING.fromBytes(String.class,
                                column.getName());

                        if (column.getValue() == null) {
                            entity.put(thriftColumnName, null);
                        } else {
                            entity.put(thriftColumnName, composeColumnValue(cqlResult.getSchema(),
                                    column.getValue(), column.getName()));
                        }
                    }
                }
                results.add(entity);
            }
        }
    } catch (Exception e) {
        log.error("Error while executing native CQL query Caused by {}.", e);
        throw new PersistenceException(e);
    }
    return results;
}

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

/**
 * Returns encoded bytes./*from w ww.  j  a v  a  2  s  . c om*/
 * 
 * @param name
 *            field name.
 * @return encoded byte array.
 */
byte[] getEncodedBytes(final String name) {
    try {
        if (name != null) {
            return name.getBytes(Constants.CHARSET_UTF8);
        }
    } catch (UnsupportedEncodingException e) {
        logger.error("Error during persist, Caused by:", e);
        throw new PersistenceException(e);
    }

    return null;
}