Example usage for java.lang.reflect AccessibleObject isAnnotationPresent

List of usage examples for java.lang.reflect AccessibleObject isAnnotationPresent

Introduction

In this page you can find the example usage for java.lang.reflect AccessibleObject isAnnotationPresent.

Prototype

@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) 

Source Link

Usage

From source file:com.yahoo.elide.core.EntityBinding.java

/**
 * Bind fields of an entity including the Id field, attributes, and relationships.
 *
 * @param cls Class type to bind fields//from w w w .  j  ava  2s  .  co  m
 * @param type JSON API type identifier
 * @param fieldOrMethodList List of fields and methods on entity
 */
private void bindEntityFields(Class<?> cls, String type, Collection<AccessibleObject> fieldOrMethodList) {
    for (AccessibleObject fieldOrMethod : fieldOrMethodList) {
        bindTrigger(OnCreate.class, fieldOrMethod);
        bindTrigger(OnDelete.class, fieldOrMethod);
        bindTrigger(OnUpdate.class, fieldOrMethod);
        bindTrigger(OnCommit.class, fieldOrMethod);

        if (fieldOrMethod.isAnnotationPresent(Id.class)) {
            bindEntityId(cls, type, fieldOrMethod);
        } else if (fieldOrMethod.isAnnotationPresent(Transient.class)
                && !fieldOrMethod.isAnnotationPresent(ComputedAttribute.class)) {
            continue; // Transient. Don't serialize
        } else if (!fieldOrMethod.isAnnotationPresent(Exclude.class)) {
            if (fieldOrMethod instanceof Field
                    && Modifier.isTransient(((Field) fieldOrMethod).getModifiers())) {
                continue; // Transient. Don't serialize
            }
            if (fieldOrMethod instanceof Method
                    && Modifier.isTransient(((Method) fieldOrMethod).getModifiers())) {
                continue; // Transient. Don't serialize
            }
            if (fieldOrMethod instanceof Field && !fieldOrMethod.isAnnotationPresent(Column.class)
                    && Modifier.isStatic(((Field) fieldOrMethod).getModifiers())) {
                continue; // Field must have Column annotation?
            }
            bindAttrOrRelation(cls, fieldOrMethod);
        }
    }
}

From source file:com.github.gekoh.yagen.ddl.TableConfig.java

private void gatherPkColumn(Class entityClass) {
    Set<AccessibleObject> fieldsOrMethods = getAnnotatedFieldOrMethod(new HashSet<AccessibleObject>(), Id.class,
            entityClass, true);//from   w  ww  .j  a v  a 2s. c  om

    if (entityClass.isAnnotationPresent(PrimaryKeyJoinColumn.class)) {
        pkColnames = Arrays
                .asList(((PrimaryKeyJoinColumn) entityClass.getAnnotation(PrimaryKeyJoinColumn.class)).name());
    } else if (fieldsOrMethods.size() > 0) {
        pkColnames = new ArrayList<String>();
        for (AccessibleObject fieldOrMethod : fieldsOrMethods) {
            String colName = null;
            if (fieldOrMethod.isAnnotationPresent(Column.class)) {
                colName = fieldOrMethod.getAnnotation(Column.class).name();
            }
            if (colName == null && fieldOrMethod instanceof Field) {
                colName = ((Field) fieldOrMethod).getName();
            }
            if (colName != null) {
                pkColnames.add(colName);
            }
        }
    }
}

From source file:com.clarkparsia.empire.annotation.RdfGenerator.java

/**
 * Return the given Java bean as a set of RDF triples
 * @param theObj the object//  w  w w.  ja v  a  2 s. c o m
 * @return the object represented as RDF triples
 * @throws InvalidRdfException thrown if the object cannot be transformed into RDF.
 */
