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.pelops.PelopsClient.java

/**
 * Find.//w w  w  .  j  a v a 2 s  .c  om
 * 
 * @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 {
        result = (List<Object>) find(clazz, relationNames, relationNames != null, metadata,
                rowId != null ? rowId.toString() : null);
    } catch (Exception e) {
        log.error("Error on retrieval" + e.getMessage());
        throw new PersistenceException(e);
    }

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

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

/**
 * Load super columns./*from   w ww.ja v a 2s .  c o  m*/
 * 
 * @param keyspace
 *            the keyspace
 * @param columnFamily
 *            the column family
 * @param rowId
 *            the row id
 * @param superColumnNames
 *            the super column names
 * @return the list
 */
private final List<SuperColumn> loadSuperColumns(String keyspace, String columnFamily, String rowId,
        String... superColumnNames) {
    if (!isOpen())
        throw new PersistenceException("PelopsClient is closed.");
    Selector selector = Pelops.createSelector(PelopsUtils.generatePoolName(getPersistenceUnit()));
    List<ByteBuffer> rowKeys = new ArrayList<ByteBuffer>();
    rowKeys.add(ByteBuffer.wrap(rowId.getBytes()));

    // selector.getColumnOrSuperColumnsFromRows(new
    // ColumnParent(columnFamily),rowKeys ,
    // Selector.newColumnsPredicate(superColumnNames), consistencyLevel);
    return selector.getSuperColumnsFromRow(columnFamily, rowId, Selector.newColumnsPredicate(superColumnNames),
            consistencyLevel);
}

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

/**
 * On index search.//from  w w  w  .j a v  a 2 s  .  c  o m
 * 
 * @param <E>
 *            the element type
 * @param interpreter
 *            the interpreter
 * @param entityMetadata
 *            the entity metadata
 * @param metamodel
 *            the metamodel
 * @param results
 *            the results
 * @param columnsToSelect
 *            the columns to select
 * @return the list
 */
private <E> List<E> onIndexSearch(OracleNoSQLQueryInterpreter interpreter, EntityMetadata entityMetadata,
        MetamodelImpl metamodel, List<E> results, List<String> columnsToSelect) {
    Map<String, List> indexes = new HashMap<String, List>();
    StringBuilder indexNamebuilder = new StringBuilder();

    for (Object clause : interpreter.getClauseQueue()) {
        if (clause.getClass().isAssignableFrom(FilterClause.class)) {
            String fieldName = null;

            String clauseName = ((FilterClause) clause).getProperty();
            StringTokenizer stringTokenizer = new StringTokenizer(clauseName, ".");
            // if need to select embedded columns
            if (stringTokenizer.countTokens() > 1) {
                fieldName = stringTokenizer.nextToken();
            }

            fieldName = stringTokenizer.nextToken();
            Object value = ((FilterClause) clause).getValue();
            if (!indexes.containsKey(fieldName)) {
                indexNamebuilder.append(fieldName);
                indexNamebuilder.append(",");
            }
            indexes.put(fieldName, (List) value);
        } else {
            if (clause.toString().equalsIgnoreCase("OR")) {
                throw new QueryHandlerException("OR clause is not supported with oracle nosql db");
            }
        }
    }

    // prepare index name and value.
    Table schemaTable = tableAPI.getTable(entityMetadata.getTableName());
    String indexKeyName = indexNamebuilder.deleteCharAt(indexNamebuilder.length() - 1).toString();
    Index index = schemaTable.getIndex(entityMetadata.getIndexProperties().get(indexKeyName).getName());
    IndexKey indexKey = index.createIndexKey();

    // StringBuilder indexNamebuilder = new StringBuilder();
    for (String indexName : indexes.keySet()) {
        NoSqlDBUtils.add(schemaTable.getField(indexName), indexKey, indexes.get(indexName).get(0), indexName);
    }

    Iterator<Row> rowsIter = tableAPI.tableIterator(indexKey, null, null);

    Map<String, Object> relationMap = initialize(entityMetadata);

    try {
        results = scrollAndPopulate(null, entityMetadata, metamodel, schemaTable, rowsIter, relationMap,
                columnsToSelect);
        KunderaCoreUtils.printQueryWithFilterClause(interpreter.getClauseQueue(),
                entityMetadata.getTableName());
    } catch (Exception e) {
        log.error("Error while finding records , Caused By :" + e + ".");
        throw new PersistenceException(e);
    }

    return results;
}

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

