Example usage for java.lang.reflect Field getAnnotations

List of usage examples for java.lang.reflect Field getAnnotations

Introduction

In this page you can find the example usage for java.lang.reflect Field getAnnotations.

Prototype

public Annotation[] getAnnotations() 

Source Link

Usage

From source file:com.prepaird.objectgraphdb.ObjectGraphDb.java

/**
 *
 * @param o          should be an entity attached to the db
 * @param iFetchPlan/*from  w ww.  j  ava2 s  . c  om*/
 * @param iCreate
 * @return
 */
public Object loadRelatedPojos(final Object o, final String iFetchPlan) {
    if (!isLoadRelatedPojos()) {
        return o;
    }
    //the objects returned here are proxy object custom to orientdb. The actual class is just the superclass of the object returned
    Class cl = o.getClass();
    while (cl.getSuperclass() != null) {
        for (Field f : cl.getDeclaredFields()) {
            f.setAccessible(true);
            //TODO use another method to get the specific annotations
            for (Annotation a : f.getAnnotations()) {
                if (isOGAnnotation(a.annotationType())) {
                    try {
                        Method setterMethod = Utils.getSetterMethod(cl, f);
                        if (setterMethod != null) {
                            if (a.annotationType() == OGRelation.class) {
                                OGRelation rel = (OGRelation) a;
                                OGBinder ogb = (OGBinder) rel.binder().newInstance();
                                setterMethod.invoke(o, ogb.onLoad(this, getRecordByUserObject(o, false)));
                            } else {
                                boolean idOnly;
                                Collection relations;

                                if (a.annotationType() == OEdgeRelation.class) {
                                    OEdgeRelation rel = (OEdgeRelation) a;
                                    idOnly = rel.idOnly();
                                    relations = getExistingVertices(o, f, rel);
                                    sortCollectionIfNecessary(relations, rel);

                                } else { // (a.annotationType() == OVertexRelation.class)
                                    //load the vertices connected to this edge
                                    OVertexRelation rel = (OVertexRelation) a;
                                    idOnly = rel.idOnly();
                                    relations = getExistingVertices(o, f, rel);
                                }
                                Object[] setterParam = new Object[1];
                                boolean isCollection = Iterable.class.isAssignableFrom(f.getType());
                                if (isCollection) {
                                    setterParam[0] = relations;
                                } else if (relations.iterator().hasNext()) {
                                    setterParam[0] = relations.iterator().next();
                                } else {
                                    setterParam[0] = null;
                                }
                                if (idOnly) {
                                    setterParam[0] = convertToIdType(f, setterParam[0]);
                                }
                                setterMethod.invoke(o, setterParam);
                            }
                        } else {
                            Log.error("Cannot set " + f.getName() + " for class " + cl.getName());
                        }
                    } catch (RuntimeException ex) {
                        Log.error(ex);
                        throw ex;
                    } catch (Exception ex) {
                        Log.error(ex);
                    }

                }
            }
        }
        cl = cl.getSuperclass();
    }
    return o;
}

From source file:adalid.core.AbstractArtifact.java

void annotate(Field field) {
    if (field == null) {
        return;//from ww w .  jav  a 2  s  .  c o  m
    }
    Annotation[] annotations = field.getAnnotations();
    List<Class<? extends Annotation>> valid = getValidFieldAnnotations();
    checkAnnotations(field, annotations, valid);
}

From source file:py.una.pol.karaku.dao.entity.interceptors.InterceptorHandler.java

/**
 * Intercepta un atributo de un bean especifico.
 * //ww w  .j a  v a  2 s.c o  m
 * <p>
 * Reglas:
 * <ol>
 * <li>Si el item es un atributo normal, invocar a su respectivo
 * interceptor.
 * </p>
 * <li>Si es una coleccin, y tiene tiene la anotacin {@link OneToMany}, y
 * su {@link CascadeType} es {@link CascadeType#ALL}, entonces se propaga la
 * intercepcin a los miembros de la coleccin. </p>
 * 
 * @param op
 *            Operacin actual.
 * @param field
 *            campo sobre el cual se esta ejecutando.
 * @param bean
 *            objeto que esta siendo interceptado.
 */
