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.kundera.ejb.EntityManagerFactoryBuilder.java

/**
 * Find persistence metadatas./* ww w .  j  a va 2s .  c o  m*/
 * 
 * @return the list
 */
private List<PersistenceMetadata> findPersistenceMetadatas() {
    try {
        Enumeration<URL> xmls = Thread.currentThread().getContextClassLoader()
                .getResources("META-INF/persistence.xml");

        if (!xmls.hasMoreElements()) {
            log.info("Could not find any META-INF/persistence.xml " + "file in the classpath");
        }

        Set<String> persistenceUnitNames = new HashSet<String>();
        List<PersistenceMetadata> persistenceUnits = new ArrayList<PersistenceMetadata>();

        while (xmls.hasMoreElements()) {
            URL url = xmls.nextElement();
            log.trace("Analyse of persistence.xml: " + url);
            List<PersistenceMetadata> metadataFiles = PersistenceXmlLoader.findPersistenceUnits(url,
                    PersistenceUnitTransactionType.RESOURCE_LOCAL);

            // Pick only those that have Kundera Provider
            for (PersistenceMetadata metadata : metadataFiles) {
                // check for provider
                if (metadata.getProvider() == null
                        || PROVIDER_IMPLEMENTATION_NAME.equalsIgnoreCase(metadata.getProvider())) {
                    persistenceUnits.add(metadata);
                }

                // check for unique names
                if (persistenceUnitNames.contains(metadata.getName())) {
                    throw new PersistenceException(
                            "Duplicate persistence-units for name: " + metadata.getName());
                }
                persistenceUnitNames.add(metadata.getName());
            }
        }

        return persistenceUnits;
    } catch (Exception e) {
        if (e instanceof PersistenceException) {
            throw (PersistenceException) e;
        } else {
            throw new PersistenceException(e);
        }
    }
}

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

public Object loadObject(ManagedIdentifiableProxy obj, Projection proj) {
    try {//ww w.ja  v a 2s. com
        BdkUserContextImpl userContext = (BdkUserContextImpl) obj.getPersistenceContext().getUserContext();
        BeeId id = getBeeId(obj.getObjectId().toString());
        String collabId = id.getId();
        String resourceType = id.getResourceType();
        GetMethod method = prepareGetMethod(resourceType, collabId, proj);
        Object bdkVersionControlConfiguration = bdkHttpUtil.execute(Object.class, method,
                userContext.httpClient);
        return bdkVersionControlConfiguration;
    } catch (Exception ex) {
        throw new PersistenceException(ex);
    }
}

From source file:com.impetus.kundera.client.PelopsClient.java

@Override
public final /*Map<String, List<Column>>*/ <E> List<E> loadColumns(EntityManagerImpl em, Class<E> clazz,
        String keyspace, String columnFamily, EntityMetadata m, String... rowIds) throws Exception {

    if (!isOpen()) {
        throw new PersistenceException("PelopsClient is closed.");
    }/*from w  w  w.j a  va 2s.  c  o m*/
    Selector selector = Pelops.createSelector(poolName, keyspace);
    Map<String, List<Column>> map = selector.getColumnsFromRows(Arrays.asList(rowIds), columnFamily,
            Selector.newColumnsPredicateAll(false, 1000), ConsistencyLevel.ONE);
    List<E> entities = new ArrayList<E>();
    // Iterate and populate entities
    for (Map.Entry<String, List<Column>> entry : map.entrySet()) {

        String id = entry.getKey();
        List<Column> columns = entry.getValue();

        if (entry.getValue().size() == 0) {
            log.debug("@Entity not found for id: " + id);
            continue;
        }

        E e = fromThriftRow(em, clazz, m, this.new ThriftRow(id, columnFamily, columns));
        entities.add(e);
    }
    return entities;
}

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

/**
 * Cache metadata./*from   w w w. j a  v a  2s . c  o  m*/
 * 
 * @param clazz
 *            the clazz
 * @param metadata
 *            the metadata
 */
private void cacheMetadata(Class<?> clazz, EntityMetadata metadata) {
    metadataCache.put(clazz, metadata);

    // save name to class map.
    if (entityNameToClassMap.containsKey(clazz.getSimpleName())) {
        throw new PersistenceException("Name conflict between classes "
                + entityNameToClassMap.get(clazz.getSimpleName()).getName() + " and " + clazz.getName());
    }
    entityNameToClassMap.put(clazz.getSimpleName(), clazz);
}

From source file:com.impetus.kundera.cache.ElementCollectionCacheManager.java

/**
 * Gets the last element collection object count.
 * /*w  w  w.  j  a  va  2s .co  m*/
 * @param rowKey
 *            the row key
 * @return the last element collection object count
 */