public static Graph asRdf(final Object theObj) throws InvalidRdfException {
    if (theObj == null) {
        return null;
    }

    Object aObj = theObj;

    if (aObj instanceof ProxyHandler) {
        aObj = ((ProxyHandler) aObj).mProxy.value();
    } else {
        try {
            if (aObj.getClass().getDeclaredField("handler") != null) {
                Field aProxy = aObj.getClass().getDeclaredField("handler");
                aObj = ((ProxyHandler) BeanReflectUtil.safeGet(aProxy, aObj)).mProxy.value();
            }
        } catch (InvocationTargetException e) {
            // this is probably an error, we know its a proxy object, but can't get the proxied object
            throw new InvalidRdfException("Could not access proxy object", e);
        } catch (NoSuchFieldException e) {
            // this is probably ok.
        }
    }

    RdfsClass aClass = asValidRdfClass(aObj);

    Resource aSubj = id(aObj);

    addNamespaces(aObj.getClass());

    GraphBuilder aBuilder = new GraphBuilder();

    Collection<AccessibleObject> aAccessors = new HashSet<AccessibleObject>();
    aAccessors.addAll(getAnnotatedFields(aObj.getClass()));
    aAccessors.addAll(getAnnotatedGetters(aObj.getClass(), true));

    try {
        ResourceBuilder aRes = aBuilder.instance(
                aBuilder.getValueFactory().createURI(PrefixMapping.GLOBAL.uri(aClass.value())), aSubj);

        for (AccessibleObject aAccess : aAccessors) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Getting rdf for : {}", aAccess);
            }

            AsValueFunction aFunc = new AsValueFunction(aAccess);

            if (aAccess.isAnnotationPresent(Transient.class)
                    || (aAccess instanceof Field && Modifier.isTransient(((Field) aAccess).getModifiers()))) {

                // transient fields or accessors with the Transient annotation do not get converted.
                continue;
            }

            RdfProperty aPropertyAnnotation = BeanReflectUtil.getAnnotation(aAccess, RdfProperty.class);
            String aBase = "urn:empire:clark-parsia:";
            if (aRes instanceof URI) {
                aBase = ((URI) aRes).getNamespace();
            }

            URI aProperty = aPropertyAnnotation != null
                    ? aBuilder.getValueFactory()
                            .createURI(PrefixMapping.GLOBAL.uri(aPropertyAnnotation.value()))
                    : (aAccess instanceof Field
                            ? aBuilder.getValueFactory().createURI(aBase + ((Field) aAccess).getName())
                            : null);

            boolean aOldAccess = aAccess.isAccessible();
            setAccessible(aAccess, true);

            Object aValue = get(aAccess, aObj);

            setAccessible(aAccess, aOldAccess);

            if (aValue == null || aValue.toString().equals("")) {
                continue;
            } else if (Collection.class.isAssignableFrom(aValue.getClass())) {
                @SuppressWarnings("unchecked")
                List<Value> aValueList = asList(aAccess, (Collection<?>) Collection.class.cast(aValue));

                if (aValueList.isEmpty()) {
                    continue;
                }

                if (aPropertyAnnotation.isList()) {
                    aRes.addProperty(aProperty, aValueList);
                } else {
                    for (Value aVal : aValueList) {
                        aRes.addProperty(aProperty, aVal);
                    }
                }
            } else {
                aRes.addProperty(aProperty, aFunc.apply(aValue));
            }
        }
    } catch (IllegalAccessException e) {
        throw new InvalidRdfException(e);
    } catch (RuntimeException e) {
        throw new InvalidRdfException(e);
    } catch (InvocationTargetException e) {
        throw new InvalidRdfException("Cannot invoke method", e);
    }

    return aBuilder.graph();
}

From source file:com.github.gekoh.yagen.ddl.TableConfig.java

private void gatherDeferrable(final Map<String, String> attr2colName, final String attrPath, Class type) {
    traverseFieldsAndMethods(type, true, true, new GatherFieldOrMethodInfoAction() {
        @Override//  w  ww . ja  v a2  s  .c o  m
        public void gatherInfo(AccessibleObject fOm) {
            String attributeName = getAttributeName(fOm);
            String attrPathField = attrPath + "." + attributeName;
            Class attributeType = getAttributeType(fOm);

            if (fOm.isAnnotationPresent(Embedded.class)) {
                addAttributeOverrides(attr2colName, attrPathField, fOm);
                gatherDeferrable(attr2colName, attrPathField, attributeType);
            } else if (fOm.isAnnotationPresent(Deferrable.class)) {
                String colName = attr2colName.get(attrPathField);
                if (colName == null) {
                    if (fOm.isAnnotationPresent(JoinColumn.class)) {
                        colName = getIdentifierForReference(fOm.getAnnotation(JoinColumn.class).name());
                    }

                    if (StringUtils.isEmpty(colName)) {
                        colName = getIdentifierForReference(attributeName);
                    }
                    columnNameToDeferrable.put(colName, fOm.getAnnotation(Deferrable.class));
                }
            }
        }
    });
}

From source file:com.github.gekoh.yagen.ddl.TableConfig.java

