Example usage for java.lang.reflect Field isAnnotationPresent

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

Introduction

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

Prototype

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

Source Link

Usage

From source file:com.github.gekoh.yagen.util.MappingUtils.java

public static boolean fkIsNullable(Field field) {
    if (field.isAnnotationPresent(ManyToOne.class) && !field.getAnnotation(ManyToOne.class).optional()) {
        return false;
    }/*from  www.  j ava  2 s .co  m*/
    if (field.isAnnotationPresent(JoinColumn.class) && !field.getAnnotation(JoinColumn.class).nullable()) {
        return false;
    }
    if (field.isAnnotationPresent(OneToMany.class)) {
        String mappedBy = field.getAnnotation(OneToMany.class).mappedBy();
        if (StringUtils.isNotEmpty(mappedBy)) {
            try {
                Class targetEntity = MappingUtils.determineTargetEntity(field);
                Field fkField = targetEntity.getDeclaredField(mappedBy);
                if (fkField.isAnnotationPresent(JoinColumn.class)
                        && !fkField.getAnnotation(JoinColumn.class).nullable()) {
                    return false;
                }
            } catch (NoSuchFieldException e) {
                LOG.error("unable to get mappedBy field", e);
            }
        }
    }
    return true;
}

From source file:org.uimafit.factory.ConfigurationParameterFactory.java

/**
 * This method determines if the field is annotated with
 * {@link org.uimafit.descriptor.ConfigurationParameter}.
 *///from   ww  w  .j a v a  2 s  . c  o m
public static boolean isConfigurationParameterField(Field field) {
    return field.isAnnotationPresent(org.uimafit.descriptor.ConfigurationParameter.class);
}

From source file:org.agiso.core.i18n.util.I18nUtils.java

public static String getCode(Field f) {
    if (f.isAnnotationPresent(I18n.class)) {
        if (f.getAnnotation(I18n.class).value().length() > 0) {
            return f.getAnnotation(I18n.class).value();
        } else {//from   w  w w.  j  a  va2  s. c  o m
            return f.getDeclaringClass().getName() + CODE_SEPARATOR + f.getName();
        }
    }
    // else if(f.isAnnotationPresent(I18nRef.class)) {
    //    Object ref = f.getAnnotation(I18nRef.class).value();
    //    if(((Class<?>)ref).isEnum()) {
    //       return getCode((Enum<?>)ref);
    //    } else {
    //       return getCode((Class<?>)ref);
    //    }
    // }
    return f.getDeclaringClass().getName() + CODE_SEPARATOR + f.getName();
}

From source file:gr.abiss.calipso.jpasearch.specifications.GenericSpecifications.java

private static IPredicateFactory<?> getPredicateFactoryForClass(Field field) {
    Class clazz = field.getType();
    if (clazz.isEnum()) {
        return new EnumStringPredicateFactory(clazz);
    } else if (Persistable.class.isAssignableFrom(clazz)) {
        if (field.isAnnotationPresent(CurrentPrincipalIdPredicate.class)) {
            return currentPrincipalPredicateFactory;
        } else {//from  ww w  .  j ava2s.co m
            return anyToOnePredicateFactory;
        }
    } else {
        return factoryForClassMap.get(clazz);
    }
}

From source file:br.gov.frameworkdemoiselle.ldap.internal.ClazzUtils.java

/**
 * Get Distinguished Name value of a @LDAPEntry annotated object. The
 * Distinguished Name will be get by annotation @DistinguishedName if not
 * present or is null, will be get from value of @ParentDN annotation
 * concatenate with @Id/*from w w w  .j a  va  2 s. c  om*/
 * 
 * @param entry
 * @return Distinguished Name
 */
public static String getDistinguishedName(Object entry) {
    isAnnotationPresent(entry.getClass(), LDAPEntry.class, true);

    Field idField = null;
    Field parentDnField = null;

    for (Field field : getSuperClassesFields(entry.getClass())) {
        if (field.isAnnotationPresent(DistinguishedName.class)) {
            Object dn = Reflections.getFieldValue(field, entry);
            if (dn != null)
                return (String) dn;
        } else if (field.isAnnotationPresent(Id.class))
            idField = field;
        else if (field.isAnnotationPresent(ParentDN.class))
            parentDnField = field;
    }

    if (parentDnField != null && idField != null)
        return getFieldName(idField) + "=" + (String) Reflections.getFieldValue(idField, entry) + ","
                + (String) Reflections.getFieldValue(parentDnField, entry);

    throw new EntryException(
            "Field with @DistinguishedName or fields with @ParentDN and @Id not found on class "
                    + entry.getClass().getSimpleName());
}

From source file:com.github.gekoh.yagen.util.MappingUtils.java

public static Set<Field> getFielsWith(Class<? extends Annotation> a, Class clazz) {
    Set<Field> fields = new HashSet<Field>();

    for (Field field : clazz.getDeclaredFields()) {
        if (field.isAnnotationPresent(a)) {
            fields.add(field);// w  w w.  j av a  2 s.  c o m
        }
    }

    return fields;
}

From source file:com.github.gekoh.yagen.util.MappingUtils.java

public static boolean fkIsPhysicallyNullable(Field field) {
    return (MappingUtils.fkIsNullable(field) || field.isAnnotationPresent(CascadeNullable.class))
            && !field.isAnnotationPresent(CascadeDelete.class);
}

From source file:com.erudika.para.core.ParaObjectUtils.java

