Example usage for javax.persistence.metamodel Attribute getJavaMember

List of usage examples for javax.persistence.metamodel Attribute getJavaMember

Introduction

In this page you can find the example usage for javax.persistence.metamodel Attribute getJavaMember.

Prototype

java.lang.reflect.Member getJavaMember();

Source Link

Document

Return the java.lang.reflect.Member for the represented attribute.

Usage

From source file:com.impetus.client.cassandra.query.ResultIterator.java

/**
 * Parse and append cql3 token function for iter.next() call.
 * //from  w  w w  .j  av a  2  s  .  c  o m
 * @param translator
 *            cql translator.
 * @param query
 *            the query
 * @return parsed/append cql3 query.
 */
private String prepareNext(CQLTranslator translator, String query) {
    if (checkOnEmptyResult()) {
        String idName = ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName();
        Map<Boolean, String> filterOnId = getConditionOnIdColumn(idName);

        if (filterOnId.get(true) != null) {
            String condition = filterOnId.get(true);
            // means id clause present in query.
            // now if id attribute is embeddable then fetch partition key
            // for token
            // if condition is with equals then no need to go for another
            // fetch.

            if (condition.equals("=")) {
                // no need to fetch another record, as there will be only
                // one
                return null;
            } else if (condition.endsWith(">") || condition.equals(">=")) {
                query = replaceAppliedToken(query);
                return query;
            }
        }

        // Means there is an previous entity.
        Object entity = results.get(results.size() - 1);
        Class idClazz = ((AbstractAttribute) entityMetadata.getIdAttribute()).getBindableJavaType();
        Object id = PropertyAccessorHelper.getId(entity, entityMetadata);
        StringBuilder builder = new StringBuilder(CQLTranslator.TOKEN);
        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
                .getMetamodel(entityMetadata.getPersistenceUnit());

        EmbeddableType keyObj = null;
        // Bytes bytes = null;
        String columnName = null;
        if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType())) {
            keyObj = metaModel.embeddable(entityMetadata.getIdAttribute().getBindableJavaType());
            Field embeddedField = getPartitionKeyField();
            Attribute partitionKey = keyObj.getAttribute(embeddedField.getName());
            Object partitionKeyValue = PropertyAccessorHelper.getObject(id,
                    (Field) partitionKey.getJavaMember());
            columnName = ((AbstractAttribute) partitionKey).getJPAColumnName();
            id = partitionKeyValue;
            idClazz = ((AbstractAttribute) partitionKey).getBindableJavaType();
            // StringBuilder pkNameTokens = new StringBuilder("token(");
            // StringBuilder pkValueTokens = new StringBuilder("token(");
            // buildPartitionKeyTokens(metaModel,
            // entityMetadata.getIdAttribute(), id, translator,
            // pkNameTokens,
            // pkValueTokens);

        } else {
            columnName = CassandraUtilities.getIdColumnName(kunderaMetadata, entityMetadata, externalProperties,
                    ((CassandraClientBase) client).isCql3Enabled(entityMetadata));
        }

        translator.appendColumnName(builder, columnName);
        builder.append(CQLTranslator.CLOSE_BRACKET);
        builder.append(" > ");
        builder.append(CQLTranslator.TOKEN);
        translator.appendValue(builder, idClazz, id, false, false);
        builder.append(CQLTranslator.CLOSE_BRACKET);
        return builder.toString();
    }
    return null;
}

From source file:com.impetus.client.cassandra.query.ResultIterator.java