public int getLastElementCollectionObjectCount(String rowKey) {
    if (getElementCollectionCache().get(rowKey) == null) {
        log.debug("No element collection object map found in cache for Row key " + rowKey);
        return -1;
    } else {
        Map<Object, String> elementCollectionMap = getElementCollectionCache().get(rowKey);
        Collection<String> elementCollectionObjectNames = elementCollectionMap.values();
        int max = 0;

        for (String s : elementCollectionObjectNames) {
            String elementCollectionCountStr = s
                    .substring(s.indexOf(Constants.EMBEDDED_COLUMN_NAME_DELIMITER) + 1);
            int elementCollectionCount = 0;
            try {
                elementCollectionCount = Integer.parseInt(elementCollectionCountStr);
            } catch (NumberFormatException e) {
                log.error("Invalid element collection Object name " + s);
                throw new PersistenceException("Invalid element collection Object name " + s);
            }
            if (elementCollectionCount > max) {
                max = elementCollectionCount;
            }
        }
        return max;
    }
}

From source file:com.impetus.kundera.mongodb.MongoDBDataHandler.java

public BasicDBObject getDocumentFromEntity(EntityManagerImpl em, EntityMetadata m, Object entity)
        throws PropertyAccessException {
    List<Column> columns = m.getColumnsAsList();
    BasicDBObject dbObj = new BasicDBObject();

    //Populate columns
    for (Column column : columns) {
        try {/*from w ww .jav  a  2s.  com*/
            extractEntityField(entity, dbObj, column);
        } catch (PropertyAccessException e1) {
            log.error("Can't access property " + column.getField().getName());
        }
    }

    //Populate Relationship fields
    List<Relation> relations = m.getRelations();
    for (Relation relation : relations) {
        // Cascade?
        if (!relation.getCascades().contains(CascadeType.ALL)
                && !relation.getCascades().contains(CascadeType.PERSIST)) {
            continue;
        }

        Class<?> embeddedEntityClass = relation.getTargetEntity(); //Target entity
        Field embeddedEntityField = relation.getProperty(); //Mapped to this property         
        boolean optional = relation.isOptional(); // Is it optional         
        Object embeddedObject = PropertyAccessorHelper.getObject(entity, embeddedEntityField); // Value         

        EntityMetadata relMetadata = em.getMetadataManager().getEntityMetadata(embeddedEntityClass);
        relMetadata.addColumn(relMetadata.getIdColumn().getName(), relMetadata.getIdColumn()); //Add PK column

        if (embeddedObject == null) {
            if (!optional) {
                throw new PersistenceException(
                        "Field " + embeddedEntityField + " is not optional, and hence must be set.");
            }

        } else {
            if (relation.isUnary()) {
                BasicDBObject relDBObj = getDocumentFromEntity(em, relMetadata, embeddedObject);
                dbObj.put(embeddedEntityField.getName(), relDBObj);

            } else if (relation.isCollection()) {
                Collection collection = (Collection) embeddedObject;
                BasicDBObject[] relDBObjects = new BasicDBObject[collection.size()];
                int count = 0;
                for (Object o : collection) {
                    relDBObjects[count] = getDocumentFromEntity(em, relMetadata, o);
                    count++;
                }
                dbObj.put(embeddedEntityField.getName(), relDBObjects);
            }

        }

    }
    return dbObj;
}

From source file:com.impetus.kundera.utils.KunderaCoreUtils.java

/**
 * Prepares composite key as a lucene key.
 * /*  w w  w.j  a  va2 s .  co  m*/
 * @param m
 *            entity metadata
 * @param metaModel
 *            meta model.
 * @param compositeKey
 *            composite key instance
 * @return redis key
 */
public static String prepareCompositeKey(final SingularAttribute attribute, final MetamodelImpl metaModel,
        final Object compositeKey) {
    Field[] fields = attribute.getBindableJavaType().getDeclaredFields();
    EmbeddableType embeddable = metaModel.embeddable(attribute.getBindableJavaType());
    StringBuilder stringBuilder = new StringBuilder();

    try {
        for (Field f : fields) {
            if (!ReflectUtils.isTransientOrStatic(f)) {
                if (metaModel.isEmbeddable(
                        ((AbstractAttribute) embeddable.getAttribute(f.getName())).getBindableJavaType())) {
                    f.setAccessible(true);
                    stringBuilder.append(
                            prepareCompositeKey((SingularAttribute) embeddable.getAttribute(f.getName()),
                                    metaModel, f.get(compositeKey)))
                            .append(LUCENE_COMPOSITE_KEY_SEPERATOR);
                } else {
                    String fieldValue = PropertyAccessorHelper.getString(compositeKey, f);
                    fieldValue = fieldValue.replaceAll("[^a-zA-Z0-9]", "_");

                    stringBuilder.append(fieldValue);
                    stringBuilder.append(LUCENE_COMPOSITE_KEY_SEPERATOR);
                }
            }
        }
    } catch (IllegalAccessException e) {
        logger.error(e.getMessage());
    } catch (IllegalArgumentException e) {
        logger.error("Error during prepare composite key, Caused by {}.", e);
        throw new PersistenceException(e);
    }

    if (stringBuilder.length() > 0) {
        stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(LUCENE_COMPOSITE_KEY_SEPERATOR));
    }
    return stringBuilder.toString();
}