private void intercept(@Nonnull Operation op, @Nonnull Field field, @Nonnull Object bean) {

    if (field.getAnnotation(OneToMany.class) != null) {
        OneToMany otm = field.getAnnotation(OneToMany.class);
        CascadeType[] cascade = otm.cascade();
        if (cascade != null && ListHelper.contains(cascade, CascadeType.ALL)) {
            field.setAccessible(true);
            Collection<?> c = (Collection<?>) ReflectionUtils.getField(field, bean);
            if (Hibernate.isInitialized(c) && ListHelper.hasElements(c)) {
                for (Object o : c) {
                    this.intercept(op, o);
                }
            }
        }
        return;
    }
    field.setAccessible(true);
    Class<?> type = field.getType();

    Set<Interceptor> typeInterceptors = addAll(byType.get(void.class), byType.get(type));

    Annotation[] annons = field.getAnnotations();

    Set<Interceptor> annonInterceptors = new HashSet<Interceptor>();
    if (byAnnotation.get(void.class) != null) {
        annonInterceptors.addAll(byAnnotation.get(void.class));
    }

    for (Annotation an : annons) {
        if (byAnnotation.get(an.annotationType()) != null) {
            annonInterceptors.addAll(byAnnotation.get(an.annotationType()));
        }
    }

    typeInterceptors.retainAll(annonInterceptors);

    for (Interceptor bi : typeInterceptors) {
        if (this.isAssignable(field) && bi.interceptable(op, field, bean)) {
            bi.intercept(op, field, bean);
        }
    }
}

From source file:org.apache.syncope.core.persistence.jpa.dao.AbstractAnySearchDAO.java

protected Triple<PlainSchema, PlainAttrValue, AnyCond> check(final AnyCond cond, final AnyTypeKind kind) {
    AnyCond condClone = SerializationUtils.clone(cond);

    AnyUtils attrUtils = anyUtilsFactory.getInstance(kind);

    // Keeps track of difference between entity's getKey() and JPA @Id fields
    if ("key".equals(condClone.getSchema())) {
        condClone.setSchema("id");
    }//w w  w  . ja va2 s  . c o  m

    Field anyField = ReflectionUtils.findField(attrUtils.anyClass(), condClone.getSchema());
    if (anyField == null) {
        LOG.warn("Ignoring invalid schema '{}'", condClone.getSchema());
        throw new IllegalArgumentException();
    }

    PlainSchema schema = new JPAPlainSchema();
    schema.setKey(anyField.getName());
    for (AttrSchemaType attrSchemaType : AttrSchemaType.values()) {
        if (anyField.getType().isAssignableFrom(attrSchemaType.getType())) {
            schema.setType(attrSchemaType);
        }
    }

    // Deal with any Integer fields logically mapping to boolean values
    boolean foundBooleanMin = false;
    boolean foundBooleanMax = false;
    if (Integer.class.equals(anyField.getType())) {
        for (Annotation annotation : anyField.getAnnotations()) {
            if (Min.class.equals(annotation.annotationType())) {
                foundBooleanMin = ((Min) annotation).value() == 0;
            } else if (Max.class.equals(annotation.annotationType())) {
                foundBooleanMax = ((Max) annotation).value() == 1;
            }
        }
    }
    if (foundBooleanMin && foundBooleanMax) {
        schema.setType(AttrSchemaType.Boolean);
    }

    // Deal with any fields representing relationships to other entities
    if (anyField.getType().getAnnotation(Entity.class) != null) {
        Method relMethod = null;
        try {
            relMethod = ClassUtils.getPublicMethod(anyField.getType(), "getKey", new Class<?>[0]);
        } catch (Exception e) {
            LOG.error("Could not find {}#getKey", anyField.getType(), e);
        }

        if (relMethod != null && String.class.isAssignableFrom(relMethod.getReturnType())) {
            condClone.setSchema(condClone.getSchema() + "_id");
            schema.setType(AttrSchemaType.String);
        }
    }

    PlainAttrValue attrValue = attrUtils.newPlainAttrValue();
    if (condClone.getType() != AttributeCond.Type.LIKE && condClone.getType() != AttributeCond.Type.ILIKE
            && condClone.getType() != AttributeCond.Type.ISNULL
            && condClone.getType() != AttributeCond.Type.ISNOTNULL) {

        try {
            ((JPAPlainSchema) schema).validator().validate(condClone.getExpression(), attrValue);
        } catch (ValidationException e) {
            LOG.error("Could not validate expression '" + condClone.getExpression() + "'", e);
            throw new IllegalArgumentException();
        }
    }

    return Triple.of(schema, attrValue, condClone);
}