private void buildPartitionKeyTokens(MetamodelImpl metaModel, SingularAttribute idAttribute, Object id,
        CQLTranslator translator, StringBuilder pkNameTokens, StringBuilder pkValueTokens) {
    EmbeddableType keyObj = metaModel.embeddable(entityMetadata.getIdAttribute().getBindableJavaType());
    Field embeddedField = getPartitionKeyField();

    if (embeddedField == null) {
        // use tokens on the fields (no clustering keys
        Field[] fields = entityMetadata.getIdAttribute().getBindableJavaType().getDeclaredFields();

        for (Field field : fields) {
            Object value = PropertyAccessorHelper.getObject(id, field);
            String columnName = ((AbstractAttribute) keyObj.getAttribute(field.getName())).getJPAColumnName();
            translator.appendColumnName(pkNameTokens, columnName);
            translator.appendValue(pkValueTokens, field.getType(), value, false, false);
        }/*from  www .j a v a2  s .  c o m*/
    } else {
        // use tokens for partition key fields (fields in embeddedField) and
        // where clause for clustering fields
        Attribute partitionKey = keyObj.getAttribute(embeddedField.getName());
        EmbeddableType partitionKeyObj = metaModel.embeddable(partitionKey.getJavaType());
        Object partitionKeyValue = PropertyAccessorHelper.getObject(id, (Field) partitionKey.getJavaMember());
        Field[] fields = partitionKey.getJavaType().getDeclaredFields();
        // handle for part keys
        for (Field field : fields) {
            if (!ReflectUtils.isTransientOrStatic(field)) {
                Object value = PropertyAccessorHelper.getObject(partitionKeyValue, field);
                String columnName = ((AbstractAttribute) partitionKeyObj.getAttribute(field.getName()))
                        .getJPAColumnName();
                translator.appendColumnName(pkNameTokens, columnName);
                translator.appendValue(pkValueTokens, field.getType(), value, false, false);
                pkNameTokens.append(CQLTranslator.COMMA_STR);
                pkValueTokens.append(CQLTranslator.COMMA_STR);
            }
        }
        pkNameTokens.delete(pkNameTokens.lastIndexOf(CQLTranslator.COMMA_STR), pkNameTokens.length());
        pkValueTokens.delete(pkValueTokens.lastIndexOf(CQLTranslator.COMMA_STR), pkValueTokens.length());
        pkNameTokens.append(CQLTranslator.CLOSE_BRACKET);
        pkValueTokens.append(CQLTranslator.CLOSE_BRACKET);

        // TODO: handle for cluster keys
        throw new UnsupportedOperationException(
                "Pagination is not suported via ThriftClient on primary key with clustering keys...");
    }

}

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

/**
 * //w  ww  .ja  v a2s.  co  m
 * Gets (if available) or creates a node for the given entity
 */
private Node getOrCreateNodeWithUniqueFactory(final Object entity, final Object id, final EntityMetadata m,
        GraphDatabaseService graphDb) {
    final String idColumnName = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();
    final MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
            .getMetamodel(m.getPersistenceUnit());
    final String idUniqueValue = serializeIdAttributeValue(m, metaModel, id);

    UniqueFactory<Node> factory = new UniqueFactory.UniqueNodeFactory(graphDb, m.getIndexName()) {
        /**
         * Initialize ID attribute
         */
        @Override
        protected void initialize(Node created, Map<String, Object> properties) {
            // Set Embeddable ID attribute
            if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType())) {
                // Populate embedded field value in serialized format
                created.setProperty(idColumnName, idUniqueValue);

                // Populated all other attributes of embedded into this node
                Set<Attribute> embeddableAttributes = metaModel
                        .embeddable(m.getIdAttribute().getBindableJavaType()).getSingularAttributes();
                for (Attribute attribute : embeddableAttributes) {
                    String columnName = ((AbstractAttribute) attribute).getJPAColumnName();
                    if (columnName == null)
                        columnName = attribute.getName();
                    Object value = PropertyAccessorHelper.getObject(id, (Field) attribute.getJavaMember());

                    if (value != null)
                        created.setProperty(columnName, value);
                }
            } else {
                created.setProperty(idColumnName, properties.get(idColumnName));
            }

        }
    };

    if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType())) {
        return factory.getOrCreate(idColumnName, idUniqueValue);
    } else {
        return factory.getOrCreate(idColumnName, id);
    }

}

From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectDeltaUpdater.java

private AttributeStep stepThroughAttribute(Attribute attribute, AttributeStep step,
        Iterator<ItemPathSegment> segments) {
    Method method = (Method) attribute.getJavaMember();

    switch (attribute.getPersistentAttributeType()) {
    case EMBEDDED:
        step.managedType = entityRegistry.getMapping(attribute.getJavaType());
        Object child = invoke(step.bean, method);
        if (child == null) {
            // embedded entity doesn't exist we have to create it first, so it can be populated later
            Class childType = getRealOutputType(attribute);
            try {
                child = childType.newInstance();
                PropertyUtils.setSimpleProperty(step.bean, attribute.getName(), child);
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException
                    | NoSuchMethodException ex) {
                throw new SystemException("Couldn't create new instance of '" + childType.getName()
                        + "', attribute '" + attribute.getName() + "'", ex);
            }//from  w w w.j  av a2s . c  o m
        }
        step.bean = child;
        break;
    case ONE_TO_MANY:
        // object extension is handled separately, only {@link Container} and references are handled here
        Class clazz = getRealOutputType(attribute);

        IdItemPathSegment id = (IdItemPathSegment) segments.next();

        Collection c = (Collection) invoke(step.bean, method);
        if (!Container.class.isAssignableFrom(clazz)) {
            throw new SystemException(
                    "Don't know how to go through collection of '" + getRealOutputType(attribute) + "'");
        }

        boolean found = false;
        for (Container o : (Collection<Container>) c) {
            long l = o.getId().longValue();
            if (l == id.getId()) {
                step.managedType = entityRegistry.getMapping(clazz);
                step.bean = o;

                found = true;
                break;
            }
        }

        if (!found) {
            throw new RuntimeException("Couldn't find container of type '" + getRealOutputType(attribute)
                    + "' with id '" + id + "'");
        }
        break;
    case ONE_TO_ONE:
        // assignment extension is handled separately
        break;
    default:
        // nothing to do for other cases
    }

    return step;
}