/**
 * On execute query./*  w  ww .ja v a  2s.c o m*/
 * 
 * @param queryParameter
 *            the query parameter
 * @param entityClazz
 *            the entity clazz
 * @return the list
 */
List onExecuteQuery(RedisQueryInterpreter queryParameter, Class entityClazz) {
    /**
     * Find a list of id's and then call findById for each!
     */
    Object connection = null;
    List<Object> results = new ArrayList<Object>();
    try {
        connection = getConnection();
        Set<String> rowKeys = new HashSet<String>();
        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);
        String printQuery = null;

        if (showQuery) {
            printQuery = "Fetching primary key from " + entityMetadata.getTableName() + " corresponding to ";
        }

        if (queryParameter.getClause() != null && !queryParameter.isByRange()) {
            String destStore = entityClazz.getSimpleName() + System.currentTimeMillis();

            Map<String, Object> fieldSets = queryParameter.getFields();

            Set<String> keySets = new HashSet<String>(fieldSets.size());
            // byte[][] keys = new byte[][fieldSets.size()];
            for (String column : fieldSets.keySet()) {
                String valueAsStr = PropertyAccessorHelper.getString(fieldSets.get(column));
                String key = getHashKey(entityMetadata.getTableName(), getHashKey(column, valueAsStr));
                keySets.add(key);
                if (showQuery) {
                    printQuery = printQuery + key + " and ";
                }
            }

            if (showQuery) {
                printQuery = printQuery.substring(0, printQuery.lastIndexOf(" and "));
            }

            if (queryParameter.getClause().equals(Clause.INTERSECT)) {
                KunderaCoreUtils.printQuery(printQuery, showQuery);

                if (resource != null && resource.isActive()) {
                    ((Transaction) connection).zinterstore(destStore, keySets.toArray(new String[] {}));
                } else {
                    ((Jedis) connection).zinterstore(destStore, keySets.toArray(new String[] {}));
                }
            } else {
                if (showQuery) {
                    KunderaCoreUtils.printQuery(printQuery.replaceAll("and", "or"), showQuery);
                }

                if (resource != null && resource.isActive()) {
                    ((Transaction) connection).zunionstore(destStore, keySets.toArray(new String[] {}));
                } else {
                    ((Jedis) connection).zunionstore(destStore, keySets.toArray(new String[] {}));
                }
            }

            if (resource != null && resource.isActive()) {
                Response response = ((Transaction) connection).zrange(destStore, 0, -1);
                // ((Transaction) connection).exec();
                ((RedisTransaction) resource).onExecute(((Transaction) connection));

                rowKeys = (Set<String>) response.get();
                // connection = reInitialize(connection, rowKeys);
                //
                // ((Transaction) connection).del(destStore);

            } else {
                rowKeys = ((Jedis) connection).zrange(destStore, 0, -1);
                ((Jedis) connection).del(destStore);
            }

            // delete intermediate store after find.
            //
            // means it is a query over sorted set.
        } else if (queryParameter.isByRange()) {
            // means query over a single sorted set with range
            Map<String, Double> minimum = queryParameter.getMin();
            Map<String, Double> maximum = queryParameter.getMax();

            String column = minimum.keySet().iterator().next();
            KunderaCoreUtils.printQuery(printQuery + column + " between " + minimum + " and " + maximum,
                    showQuery);
            if (resource != null && resource.isActive()) {
                Response response = ((Transaction) connection).zrangeByScore(
                        getHashKey(entityMetadata.getTableName(), column), minimum.get(column),
                        maximum.get(column));
                // ((Transaction) connection).exec();
                ((RedisTransaction) resource).onExecute(((Transaction) connection));

                rowKeys = (Set<String>) response.get();
                // connection = reInitialize(connection, rowKeys);
            } else {
                rowKeys = ((Jedis) connection).zrangeByScore(getHashKey(entityMetadata.getTableName(), column),
                        minimum.get(column), maximum.get(column));
            }
        } else if (queryParameter.isById()) {
            Map<String, Object> fieldSets = queryParameter.getFields();

            results = findAllColumns(entityClazz,
                    (queryParameter.getColumns() != null ? queryParameter.getColumns().toArray(new byte[][] {})
                            : null),
                    fieldSets.values().toArray());
            return results;
        } else if (queryParameter.getFields() != null) {
            Set<String> columns = queryParameter.getFields().keySet();

            for (String column : columns) {
                // ideally it will always be 1 value in map, else it will go
                // it queryParameter.getClause() will not be null!
                Double value = getDouble(
                        PropertyAccessorHelper.getString(queryParameter.getFields().get(column)));
                if (resource != null && resource.isActive()) {
                    Response response = ((Transaction) connection)
                            .zrangeByScore(getHashKey(entityMetadata.getTableName(), column), value, value);
                    // ((Transaction) connection).exec();
                    ((RedisTransaction) resource).onExecute(((Transaction) connection));

                    rowKeys = (Set<String>) response.get();
                    // connection = reInitialize(connection, rowKeys);

                } else {
                    rowKeys = ((Jedis) connection)
                            .zrangeByScore(getHashKey(entityMetadata.getTableName(), column), value, value);
                }
            }
        } else {
            if (resource != null && resource.isActive()) {
                Response response = ((Transaction) connection).zrange(
                        getHashKey(entityMetadata.getTableName(),
                                ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()),
                        0, -1);
                // resource.onCommit()
                // ((Transaction) connection).exec();
                ((RedisTransaction) resource).onExecute(((Transaction) connection));

                rowKeys = new HashSet<String>((Collection<? extends String>) response.get());
            } else {
                rowKeys = new HashSet<String>(((Jedis) connection).zrange(
                        getHashKey(entityMetadata.getTableName(),
                                ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()),
                        0, -1));
            }
        }

        for (String k : rowKeys) {
            connection = reInitialize(connection, rowKeys);
            Object record = fetch(entityClazz, k, connection,
                    (queryParameter.getColumns() != null ? queryParameter.getColumns().toArray(new byte[][] {})
                            : null));
            if (record != null) {
                results.add(record);
            }
        }

    } catch (InstantiationException e) {
        logger.error("Error during persist, Caused by:", e);
        throw new PersistenceException(e);
    } catch (IllegalAccessException e) {
        logger.error("Error during persist, Caused by:", e);
        throw new PersistenceException(e);
    } catch (Exception e) {
        logger.error("Error during persist, Caused by:", e);
        throw new PersistenceException(e);
    } finally {
        onCleanup(connection);

    }

    return results;
}

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