From source file:edu.kit.dama.staging.services.impl.download.DownloadInformationPersistenceImpl.java

/**
 * Create a new download entity.//  w  ww .  j  av  a  2 s . c  o m
 *
 * @param pDigitalObjectId The digital object id for which the download will
 * be created.
 * @param pAccessPointId The AccessPoint to use for downloading data.
 * @param pProcessors A collection of StagingProcessor applied after the
 * download preparation.
 * @param pSecurityContext The security context.
 *
 * @return The created download information.
 */
public DownloadInformation createEntity(final DigitalObjectId pDigitalObjectId, String pAccessPointId,
        Collection<StagingProcessor> pProcessors, IAuthorizationContext pSecurityContext) {
    if (pDigitalObjectId == null) {
        throw new IllegalArgumentException("Argument pDigitalObjectId must not be 'null'");
    }
    if (pAccessPointId == null) {
        LOGGER.warn("AccessPointId should not be null! E.g. cleanup may fail.");
    }

    if (pSecurityContext == null) {
        throw new IllegalArgumentException("Argument pSecurityContext must not be 'null'");
    } else if (pSecurityContext.getUserId() == null) {
        throw new IllegalArgumentException("Illegal security context. User must not be 'null'");
    }

    try {
        List<DownloadInformation> entities = getEntitiesByDigitalObjectId(pDigitalObjectId, 0,
                Integer.MAX_VALUE, pSecurityContext);
        if (!entities.isEmpty()) {
            throw new PersistenceException("Obviously, there is already an entity with the digital object id '"
                    + pDigitalObjectId + "' registed in the current context.");
        }
    } catch (PersistenceException pe) {
        //some error occured
        throw new PersistenceException("Failed to check for duplicated entities", pe);
    }
    DownloadInformation result = new DownloadInformation(pDigitalObjectId);
    //add staging processors if available
    if (pProcessors != null && !pProcessors.isEmpty()) {
        for (StagingProcessor processor : pProcessors) {
            result.addStagingProcessor(processor);
        }
    }

    IMetaDataManager mdm = SecureMetaDataManager.factorySecureMetaDataManager(getPersistenceUnit(),
            pSecurityContext);
    try {
        result.setAccessPointId(pAccessPointId);
        result.setOwnerId(pSecurityContext.getUserId().getStringRepresentation());
        result.setGroupId(pSecurityContext.getGroupId().getStringRepresentation());
        result.setLastUpdate(System.currentTimeMillis());
        result.setExpiresAt(System.currentTimeMillis() + DownloadInformation.DEFAULT_LIFETIME);
        LOGGER.debug("Persisting download for object id  '{}'", result.getDigitalObjectId());
        result = mdm.save(result);
    } catch (UnauthorizedAccessAttemptException ex) {
        throw new PersistenceException(
                "Failed for persist download information for object id " + pDigitalObjectId + "'", ex);
    } finally {
        mdm.close();
    }
    return result;
}

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

/**
 * Gets the transaction type./* w w  w.  j a v a2  s. c  o  m*/
 * 
 * @param elementContent
 *            the element content
 * @return the transaction type
 */
public static PersistenceUnitTransactionType getTransactionType(String elementContent) {

    if (elementContent == null || elementContent.isEmpty()) {
        return null;
    } else if (elementContent.equalsIgnoreCase("JTA")) {
        return PersistenceUnitTransactionType.JTA;
    } else if (elementContent.equalsIgnoreCase("RESOURCE_LOCAL")) {
        return PersistenceUnitTransactionType.RESOURCE_LOCAL;
    } else {
        throw new PersistenceException("Unknown TransactionType: " + elementContent);
    }
}

From source file:com.impetus.kundera.client.PelopsClient.java

@Override
public final void delete(String keyspace, String columnFamily, String rowId) throws Exception {

    if (!isOpen()) {
        throw new PersistenceException("PelopsClient is closed.");
    }//w w w  . java2s. c o  m
    KeyDeletor keyDeletor = Pelops.createKeyDeletor(poolName, keyspace);
    keyDeletor.deleteColumnFamily(rowId, columnFamily, ConsistencyLevel.ONE);
}