From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectDeltaUpdater.java

private void handleAttribute(Attribute attribute, Object bean, ItemDelta delta, PrismObject prismObject,
        PrismIdentifierGenerator idGenerator) {
    Method method = (Method) attribute.getJavaMember();

    switch (attribute.getPersistentAttributeType()) {
    case BASIC:/*  www .  j a v  a 2s  . c om*/
    case EMBEDDED:
        handleBasicOrEmbedded(bean, delta, attribute);
        break;
    case MANY_TO_MANY:
        // not used in our mappings
        throw new SystemException("Don't know how to handle @ManyToMany relationship, should not happen");
    case ONE_TO_ONE:
        // assignment extension is handled separately
        break;
    case MANY_TO_ONE:
        // this can't be in delta (probably)
        throw new SystemException("Don't know how to handle @ManyToOne relationship, should not happen");
    case ONE_TO_MANY:
        // object extension is handled separately, only {@link Container} and references are handled here
        Collection oneToMany = (Collection) invoke(bean, method);
        handleOneToMany(oneToMany, delta, attribute, bean, prismObject, idGenerator);
        break;
    case ELEMENT_COLLECTION:
        Collection elementCollection = (Collection) invoke(bean, method);
        handleElementCollection(elementCollection, delta, attribute, bean, prismObject, idGenerator);
        break;
    }
}

From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectDeltaUpdater.java

private Class getRealOutputType(Attribute attribute) {
    Class type = attribute.getJavaType();
    if (!Collection.class.isAssignableFrom(type)) {
        return type;
    }/*from www . j  av  a 2 s  . c  om*/

    Method method = (Method) attribute.getJavaMember();
    ParameterizedType parametrized = (ParameterizedType) method.getGenericReturnType();
    Type t = parametrized.getActualTypeArguments()[0];
    if (t instanceof Class) {
        return (Class) t;
    }

    parametrized = (ParameterizedType) t;
    return (Class) parametrized.getRawType();
}

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

/**
 * Gets the compound key.//w  w w.  j  av a  2  s.c  o  m
 * 
 * @param attribute
 *            the attribute
 * @param entity
 *            the entity
 * @return the compound key
 * @throws InstantiationException
 *             the instantiation exception
 * @throws IllegalAccessException
 *             the illegal access exception
 */
private Object getCompoundKey(Attribute attribute, Object entity)
        throws InstantiationException, IllegalAccessException {
    Object compoundKeyObject = null;
    if (entity != null) {
        compoundKeyObject = PropertyAccessorHelper.getObject(entity, (Field) attribute.getJavaMember());
        if (compoundKeyObject == null) {
            compoundKeyObject = ((AbstractAttribute) attribute).getBindableJavaType().newInstance();
        }
    }

    return compoundKeyObject;
}

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

/**
 * setter field.//from   www.  ja  v  a  2 s  .  co m
 * 
 * @param row
 *            the row
 * @param schemaTable
 *            the schema table
 * @param embeddedObject
 *            the embedded object
 * @param embeddedAttrib
 *            the embedded attrib
 */
private void setField(Row row, Table schemaTable, Object embeddedObject, Attribute embeddedAttrib) {
    Field field = (Field) embeddedAttrib.getJavaMember();
    FieldDef fieldDef = schemaTable.getField(((AbstractAttribute) embeddedAttrib).getJPAColumnName());

    Object valueObj = PropertyAccessorHelper.getObject(embeddedObject, field);

    if (valueObj != null)
        NoSqlDBUtils.add(fieldDef, row, valueObj, ((AbstractAttribute) embeddedAttrib).getJPAColumnName());

}

From source file:com.impetus.client.rdbms.query.RDBMSEntityReader.java

/**
 * //from   w w  w .  j  a  v  a 2  s  .c  om
 * @param entityMetadata
 * @param primaryKeys
 * @param aliasName
 * @param queryBuilder
 * @param entityType
 */
