Example usage for javax.persistence.metamodel Attribute getJavaType

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

Introduction

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

Prototype

Class<Y> getJavaType();

Source Link

Document

Return the Java type of the represented attribute.

Usage

From source file:com.evanzeimet.queryinfo.jpa.field.QueryInfoJPAAttributePathBuilder.java

protected Class<?> getAttributeJoinedType(Attribute<?, ?> attribute) {
    Class<?> result;/*from w  w  w  . jav a 2s  .co  m*/

    if (attribute instanceof PluralAttribute<?, ?, ?>) {
        PluralAttribute<?, ?, ?> pluralAttribute = ((PluralAttribute<?, ?, ?>) attribute);
        result = pluralAttribute.getBindableJavaType();
    } else {
        result = attribute.getJavaType();
    }

    return result;
}

From source file:com.jaxio.jpa.querybyexample.JpaUtil.java

public void verifyPath(List<Attribute<?, ?>> path) {
    List<Attribute<?, ?>> attributes = newArrayList(path);
    Class<?> from = null;/*from   ww w  . j a  v  a 2 s  . c  o  m*/
    if (attributes.get(0).isCollection()) {
        from = ((PluralAttribute) attributes.get(0)).getElementType().getJavaType();
    } else {
        from = attributes.get(0).getJavaType();
    }
    attributes.remove(0);
    for (Attribute<?, ?> attribute : attributes) {
        if (!attribute.getDeclaringType().getJavaType().isAssignableFrom(from)) {
            throw new IllegalStateException("Wrong path.");
        }
        from = attribute.getJavaType();
    }
}

From source file:com.dbs.sdwt.jpa.JpaUtil.java

@SuppressWarnings("rawtypes")
public void verifyPath(List<Attribute<?, ?>> path) {
    List<Attribute<?, ?>> attributes = newArrayList(path);
    Class<?> from = null;/*from ww  w  .j  a v  a 2s . c  om*/
    if (attributes.get(0).isCollection()) {
        from = ((PluralAttribute) attributes.get(0)).getElementType().getJavaType();
    } else {
        from = attributes.get(0).getJavaType();
    }
    attributes.remove(0);
    for (Attribute<?, ?> attribute : attributes) {
        if (!attribute.getDeclaringType().getJavaType().isAssignableFrom(from)) {
            throw new IllegalStateException("Wrong path.");
        }
        from = attribute.getJavaType();
    }
}

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 ww  w .  j av a  2 s  .co  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.evolveum.midpoint.repo.sql.helpers.ObjectDeltaUpdater.java

private Class getRealOutputType(Attribute attribute) {
    Class type = attribute.getJavaType();
    if (!Collection.class.isAssignableFrom(type)) {
        return type;
    }//  ww  w .  j  a va2 s  . com

    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.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 a  v a2 s  . c  om
        }
        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:org.jdal.dao.jpa.JpaDao.java

/**
 * Null References on one to many and one to one associations.
 * Will only work if association has annotated with a mappedBy attribute.
 * //from   w  ww .  j av a2  s.  c om
 * @param entity entity
 */