/**
 * Returns a map of annotated fields of a domain object. Only annotated fields are returned. This method forms the
 * basis of an Object/Grid Mapper. It converts an object to a map of key/value pairs. That map can later be
 * persisted to a data store./* w w w . ja v a 2s.  com*/
 * <br>
 * If {@code convertNestedToJsonString} is true all field values that are objects (i.e. not primitive types or
 * wrappers) are converted to a JSON string otherwise they are left as they are and will be serialized as regular
 * JSON objects later (structure is preserved). Null is considered a primitive type. Transient fields and
 * serialVersionUID are skipped.
 *
 * @param <P> the object type
 * @param pojo the object to convert to a map
 * @param filter a filter annotation. fields that have it will be skipped
 * @param convertNestedToJsonString true if you want to flatten the nested objects to a JSON string.
 * @return a map of fields and their values
 */
public static <P extends ParaObject> Map<String, Object> getAnnotatedFields(P pojo,
        Class<? extends Annotation> filter, boolean convertNestedToJsonString) {
    HashMap<String, Object> map = new HashMap<String, Object>();
    if (pojo == null) {
        return map;
    }
    try {
        List<Field> fields = getAllDeclaredFields(pojo.getClass());
        // filter transient fields and those without annotations
        for (Field field : fields) {
            boolean dontSkip = ((filter == null) ? true : !field.isAnnotationPresent(filter));
            if (field.isAnnotationPresent(Stored.class) && dontSkip) {
                String name = field.getName();
                Object value = PropertyUtils.getProperty(pojo, name);
                if (!Utils.isBasicType(field.getType()) && convertNestedToJsonString) {
                    value = getJsonWriterNoIdent().writeValueAsString(value);
                }
                map.put(name, value);
            }
        }
    } catch (Exception ex) {
        logger.error(null, ex);
    }

    return map;
}

From source file:com.erudika.para.core.ParaObjectUtils.java

/**
 * Converts a map of fields/values to a domain object. Only annotated fields are populated. This method forms the
 * basis of an Object/Grid Mapper.//from w w w  .  jav a 2  s  . c om
 * <br>
 * Map values that are JSON objects are converted to their corresponding Java types. Nulls and primitive types are
 * preserved.
 *
 * @param <P> the object type
 * @param pojo the object to populate with data
 * @param data the map of fields/values
 * @param filter a filter annotation. fields that have it will be skipped
 * @return the populated object
 */
public static <P extends ParaObject> P setAnnotatedFields(P pojo, Map<String, Object> data,
        Class<? extends Annotation> filter) {
    if (data == null || data.isEmpty()) {
        return null;
    }
    try {
        if (pojo == null) {
            // try to find a declared class in the core package
            pojo = (P) toClass((String) data.get(Config._TYPE)).getConstructor().newInstance();
        }
        List<Field> fields = getAllDeclaredFields(pojo.getClass());
        Map<String, Object> props = new HashMap<String, Object>(data);
        for (Field field : fields) {
            boolean dontSkip = ((filter == null) ? true : !field.isAnnotationPresent(filter));
            String name = field.getName();
            Object value = data.get(name);
            if (field.isAnnotationPresent(Stored.class) && dontSkip) {
                // try to read a default value from the bean if any
                if (value == null && PropertyUtils.isReadable(pojo, name)) {
                    value = PropertyUtils.getProperty(pojo, name);
                }
                // handle complex JSON objects deserialized to Maps, Arrays, etc.
                if (!Utils.isBasicType(field.getType()) && value instanceof String) {
                    // in this case the object is a flattened JSON string coming from the DB
                    value = getJsonReader(field.getType()).readValue(value.toString());
                }
                field.setAccessible(true);
                BeanUtils.setProperty(pojo, name, value);
            }
            props.remove(name);
        }
        // handle unknown (user-defined) fields
        if (!props.isEmpty() && pojo instanceof Sysprop) {
            for (Map.Entry<String, Object> entry : props.entrySet()) {
                String name = entry.getKey();
                Object value = entry.getValue();
                // handle the case where we have custom user-defined properties
                // which are not defined as Java class fields
                if (!PropertyUtils.isReadable(pojo, name)) {
                    if (value == null) {
                        ((Sysprop) pojo).removeProperty(name);
                    } else {
                        ((Sysprop) pojo).addProperty(name, value);
                    }
                }
            }
        }
    } catch (Exception ex) {
        logger.error(null, ex);
        pojo = null;
    }
    return pojo;
}

From source file:com.github.gekoh.yagen.util.FieldInfo.java

private static void addAttributeOverrides(Map<String, String> overrides, String path, Class type) {
    for (Field field : type.getDeclaredFields()) {
        String curPath = path + field.getName() + ".";
        Column column;/*from  www . ja v a2  s  .c  om*/
        if (field.isAnnotationPresent(AttributeOverride.class)) {
            addAttributeOverride(overrides, addNamePrefixToAttributeOverride(
                    formatAnnotation(field.getAnnotation(AttributeOverride.class)), curPath));
        } else if (field.isAnnotationPresent(AttributeOverrides.class)) {
            for (AttributeOverride attributeOverride : field.getAnnotation(AttributeOverrides.class).value()) {
                addAttributeOverride(overrides,
                        addNamePrefixToAttributeOverride(formatAnnotation(attributeOverride), curPath));
            }
        } else if (((column = field.getAnnotation(Column.class)) != null
                && (!column.nullable() || column.unique()))
                || (field.isAnnotationPresent(Basic.class) && !field.getAnnotation(Basic.class).optional())) {
            String columnName = column != null ? column.name() : field.getName();
            int length = column != null ? column.length() : 255;

            String override = "@javax.persistence.AttributeOverride(name=\"" + path + field.getName()
                    + "\", column=" + "@javax.persistence.Column(name=\"" + columnName + "\", length=" + length
                    + ", nullable=true, unique=false))";

            addAttributeOverride(overrides, override);
        }

        if (field.isAnnotationPresent(Embedded.class)) {
            addAttributeOverrides(overrides, curPath, field.getType());
        }
    }
}