From source file:org.compass.annotations.config.binding.AnnotationsMappingBinding.java

/**
 * Recursivly process the class to find all it's annotations. Lower level
 * class/interfaces with annotations will be added first.
 *///  ww w  .j a v a2 s .c  o  m
private void processAnnotatedClass(Class<?> clazz) {
    if (clazz.equals(Class.class)) {
        return;
    }
    Class<?> superClazz = clazz.getSuperclass();
    if (superClazz != null && !superClazz.equals(Object.class)) {
        processAnnotatedClass(superClazz);
    }
    Class<?>[] interfaces = clazz.getInterfaces();
    for (Class<?> anInterface : interfaces) {
        processAnnotatedClass(anInterface);
    }

    SearchableConstant searchableConstant = clazz.getAnnotation(SearchableConstant.class);
    if (searchableConstant != null) {
        bindConstantMetaData(searchableConstant);
    }

    SearchableConstants searchableConstants = clazz.getAnnotation(SearchableConstants.class);
    if (searchableConstants != null) {
        for (SearchableConstant metaData : searchableConstants.value()) {
            bindConstantMetaData(metaData);
        }
    }

    SearchableDynamicMetaData searchableDynamicMetaData = clazz.getAnnotation(SearchableDynamicMetaData.class);
    if (searchableDynamicMetaData != null) {
        bindDynamicMetaData(searchableDynamicMetaData);
    }
    SearchableDynamicMetaDatas searchableDynamicMetaDatas = clazz
            .getAnnotation(SearchableDynamicMetaDatas.class);
    if (searchableDynamicMetaDatas != null) {
        for (SearchableDynamicMetaData metaData : searchableDynamicMetaDatas.value()) {
            bindDynamicMetaData(metaData);
        }
    }

    // handles recursive extends and the original extend
    if (clazz.isAnnotationPresent(Searchable.class)) {
        Searchable searchable = clazz.getAnnotation(Searchable.class);
        String[] extend = searchable.extend();
        if (extend.length != 0) {
            ArrayList<String> extendedMappings = new ArrayList<String>();
            if (classMapping.getExtendedAliases() != null) {
                extendedMappings.addAll(Arrays.asList(classMapping.getExtendedAliases()));
            }
            for (String extendedAlias : extend) {
                Alias extendedAliasLookup = valueLookup.lookupAlias(extendedAlias);
                if (extendedAliasLookup == null) {
                    extendedMappings.add(extendedAlias);
                } else {
                    extendedMappings.add(extendedAliasLookup.getName());
                }
            }
            classMapping.setExtendedAliases(extendedMappings.toArray(new String[extendedMappings.size()]));
        }
    }

    // if the super class has Searchable annotation as well, add it to the list of extends
    ArrayList<Class> extendedClasses = new ArrayList<Class>();
    if (clazz.getSuperclass() != null) {
        extendedClasses.add(clazz.getSuperclass());
    }
    extendedClasses.addAll(Arrays.asList(clazz.getInterfaces()));
    for (Class<?> superClass : extendedClasses) {
        if (!superClass.isAnnotationPresent(Searchable.class)) {
            continue;
        }
        Searchable superSearchable = superClass.getAnnotation(Searchable.class);
        String alias = getAliasFromSearchableClass(superClass, superSearchable);
        HashSet<String> extendedMappings = new HashSet<String>();
        if (classMapping.getExtendedAliases() != null) {
            extendedMappings.addAll(Arrays.asList(classMapping.getExtendedAliases()));
        }
        extendedMappings.add(alias);
        classMapping.setExtendedAliases(extendedMappings.toArray(new String[extendedMappings.size()]));
    }

    for (Field field : clazz.getDeclaredFields()) {
        for (Annotation annotation : field.getAnnotations()) {
            processsAnnotatedElement(clazz, field.getName(), "field", field.getType(), field.getGenericType(),
                    annotation, field);
        }
    }
    for (Method method : clazz.getDeclaredMethods()) {
        if (!method.isSynthetic() && !method.isBridge() && !Modifier.isStatic(method.getModifiers())
                && method.getParameterTypes().length == 0 && method.getReturnType() != void.class
                && (method.getName().startsWith("get") || method.getName().startsWith("is"))) {

            for (Annotation annotation : method.getAnnotations()) {
                processsAnnotatedElement(clazz, ClassUtils.getShortNameForMethod(method), "property",
                        method.getReturnType(), method.getGenericReturnType(), annotation, method);
            }
        }
    }
}