private void nullReferences(T entity) {
    EntityType<T> type = em.getMetamodel().entity(getEntityClass());

    if (log.isDebugEnabled())
        log.debug("Null references on entity " + type.getName());

    for (Attribute<?, ?> a : type.getAttributes()) {
        if (PersistentAttributeType.ONE_TO_MANY == a.getPersistentAttributeType()
                || PersistentAttributeType.ONE_TO_ONE == a.getPersistentAttributeType()) {
            Object association = PropertyAccessorFactory.forDirectFieldAccess(entity)
                    .getPropertyValue(a.getName());
            if (association != null) {
                EntityType<?> associationType = null;
                if (a.isCollection()) {
                    associationType = em.getMetamodel()
                            .entity(((PluralAttribute<?, ?, ?>) a).getBindableJavaType());
                } else {
                    associationType = em.getMetamodel().entity(a.getJavaType());

                }

                String mappedBy = JpaUtils.getMappedBy(a);
                if (mappedBy != null) {
                    Attribute<?, ?> aa = associationType.getAttribute(mappedBy);
                    if (PersistentAttributeType.MANY_TO_ONE == aa.getPersistentAttributeType()) {
                        if (log.isDebugEnabled()) {
                            log.debug("Null ManyToOne reference on " + associationType.getName() + "."
                                    + aa.getName());
                        }
                        for (Object o : (Collection<?>) association) {
                            PropertyAccessorFactory.forDirectFieldAccess(o).setPropertyValue(aa.getName(),
                                    null);
                        }
                    } else if (PersistentAttributeType.ONE_TO_ONE == aa.getPersistentAttributeType()) {
                        if (log.isDebugEnabled()) {
                            log.debug("Null OneToOne reference on " + associationType.getName() + "."
                                    + aa.getName());
                        }
                        PropertyAccessorFactory.forDirectFieldAccess(association).setPropertyValue(aa.getName(),
                                null);
                    }
                }
            }
        }
    }
}

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

/**
 * Returns bytes value for given value./*from w w  w  .j  a va2 s.  co  m*/
 * 
 * @param jpaFieldName
 *            field name.
 * @param m
 *            entity metadata
 * @param value
 *            value.
 * @return bytes value.
 */
ByteBuffer getBytesValue(String jpaFieldName, EntityMetadata m, Object value) {
    Attribute idCol = m.getIdAttribute();
    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
            .getMetamodel(m.getPersistenceUnit());

    EntityType entity = metaModel.entity(m.getEntityClazz());
    Field f = null;
    boolean isId = false;
    if (((AbstractAttribute) idCol).getJPAColumnName().equals(jpaFieldName)) {
        f = (Field) idCol.getJavaMember();
        isId = true;
    } else {
        if (jpaFieldName != null && jpaFieldName.indexOf(Constants.INDEX_TABLE_ROW_KEY_DELIMITER) > 0) {
            String embeddedFieldName = jpaFieldName.substring(0,
                    jpaFieldName.indexOf(Constants.INDEX_TABLE_ROW_KEY_DELIMITER));
            String columnFieldName = jpaFieldName.substring(
                    jpaFieldName.indexOf(Constants.INDEX_TABLE_ROW_KEY_DELIMITER) + 1, jpaFieldName.length());

            Attribute embeddedAttr = entity.getAttribute(embeddedFieldName);
            try {
                Class<?> embeddedClass = embeddedAttr.getJavaType();
                if (Collection.class.isAssignableFrom(embeddedClass)) {
                    Class<?> genericClass = PropertyAccessorHelper
                            .getGenericClass((Field) embeddedAttr.getJavaMember());
                    f = genericClass.getDeclaredField(columnFieldName);
                } else {
                    f = embeddedClass.getDeclaredField(columnFieldName);
                }

            } catch (SecurityException e) {
                log.error("Error while extrating " + jpaFieldName + ", Caused by: ", e);
                throw new QueryHandlerException("Error while extrating " + jpaFieldName + ".");
            } catch (NoSuchFieldException e) {
                log.error("Error while extrating " + jpaFieldName + ", Caused by: ", e);
                throw new QueryHandlerException("Error while extrating " + jpaFieldName + ".");
            }
        } else {
            String discriminatorColumn = ((AbstractManagedType) entity).getDiscriminatorColumn();

            if (!jpaFieldName.equals(discriminatorColumn)) {
                String fieldName = m.getFieldName(jpaFieldName);

                Attribute col = entity.getAttribute(fieldName);
                if (col == null) {
                    throw new QueryHandlerException("column type is null for: " + jpaFieldName);
                }
                f = (Field) col.getJavaMember();
            }
        }
    }

    // need to do integer.parseInt..as value will be string in case of
    // create query.
    if (f != null && f.getType() != null) {
        return CassandraUtilities.toBytes(value, f);
    } else {
        // default is String type
        return CassandraUtilities.toBytes(value, String.class);
    }
}

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