/**
 * Find all columns.//from   www  .ja  va 2 s  .c  o  m
 * 
 * @param <E>
 *            the element type
 * @param entityClass
 *            the entity class
 * @param columns
 *            the columns
 * @param keys
 *            the keys
 * @return the list
 */
private <E> List<E> findAllColumns(Class<E> entityClass, byte[][] columns, Object... keys) {
    Object connection = getConnection();
    // connection.co
    List results = new ArrayList();
    try {
        for (Object key : keys) {
            Object result = fetch(entityClass, key, connection, columns);
            if (result != null) {
                results.add(result);
            }
        }
    } 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);
    }
    return results;
}

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

/**
 * Prepare mutation.// w w  w.  ja  va 2  s .co  m
 * 
 * @param entityMetadata
 *            the entity metadata
 * @param entity
 *            the entity
 * @param id
 *            the id
 * @param relationHolders
 *            the relation holders
 * @param mutationMap
 *            the mutation map
 * @return the map
 */
protected Map<ByteBuffer, Map<String, List<Mutation>>> prepareMutation(EntityMetadata entityMetadata,
        Object entity, Object id, List<RelationHolder> relationHolders,
        Map<ByteBuffer, Map<String, List<Mutation>>> mutationMap) {

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

    // check for counter column
    if (isUpdate && entityMetadata.isCounterColumnType()) {
        log.warn("Invalid operation! {} is not possible over counter column of entity {}.", "Merge",
                entityMetadata.getEntityClazz());
        throw new UnsupportedOperationException(
                "Invalid operation! Merge is not possible over counter column.");
    }

    Collection<ThriftRow> tfRows = null;
    try {
        String columnFamily = entityMetadata.getTableName();
        tfRows = getDataHandler().toThriftRow(entity, id, entityMetadata, columnFamily,
                getTtlValues().get(columnFamily));
    } catch (Exception e) {
        log.error("Error during persisting record for entity {}, Caused by: .", entityMetadata.getEntityClazz(),
                entityMetadata.getTableName(), e);
        throw new KunderaException(e);
    }

    Map<String, List<Mutation>> columnFamilyValues = new HashMap<String, List<Mutation>>();

    for (ThriftRow tf : tfRows) {
        if (tf.getColumnFamilyName().equals(entityMetadata.getTableName())) {
            addRelationsToThriftRow(entityMetadata, tf, relationHolders);
        }

        String columnFamily = tf.getColumnFamilyName();
        // Create Insertion List
        List<Mutation> mutationList = new ArrayList<Mutation>();

        /*********** Handling for counter column family ************/

        if (entityMetadata.isCounterColumnType()) {
            List<CounterColumn> thriftCounterColumns = tf.getCounterColumns();
            List<CounterSuperColumn> thriftCounterSuperColumns = tf.getCounterSuperColumns();

            if (thriftCounterColumns != null && !thriftCounterColumns.isEmpty()) {
                for (CounterColumn column : thriftCounterColumns) {
                    Mutation mut = new Mutation();
                    mut.setColumn_or_supercolumn(new ColumnOrSuperColumn().setCounter_column(column));
                    mutationList.add(mut);
                }
            }

            if (thriftCounterSuperColumns != null && !thriftCounterSuperColumns.isEmpty()) {
                for (CounterSuperColumn sc : thriftCounterSuperColumns) {
                    Mutation mut = new Mutation();
                    mut.setColumn_or_supercolumn(new ColumnOrSuperColumn().setCounter_super_column(sc));
                    mutationList.add(mut);
                }
            }
        } else
        /********* Handling for column family and super column family *********/
        {
            List<Column> thriftColumns = tf.getColumns();
            List<SuperColumn> thriftSuperColumns = tf.getSuperColumns();

            // Populate Insertion list for columns
            if (thriftColumns != null && !thriftColumns.isEmpty()) {
                for (Column column : thriftColumns) {
                    Mutation mut = new Mutation();
                    mut.setColumn_or_supercolumn(new ColumnOrSuperColumn().setColumn(column));
                    mutationList.add(mut);
                }
            }

            // Populate Insertion list for super columns
            if (thriftSuperColumns != null && !thriftSuperColumns.isEmpty()) {
                for (SuperColumn superColumn : thriftSuperColumns) {
                    Mutation mut = new Mutation();
                    mut.setColumn_or_supercolumn(new ColumnOrSuperColumn().setSuper_column(superColumn));
                    mutationList.add(mut);
                }
            }
        }
        columnFamilyValues.put(columnFamily, mutationList);
    }
    // Create Mutation Map

    ByteBuffer b = CassandraUtilities.toBytes(id, entityMetadata.getIdAttribute().getBindableJavaType());
    mutationMap.put(b, columnFamilyValues);

    return mutationMap;
}

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