From source file:org.jobjects.dao.annotation.Manager.java

private String loadSqlDelete(String usualTable, Field[] fields) {
    String sql = "DELETE FROM " + usualTable;
    sql += " WHERE ";

    boolean first = true;
    for (Field field : fields) {
        Annotation[] annotations = field.getAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation instanceof DaoField) {
                if (((DaoField) annotation).isPrimary()) {
                    if (first) {
                        first = false;//  w  w  w . ja  v  a 2 s . co  m
                    } else {
                        sql += " AND ";
                    }
                    sql += ((DaoField) annotation).fieldName() + "=?";
                }
                break;
            }
        }
    }
    return sql;
}

From source file:org.jobjects.dao.annotation.Manager.java

private String loadSqlExist(String usualTable, Field[] fields) {
    String sql = "SELECT COUNT(*)";
    sql += " FROM " + usualTable + " WHERE ";

    boolean first = true;
    for (Field field : fields) {
        Annotation[] annotations = field.getAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation instanceof DaoField) {
                if (((DaoField) annotation).isPrimary()) {
                    if (first) {
                        first = false;//  w ww.  j a  v a 2s . c o m
                    } else {
                        sql += " AND ";
                    }
                    sql += ((DaoField) annotation).fieldName() + "=?";
                }
                break;
            }
        }
    }
    return sql;
}

From source file:org.jobjects.dao.annotation.Manager.java

private String loadSqlSave(String usualTable, Field[] fields) {
    String sql = "UPDATE " + usualTable + " SET ";

    boolean first = true;
    for (Field field : fields) {
        Annotation[] annotations = field.getAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation instanceof DaoField) {
                if (!((DaoField) annotation).isPrimary()) {
                    if (first) {
                        first = false;//  w  w  w .  j  av a 2 s .  c  o  m
                    } else {
                        sql += ", ";
                    }
                    sql += ((DaoField) annotation).fieldName() + "=?";
                }
                break;
            }
        }
    }
    sql += " WHERE ";
    first = true;
    for (Field field : fields) {
        Annotation[] annotations = field.getAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation instanceof DaoField) {
                if (((DaoField) annotation).isPrimary()) {
                    if (first) {
                        first = false;
                    } else {
                        sql += " AND ";
                    }
                    sql += ((DaoField) annotation).fieldName() + "=?";
                }
                break;
            }
        }
    }
    return sql;
}

From source file:org.jobjects.dao.annotation.Manager.java

/**
 * @param beanPk le bean  supprimer//  w ww.  j a  va  2 s  .  c o m
 * @throws RemoveException Problme de suppression
 */
public final void remove(final P beanPk) throws RemoveException {
    String msg = "Delete error " + entityClass.getCanonicalName() + " : "
            + ToStringBuilder.reflectionToString(beanPk, ToStringStyle.MULTI_LINE_STYLE);

    try {
        Connection connection = getConnection();
        try {
            if (null == sql_delete) {
                sql_delete = loadSqlDelete(usualTable, fields);
            }
            PreparedStatement pstmt = connection.prepareStatement(sql_delete);
            try {
                int i = 1;
                for (Field field : fields) {
                    Annotation[] annotations = field.getAnnotations();
                    for (Annotation annotation : annotations) {
                        if (annotation instanceof DaoField) {
                            if (((DaoField) annotation).isPrimary()) {
                                Object obj = BeanUtils.getProperty(beanPk, field.getName());
                                if (obj == null) {
                                    pstmt.setNull(i++, ((DaoField) annotation).type());
                                } else {
                                    setAll(pstmt, i++, obj);
                                }
                            }
                            break;
                        }
                    }
                }
                pstmt.executeUpdate();
            } finally {
                pstmt.close();
            }
            pstmt = null;
        } finally {
            connection.close();
        }
        connection = null;
    } catch (Exception sqle) {
        log.error(msg, sqle);
        throw new RemoveException(msg, sqle);
    }

}