private void gatherEnumCheckConstraints(final Map<String, String> attr2colName, final String attrPath,
        Class type) {//  w  ww .j ava  2 s.  c o  m
    //        HACK: we are using field annotations, need to skip methods otherwise we would have wrong constraints
    traverseFieldsAndMethods(type, true, false, new GatherFieldOrMethodInfoAction() {
        @Override
        public void gatherInfo(AccessibleObject fOm) {
            String attributeName = getAttributeName(fOm);
            String attrPathField = attrPath + "." + attributeName;
            Class attributeType = getAttributeType(fOm);

            if (fOm.isAnnotationPresent(Embedded.class)) {
                addAttributeOverrides(attr2colName, attrPathField, fOm);
                gatherEnumCheckConstraints(attr2colName, attrPathField, attributeType);
            } else if (attributeType.isEnum()) {
                String colName = attr2colName.get(attrPathField);
                if (colName == null) {
                    if (fOm.isAnnotationPresent(Column.class)) {
                        colName = getIdentifierForReference(fOm.getAnnotation(Column.class).name());
                    }

                    if (StringUtils.isEmpty(colName)) {
                        colName = getIdentifierForReference(attributeName);
                    }
                }
                boolean useName = fOm.isAnnotationPresent(Enumerated.class)
                        && fOm.getAnnotation(Enumerated.class).value() == EnumType.STRING;
                StringBuilder cons = new StringBuilder();
                for (Object e : attributeType.getEnumConstants()) {
                    if (cons.length() > 0) {
                        cons.append(", ");
                    }
                    if (useName) {
                        cons.append("'").append(((Enum) e).name()).append("'");
                    } else {
                        cons.append(((Enum) e).ordinal());
                    }
                }
                columnNameToEnumCheckConstraints.put(colName, cons.toString());
            }
        }
    });

    Class superClass = getEntitySuperclass(type);
    if (superClass != null) {
        gatherEnumCheckConstraints(attr2colName, attrPath, superClass);
    }
}

From source file:com.github.gekoh.yagen.hst.CreateEntities.java

private String createHistoryEntity(String baseClassPackageName, AccessibleObject fieldOrMethod,
        Reader template) {//from   w  w  w .j av a2 s.c o m
    TemporalEntity temporalEntity = fieldOrMethod.getAnnotation(TemporalEntity.class);
    JoinTable joinTable = fieldOrMethod.getAnnotation(JoinTable.class);
    Class targetEntity = null;
    Class declaringClass;
    String packageName;
    String hstEntityClassSimpleName = FieldInfo.toCamelCase(joinTable.name()) + HISTORY_ENTITY_SUFFIX;
    hstEntityClassSimpleName = hstEntityClassSimpleName.substring(0, 1).toUpperCase()
            + hstEntityClassSimpleName.substring(1);

    if (fieldOrMethod.isAnnotationPresent(ManyToMany.class)) {
        targetEntity = MappingUtils.determineTargetEntity(fieldOrMethod,
                fieldOrMethod.getAnnotation(ManyToMany.class).targetEntity());
    } else if (fieldOrMethod.isAnnotationPresent(ManyToOne.class)) {
        targetEntity = MappingUtils.determineTargetEntity(fieldOrMethod,
                fieldOrMethod.getAnnotation(ManyToOne.class).targetEntity());
    } else {
        throw new UnsupportedOperationException(
                "when generating history entity for relation on " + fieldOrMethod);
    }

    if (fieldOrMethod instanceof Field) {
        declaringClass = ((Field) fieldOrMethod).getDeclaringClass();
    } else {
        declaringClass = ((Method) fieldOrMethod).getDeclaringClass();
    }
    packageName = declaringClass.getPackage().getName();

    List<FieldInfo> fieldInfos = new ArrayList<FieldInfo>();

    //      add join columns to both sides of the relation (assumes we have only one each)
    fieldInfos.add(FieldInfo.getIdFieldInfo(declaringClass,
            getFieldNameFromReferencingClassName(declaringClass.getSimpleName()),
            joinTable.joinColumns()[0].name()));
    fieldInfos.add(FieldInfo.getIdFieldInfo(targetEntity,
            getFieldNameFromReferencingClassName(targetEntity.getSimpleName()),
            joinTable.inverseJoinColumns()[0].name()));

    return createHistoryEntity(baseClassPackageName, packageName, hstEntityClassSimpleName,
            temporalEntity.historyTableName(), null, null, template, fieldInfos);
}

From source file:com.github.gekoh.yagen.ddl.TableConfig.java