/**
 * Executes query string using cql3.// w ww.j  a  v a2s  .c o  m
 * 
 * @param cqlQuery
 *            the cql query
 * @param isCql3Enabled
 *            the is cql3 enabled
 * @return the object
 */
protected Object executeCQLQuery(String cqlQuery, boolean isCql3Enabled) {
    Cassandra.Client conn = null;
    Object pooledConnection = null;
    pooledConnection = getConnection();
    conn = (org.apache.cassandra.thrift.Cassandra.Client) getConnection(pooledConnection);
    try {
        if (isCql3Enabled || isCql3Enabled()) {
            return execute(cqlQuery, conn);
        }
        KunderaCoreUtils.printQuery(cqlQuery, showQuery);
        if (log.isDebugEnabled()) {
            log.debug("Executing cql query {}.", cqlQuery);
        }
        return conn.execute_cql_query(ByteBufferUtil.bytes(cqlQuery),
                org.apache.cassandra.thrift.Compression.NONE);
    } catch (Exception ex) {
        if (log.isErrorEnabled()) {
            log.error("Error during executing query {}, Caused by: {} .", cqlQuery, ex);
        }
        throw new PersistenceException(ex);
    } finally {
        releaseConnection(pooledConnection);
    }
}

From source file:org.apache.camel.component.jpa.JpaConsumer.java