private void onCondition(EntityMetadata entityMetadata, MetamodelImpl metamodel, Set<String> primaryKeys,
        String aliasName, StringBuilder queryBuilder, EntityType entityType) {
    if (primaryKeys == null) {
        for (Object o : conditions) {
            if (o instanceof FilterClause) {
                FilterClause clause = ((FilterClause) o);
                Object value = clause.getValue().get(0);
                String propertyName = clause.getProperty();
                String condition = clause.getCondition();

                if (StringUtils.contains(propertyName, '.')) {
                    int indexOf = propertyName.indexOf(".");
                    String jpaColumnName = propertyName.substring(0, indexOf);
                    String embeddedColumnName = propertyName.substring(indexOf + 1, propertyName.length());
                    String fieldName = entityMetadata.getFieldName(jpaColumnName);
                    Attribute attribute = entityType.getAttribute(fieldName);
                    EmbeddableType embeddedType = metamodel
                            .embeddable(((AbstractAttribute) attribute).getBindableJavaType());
                    Attribute embeddedAttribute = embeddedType.getAttribute(embeddedColumnName);

                    addClause(entityMetadata, aliasName, queryBuilder, entityType, value, condition, fieldName,
                            embeddedAttribute);
                } else {
                    String fieldName = entityMetadata.getFieldName(propertyName);
                    Attribute attribute = entityType.getAttribute(fieldName);
                    if (metamodel.isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType())) {
                        EmbeddableType embeddedType = metamodel
                                .embeddable(((AbstractAttribute) attribute).getBindableJavaType());
                        Set<Attribute> attributes = embeddedType.getAttributes();
                        for (Attribute embeddedAttribute : attributes) {
                            Object embeddedAttributevalue = PropertyAccessorHelper.getObject(value,
                                    (Field) embeddedAttribute.getJavaMember());
                            addClause(entityMetadata, aliasName, queryBuilder, entityType,
                                    embeddedAttributevalue, condition, propertyName, embeddedAttribute);
                            queryBuilder.append(" and ");
                        }

                        queryBuilder.delete(queryBuilder.lastIndexOf("and"),
                                queryBuilder.lastIndexOf("and") + 3);
                    } else if (((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()
                            .equals(propertyName)) {
                        addClause(entityMetadata, aliasName, queryBuilder, entityType, value, condition,
                                propertyName, entityMetadata.getIdAttribute());
                    } else {
                        addClause(entityMetadata, aliasName, queryBuilder, entityType, value, condition,
                                propertyName, attribute);
                    }
                }
            } else {
                queryBuilder.append(" ");
                queryBuilder.append(o);
                queryBuilder.append(" ");
            }
        }
    } else {
        queryBuilder.append(aliasName);
        queryBuilder.append(".");
        queryBuilder.append(((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName());
        queryBuilder.append(" ");
        queryBuilder.append("IN(");
        int count = 0;
        Attribute col = entityMetadata.getIdAttribute();
        boolean isString = isStringProperty(entityType, col);
        for (String key : primaryKeys) {
            appendStringPrefix(queryBuilder, isString);
            queryBuilder.append(key);
            appendStringPrefix(queryBuilder, isString);
            if (++count != primaryKeys.size()) {
                queryBuilder.append(",");
            } else {
                queryBuilder.append(")");
            }
        }
    }
}

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

/**
 * Read embeddable.//from  w w  w  .  j  a  v  a 2  s.  c  om
 * 
 * @param key
 *            the key
 * @param columnsToSelect
 *            the columns to select
 * @param entityMetadata
 *            the entity metadata
 * @param metamodel
 *            the metamodel
 * @param schemaTable
 *            the schema table
 * @param value
 *            the value
 * @param attribute
 *            the attribute
 */
private void readEmbeddable(Object key, List<String> columnsToSelect, EntityMetadata entityMetadata,
        MetamodelImpl metamodel, Table schemaTable, RecordValue value, Attribute attribute) {
    EmbeddableType embeddableId = metamodel.embeddable(((AbstractAttribute) attribute).getBindableJavaType());
    Set<Attribute> embeddedAttributes = embeddableId.getAttributes();

    for (Attribute embeddedAttrib : embeddedAttributes) {
        String columnName = ((AbstractAttribute) embeddedAttrib).getJPAColumnName();
        Object embeddedColumn = PropertyAccessorHelper.getObject(key, (Field) embeddedAttrib.getJavaMember());

        // either null or empty or contains that column
        if (eligibleToFetch(columnsToSelect, columnName)) {
            NoSqlDBUtils.add(schemaTable.getField(columnName), value, embeddedColumn, columnName);
        }
    }
}