private void gatherCascade(final Map<String, String> attr2colName, final String attrPath, Class type) {
    //        HACK: we are using field annotations, need to skip methods otherwise we would have wrong constraints
    traverseFieldsAndMethods(type, true, false, new GatherFieldOrMethodInfoAction() {
        @Override/*  w ww . ja va 2 s.c  o m*/
        public void gatherInfo(AccessibleObject fOm) {
            String attributeName = getAttributeName(fOm);
            String attrPathField = attrPath + "." + attributeName;
            Class attributeType = getAttributeType(fOm);
            boolean onDeleteCascade = fOm.isAnnotationPresent(OnDelete.class)
                    ? fOm.getAnnotation(OnDelete.class).action() == OnDeleteAction.CASCADE
                    : false;

            if (fOm.isAnnotationPresent(Embedded.class)) {
                addAttributeOverrides(attr2colName, attrPathField, fOm);
                gatherCascade(attr2colName, attrPathField, attributeType);
            }

            if (fOm.isAnnotationPresent(CascadeNullable.class)) {
                if (onDeleteCascade) {
                    throw new IllegalStateException(
                            "conflicting declaration of @CascadeNullable and CascadeType on relation " + fOm);
                }
                String colName = attr2colName.get(attrPathField);
                if (colName == null) {
                    if (fOm.isAnnotationPresent(JoinColumn.class)) {
                        colName = getIdentifierForReference(fOm.getAnnotation(JoinColumn.class).name());
                    }

                    if (StringUtils.isEmpty(colName)) {
                        colName = getIdentifierForReference(attributeName);
                    }
                    columnNamesIsCascadeNullable.add(colName);
                }
            }

            if (fOm.isAnnotationPresent(NoForeignKeyConstraint.class)) {
                String colName = attr2colName.get(attrPathField);
                if (colName == null) {
                    if (fOm.isAnnotationPresent(JoinColumn.class)) {
                        colName = getIdentifierForReference(fOm.getAnnotation(JoinColumn.class).name());
                    }

                    if (StringUtils.isEmpty(colName)) {
                        colName = getIdentifierForReference(attributeName);
                    }
                    columnNamesIsNoFK.add(colName);
                }
            }

            Set<String> fkCols = new HashSet<String>();
            String fkTableName = null;
            if (fOm.isAnnotationPresent(JoinTable.class)) {
                JoinTable joinTable = fOm.getAnnotation(JoinTable.class);
                fkCols.add(getIdentifierForReference(joinTable.joinColumns()[0].name()));
                if (joinTable.inverseJoinColumns().length > 0) {
                    fkCols.add(getIdentifierForReference(joinTable.inverseJoinColumns()[0].name()));
                }
                fkTableName = joinTable.name();
            } else if (fOm.isAnnotationPresent(OneToMany.class)) {
                JoinColumn joinColumn = getJoinColumn(fOm);
                if (joinColumn != null) {
                    Class<?> targetEntityClass = MappingUtils.determineTargetEntity(fOm,
                            fOm.getAnnotation(OneToMany.class).targetEntity());
                    fkTableName = getTableAnnotation(targetEntityClass).name();
                    fkCols.add(getIdentifierForReference(joinColumn.name()));
                }
            } else if (fOm.isAnnotationPresent(ManyToOne.class) || fOm.isAnnotationPresent(OneToOne.class)) {
                JoinColumn joinColumn = getJoinColumn(fOm);
                if (joinColumn != null) {
                    fkTableName = tableName;
                    fkCols.add(getIdentifierForReference(joinColumn.name()));
                }
            }

            if (fkTableName != null && (onDeleteCascade || fOm.isAnnotationPresent(CascadeDelete.class))) {
                TableConfig fkConfig = ddlEnhancer
                        .getConfigForTableName(getIdentifierForReference(fkTableName));
                if (fkConfig != null) {
                    fkConfig.columnNamesIsCascadeDelete.addAll(fkCols);
                }
            }
        }
    });
}

From source file:com.github.gekoh.yagen.ddl.TableConfig.java