@Override
protected int poll() throws Exception {
    // must reset for each poll
    shutdownRunningTask = null;//from ww w.  j  a  v  a2s  .com
    pendingExchanges = 0;

    Object messagePolled = template.execute(new JpaCallback() {
        public Object doInJpa(EntityManager entityManager) throws PersistenceException {
            Queue<DataHolder> answer = new LinkedList<DataHolder>();

            Query query = getQueryFactory().createQuery(entityManager);
            configureParameters(query);
            List<Object> results = CastUtils.cast(query.getResultList());
            for (Object result : results) {
                DataHolder holder = new DataHolder();
                holder.manager = entityManager;
                holder.result = result;
                holder.exchange = createExchange(result);
                answer.add(holder);
            }

            int messagePolled;
            try {
                messagePolled = processBatch(CastUtils.cast(answer));
            } catch (Exception e) {
                throw new PersistenceException(e);
            }

            entityManager.flush();
            return messagePolled;
        }
    });

    return endpoint.getCamelContext().getTypeConverter().convertTo(int.class, messagePolled);
}

From source file:org.apache.camel.component.jpa.JpaConsumer.java

public int processBatch(Queue<Object> exchanges) throws Exception {
    int total = exchanges.size();

    // limit if needed
    if (maxMessagesPerPoll > 0 && total > maxMessagesPerPoll) {
        LOG.debug("Limiting to maximum messages to poll " + maxMessagesPerPoll + " as there was " + total
                + " messages in this poll.");
        total = maxMessagesPerPoll;/*from w  w w.j  av  a2  s  .c om*/
    }

    for (int index = 0; index < total && isBatchAllowed(); index++) {
        // only loop if we are started (allowed to run)
        DataHolder holder = ObjectHelper.cast(DataHolder.class, exchanges.poll());
        EntityManager entityManager = holder.manager;
        Exchange exchange = holder.exchange;
        Object result = holder.result;

        // add current index and total as properties
        exchange.setProperty(Exchange.BATCH_INDEX, index);
        exchange.setProperty(Exchange.BATCH_SIZE, total);
        exchange.setProperty(Exchange.BATCH_COMPLETE, index == total - 1);

        // update pending number of exchanges
        pendingExchanges = total - index - 1;

        if (lockEntity(result, entityManager)) {
            // process the current exchange
            if (LOG.isDebugEnabled()) {
                LOG.debug("Processing exchange: " + exchange);
            }
            try {
                getProcessor().process(exchange);
            } catch (Exception e) {
                throw new PersistenceException(e);
            }
            getDeleteHandler().deleteObject(entityManager, result);
        }
    }

    return total;
}

From source file:org.batoo.jpa.core.impl.collections.ManagedList.java

/**
 * {@inheritDoc}//from w ww.  j a  v a2s  .  c o  m
 * 
 */
@Override
public void initialize() {
    if (!this.initialized) {
        final ManagedInstance<?> managedInstance = this.getManagedInstance();

        if (managedInstance == null) {
            throw new PersistenceException("No session to initialize the collection");
        }

        final PluralMappingEx<?, ?, E> mapping = this.getMapping();

        BatooUtils.addAll(mapping.loadCollection(managedInstance), this.delegate);

        this.initialized = true;

        if (this.getMapping().getOrderBy() != null) {
            mapping.sortList(managedInstance.getInstance());
        }

        this.initialized = true;
    }
}