/**
 * Gets the compound key column.//from   w ww .  ja  v  a  2 s  .c  om
 * 
 * @param metamodel
 *            the metamodel
 * @param keyObj
 *            the key obj
 * @param builder
 *            the builder
 * @param isPresent
 *            the is present
 * @param translator
 *            the translator
 * @param fieldName
 *            the field name
 * @param condition
 *            the condition
 * @param value
 *            the value
 * @param useInClause
 *            the use in clause
 * @return the compound key column
 */
private boolean getCompoundKeyColumn(MetamodelImpl metamodel, EmbeddableType keyObj, StringBuilder builder,
        boolean isPresent, CQLTranslator translator, String fieldName, String condition, List<Object> value,
        boolean useInClause) {
    fieldName = fieldName.substring(fieldName.indexOf(".") + 1);

    // If partition key part age given in query, i.e. restriction on
    // id.compositekey.compositePartitionkey.partitionkeyColumn.
    if (fieldName.indexOf(".") > 0) {
        String compositePartitionkeyName = fieldName.substring(0, fieldName.indexOf("."));
        AbstractAttribute attribute = (AbstractAttribute) keyObj.getAttribute(compositePartitionkeyName);
        fieldName = fieldName.substring(fieldName.indexOf(".") + 1);

        EmbeddableType compositePartitionkey = metamodel.embeddable(attribute.getBindableJavaType());

        attribute = (AbstractAttribute) compositePartitionkey.getAttribute(fieldName);

        String columnName = attribute.getJPAColumnName();

        isPresent = buildWhereClause(builder, isPresent, translator, condition, value, useInClause, attribute,
                columnName, false);
    }
    // if composite partition key object is given in query, i.e. restriction
    // on id.compositekey.compositePartitionkey
    else if (metamodel
            .isEmbeddable(((AbstractAttribute) keyObj.getAttribute(fieldName)).getBindableJavaType())) {
        AbstractAttribute attribute = (AbstractAttribute) keyObj.getAttribute(fieldName);
        Set<Attribute> attributes = metamodel.embeddable(attribute.getBindableJavaType()).getAttributes();

        if (!useInClause) {
            // Iterating and appending each column of composite partition
            // key in query builder.
            for (Attribute nestedAttribute : attributes) {
                String columnName = ((AbstractAttribute) nestedAttribute).getJPAColumnName();
                Object valueObject = PropertyAccessorHelper.getObject(value.isEmpty() ? null : value.get(0),
                        (Field) nestedAttribute.getJavaMember());
                translator.buildWhereClause(builder, nestedAttribute.getJavaType(), columnName, valueObject,
                        condition, false);
            }
        } else {
            throw new IllegalArgumentException("In clause is not supported on first part of partition key.");
        }
        isPresent = true;
    }
    // if Not a composite partition key,
    // id.compositekey.partitionkey/clusterKey.
    else {
        AbstractAttribute attribute = (AbstractAttribute) keyObj.getAttribute(fieldName);
        String columnName = attribute.getJPAColumnName();
        isPresent = buildWhereClause(builder, isPresent, translator, condition, value, useInClause, attribute,
                columnName, false);
    }
    return isPresent;
}

From source file:com.impetus.kundera.query.KunderaQuery.java

/**
 * Filter jpa parameter info./*  ww w .j av  a 2 s  .  c om*/
 * 
 * @param type
 *            the type
 * @param name
 *            the name
 * @param fieldName
 *            the field name
 */
private void filterJPAParameterInfo(Type type, String name, String fieldName) {
    String attributeName = getAttributeName(fieldName);
    Attribute entityAttribute = ((MetamodelImpl) kunderaMetadata.getApplicationMetadata()
            .getMetamodel(persistenceUnit)).getEntityAttribute(entityClass, attributeName);
    Class fieldType = entityAttribute.getJavaType();

    if (type.equals(Type.INDEXED)) {
        typedParameter.addJPAParameter(new JPAParameter(null, Integer.valueOf(name), fieldType));
    } else {
        typedParameter.addJPAParameter(new JPAParameter(name, null, fieldType));
    }
}