private void processAnnotations(AccessibleObject[] fieldsOrMethods, boolean selectiveRendering) {
    for (AccessibleObject fieldOrMethod : fieldsOrMethods) {
        JoinTable joinTable = fieldOrMethod.getAnnotation(JoinTable.class);
        CollectionTable collectionTable = fieldOrMethod.getAnnotation(CollectionTable.class);
        String joinTableName = joinTable != null ? joinTable.name()
                : collectionTable != null ? collectionTable.name() : null;
        TableConfig joinTableConfig = joinTableName != null
                ? ddlEnhancer.getConfigForTableName(getIdentifierForReference(joinTableName))
                : null;//from w w w  .j  av a2 s .  com

        if (joinTableName != null && joinTableConfig == null) {
            joinTableConfig = new TableConfig(ddlEnhancer, null,
                    ddlEnhancer.getProfile().getNamingStrategy().tableName(joinTableName));
            ddlEnhancer.addTableConfig(joinTableConfig);
        }

        if (joinTableConfig != null) {
            joinTableConfig.putTableAnnotation(joinTable != null ? joinTable : collectionTable);

            if (fieldOrMethod.isAnnotationPresent(IntervalPartitioning.class)) {
                joinTableConfig.putTableAnnotation(fieldOrMethod.getAnnotation(IntervalPartitioning.class));
            }
            if (fieldOrMethod.isAnnotationPresent(Auditable.class)) {
                joinTableConfig.putTableAnnotation(fieldOrMethod.getAnnotation(Auditable.class));
            }
        }

        if (fieldOrMethod.getAnnotation(Profile.class) != null) {
            if (joinTableConfig == null) {
                throw new IllegalArgumentException("need @" + JoinTable.class.getSimpleName() + " or @"
                        + CollectionTable.class.getSimpleName() + " for @" + Profile.class.getSimpleName()
                        + " on a field");
            }
            Profile annotation = fieldOrMethod.getAnnotation(Profile.class);

            if (selectiveRendering
                    && !Arrays.asList(annotation.value()).contains(ddlEnhancer.getProfile().getName())) {
                joinTableConfig.setTableToBeRendered(false);
            }
        }
        if (fieldOrMethod.getAnnotation(TemporalEntity.class) != null) {
            if (joinTableConfig == null) {
                throw new IllegalArgumentException("need @" + JoinTable.class.getSimpleName() + " or @"
                        + CollectionTable.class.getSimpleName() + " for @"
                        + TemporalEntity.class.getSimpleName() + " on a field");
            }
            TemporalEntity annotation = fieldOrMethod.getAnnotation(TemporalEntity.class);

            if (annotation != null) {
                joinTableConfig.putTableAnnotation(annotation);
            }
        }
        if (fieldOrMethod.getAnnotation(Sequence.class) != null) {
            sequences.add(fieldOrMethod.getAnnotation(Sequence.class));
        } else if (fieldOrMethod.getAnnotation(Embedded.class) != null) {
            Class embed;
            if (fieldOrMethod instanceof Field) {
                Field field = (Field) fieldOrMethod;
                embed = field.getType();
            } else if (fieldOrMethod instanceof Method) {
                Method method = (Method) fieldOrMethod;
                embed = method.getReturnType();
            } else {
                throw new IllegalStateException("AccessibleObject not type of Field or Method");
            }
            processTypeAnnotations(embed, selectiveRendering);
        }
        //            if we have a ManyToMany JoinTable and current entity is part of selective rendering,
        //            we also need to render the JoinTable
        else if (fieldOrMethod.isAnnotationPresent(ManyToMany.class)) {
            if (joinTable == null) {
                String propName = fieldOrMethod instanceof Field ? ((Field) fieldOrMethod).getName()
                        : ((Method) fieldOrMethod).getName().substring(3);
                joinTableConfig = new TableConfig(ddlEnhancer, null, ddlEnhancer.getProfile()
                        .getNamingStrategy().collectionTableName(null, getTableName(), null, null, propName));
                ddlEnhancer.addTableConfig(joinTableConfig);
            }
            joinTableConfig.setTableToBeRendered(true);
        }

        if (fieldOrMethod.isAnnotationPresent(Default.class)) {
            String defaultValue = fieldOrMethod.getAnnotation(Default.class).sqlExpression();
            if (fieldOrMethod.isAnnotationPresent(Column.class)) {
                colNameToDefault.put(
                        getIdentifierForReference(fieldOrMethod.getAnnotation(Column.class).name()),
                        defaultValue);
            } else if (fieldOrMethod instanceof Field) {
                colNameToDefault.put(getIdentifierForReference(ddlEnhancer.getProfile().getNamingStrategy()
                        .columnName(((Field) fieldOrMethod).getName())), defaultValue);
            } else {
                LOG.warn(Default.class + " only supported on fields or @{} annotated methods",
                        Column.class.toString());
            }
        }
    }
}