Example usage for java.lang.reflect Field getAnnotation

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

Introduction

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

Prototype

public <T extends Annotation> T getAnnotation(Class<T> annotationClass) 

Source Link

Usage

From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java

@SuppressWarnings("unchecked")
public static void removeInvocationInfo(Object obj, String id) {

    if (obj == null)
        return;//w  w  w.java2 s. c o  m

    for (Field f : obj.getClass().getDeclaredFields()) {
        if (f.getAnnotation(CloudInvocationInfos.class) != null) {

            try {
                f.setAccessible(true);
                if (((List<InvocationInfo>) f.get(obj)).contains(new InvocationInfo(null, id, null, null)))
                    ((List<InvocationInfo>) f.get(obj)).remove(new InvocationInfo(null, id, null, null));
            } catch (Exception e) {
                e.printStackTrace();
                throw new JCloudScaleException(e, "Unexpected error when injecting into @CloudInvocationInfos");
            }

        }
    }

}

From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java

@SuppressWarnings("unchecked")
public static void addInvocationInfo(Object obj, InvocationInfo info) {

    if (obj == null)
        return;/*from ww w. j av  a 2s  .c om*/

    for (Field f : obj.getClass().getDeclaredFields()) {
        if (f.getAnnotation(CloudInvocationInfos.class) != null) {

            try {
                f.setAccessible(true);
                if (f.get(obj) == null)
                    f.set(obj, new LinkedList<InvocationInfo>());
                ((List<InvocationInfo>) f.get(obj)).add(info);
            } catch (Exception e) {
                e.printStackTrace();
                throw new JCloudScaleException(e, "Unexpected error when injecting into @CloudInvocationInfos");
            }

        }
    }

}

From source file:com.google.code.simplestuff.bean.SimpleBean.java

/**
 * //from www .ja  v  a 2s .c o m
 * Returns the hashCode basing considering only the {@link BusinessField}
 * annotated fields.
 * 
 * @param bean The bean.
 * @return The hashCode result.
 * @throws IllegalArgumentException If the bean is not a Business Object.
 */
public static int hashCode(Object bean) {

    if (bean == null) {
        throw new IllegalArgumentException("The bean passed is null!!!");
    }

    BusinessObjectDescriptor businessObjectInfo = BusinessObjectContext
            .getBusinessObjectDescriptor(bean.getClass());

    // We don't need here a not null check since by contract the
    // getBusinessObjectDescriptor method always returns an abject.
    if (businessObjectInfo.getNearestBusinessObjectClass() == null) {
        return bean.hashCode();
        // throw new IllegalArgumentException(
        // "The bean passed is not annotated in the hierarchy as Business Object!!!");
    }

    Collection<Field> annotatedField = businessObjectInfo.getAnnotatedFields();

    HashCodeBuilder builder = new HashCodeBuilder();
    for (Field field : annotatedField) {
        field.setAccessible(true);
        final BusinessField fieldAnnotation = field.getAnnotation(BusinessField.class);
        if ((fieldAnnotation != null) && (fieldAnnotation.includeInHashCode())) {
            try {
                // Vincenzo Vitale(vita) May 23, 2007 2:39:26 PM: some
                // date implementations give not equals values...
                if ((ClassUtils.isAssignable(field.getType(), Date.class))
                        || (ClassUtils.isAssignable(field.getType(), Calendar.class))) {
                    Object fieldValue = PropertyUtils.getProperty(bean, field.getName());
                    if (fieldValue != null) {
                        builder.append(DateUtils.round(fieldValue, Calendar.MILLISECOND));
                    }

                } else {
                    builder.append(PropertyUtils.getProperty(bean, field.getName()));
                }
            } catch (IllegalAccessException e) {
                if (log.isDebugEnabled()) {
                    log.debug("IllegalAccessException exception when calculating the hashcode of class"
                            + bean.getClass().toString(), e);
                }
            } catch (InvocationTargetException e) {
                if (log.isDebugEnabled()) {
                    log.debug("InvocationTargetException exception when calculating the hashcode of class"
                            + bean.getClass().toString(), e);
                }
            } catch (NoSuchMethodException e) {
                if (log.isDebugEnabled()) {
                    log.debug("NoSuchMethodException exception when calculating the hashcode of class"
                            + bean.getClass().toString(), e);
                }
            }
        }
    }

    return builder.toHashCode();

}

From source file:com.google.code.siren4j.util.ReflectionUtils.java

@SuppressWarnings("rawtypes")
public static boolean isSirenProperty(Class<?> type, Object obj, Field field) {
    boolean isProp = false;

    Siren4JProperty anno = field.getAnnotation(Siren4JProperty.class);
    if (anno != null || type.isEnum()) {
        isProp = true;/*  ww  w  .  j a v  a2s  .c  o  m*/
    } else if (ArrayUtils.contains(propertyTypes, type)) {
        isProp = true;
    } else if (obj != null && Collection.class.isAssignableFrom(type)) {
        //Try to determine value type
        if (!((Collection) obj).isEmpty()) {
            Object first = findFirstNonNull(((Collection) obj).iterator());
            if (first == null || ArrayUtils.contains(propertyTypes, first.getClass())) {
                isProp = true;
            }
        }
    } else if (obj != null && Map.class.isAssignableFrom(type)) {
        //Try to determine value types of key and value
        if (!((Map) obj).isEmpty()) {
            Object firstKey = findFirstNonNull(((Map) obj).keySet().iterator());
            Object firstVal = findFirstNonNull(((Map) obj).entrySet().iterator());
            if ((firstKey == null || ArrayUtils.contains(propertyTypes, firstKey.getClass()))
                    && (firstVal == null || ArrayUtils.contains(propertyTypes,
                            ((HashMap.Entry) firstVal).getValue().getClass()))) {
                isProp = true;
            }
        }
    }
    return isProp;
}

From source file:edu.usu.sdl.openstorefront.validation.ValidationUtil.java

private static List<RuleResult> validateFields(final ValidationModel validateModel, Class dataClass,
        String parentFieldName, String parentType) {
    List<RuleResult> ruleResults = new ArrayList<>();

    if (validateModel.getDataObject() == null && validateModel.isAcceptNull() == false) {
        RuleResult validationResult = new RuleResult();
        validationResult.setMessage("The whole data object is null.");
        validationResult.setValidationRule("Don't allow null object");
        validationResult.setEntityClassName(parentType);
        validationResult.setFieldName(parentFieldName);
        ruleResults.add(validationResult);
    } else {/*from   w ww  .j  a va 2 s.  com*/
        if (validateModel.getDataObject() != null) {
            if (dataClass.getSuperclass() != null) {
                ruleResults.addAll(validateFields(validateModel, dataClass.getSuperclass(), null, null));
            }

            for (Field field : dataClass.getDeclaredFields()) {
                Class fieldClass = field.getType();
                boolean process = true;
                if (validateModel.isConsumeFieldsOnly()) {
                    ConsumeField consumeField = (ConsumeField) field.getAnnotation(ConsumeField.class);
                    if (consumeField == null) {
                        process = false;
                    }
                }

                if (process) {
                    if (ReflectionUtil.isComplexClass(fieldClass)) {
                        //composition class
                        if (Logger.class.getName().equals(fieldClass.getName()) == false
                                && fieldClass.isEnum() == false) {
                            try {
                                Method method = validateModel.getDataObject().getClass().getMethod(
                                        "get" + StringUtils.capitalize(field.getName()), (Class<?>[]) null);
                                Object returnObj = method.invoke(validateModel.getDataObject(),
                                        (Object[]) null);
                                boolean check = true;
                                if (returnObj == null) {
                                    NotNull notNull = (NotNull) fieldClass.getAnnotation(NotNull.class);
                                    if (notNull == null) {
                                        check = false;
                                    }
                                }
                                if (check) {
                                    ruleResults.addAll(
                                            validateFields(ValidationModel.copy(validateModel, returnObj),
                                                    fieldClass, field.getName(),
                                                    validateModel.getDataObject().getClass().getSimpleName()));
                                }
                            } catch (NoSuchMethodException | SecurityException | IllegalAccessException
                                    | IllegalArgumentException | InvocationTargetException ex) {
                                throw new OpenStorefrontRuntimeException(ex);
                            }
                        }
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(List.class.getSimpleName())
                            || fieldClass.getSimpleName().equalsIgnoreCase(Map.class.getSimpleName())
                            || fieldClass.getSimpleName().equalsIgnoreCase(Collection.class.getSimpleName())
                            || fieldClass.getSimpleName().equalsIgnoreCase(Set.class.getSimpleName())) {
                        //multi
                        if (fieldClass.getSimpleName().equalsIgnoreCase(Map.class.getSimpleName())) {
                            try {
                                Method method = validateModel.getDataObject().getClass().getMethod(
                                        "get" + StringUtils.capitalize(field.getName()), (Class<?>[]) null);
                                Object returnObj = method.invoke(validateModel.getDataObject(),
                                        (Object[]) null);
                                Map mapObj = (Map) returnObj;
                                for (Object entryObj : mapObj.entrySet()) {
                                    ruleResults.addAll(
                                            validateFields(ValidationModel.copy(validateModel, entryObj),
                                                    entryObj.getClass(), field.getName(),
                                                    validateModel.getDataObject().getClass().getSimpleName()));
                                }
                            } catch (NoSuchMethodException | SecurityException | IllegalAccessException
                                    | IllegalArgumentException | InvocationTargetException ex) {
                                throw new OpenStorefrontRuntimeException(ex);
                            }
                        } else {
                            try {
                                Method method = validateModel.getDataObject().getClass().getMethod(
                                        "get" + StringUtils.capitalize(field.getName()), (Class<?>[]) null);
                                Object returnObj = method.invoke(validateModel.getDataObject(),
                                        (Object[]) null);
                                if (returnObj != null) {
                                    for (Object itemObj : (Collection) returnObj) {
                                        if (itemObj != null) {
                                            ruleResults.addAll(validateFields(
                                                    ValidationModel.copy(validateModel, itemObj),
                                                    itemObj.getClass(), field.getName(),
                                                    validateModel.getDataObject().getClass().getSimpleName()));
                                        } else {
                                            log.log(Level.WARNING,
                                                    "There is a NULL item in a collection.  Check data passed in to validation.");
                                        }
                                    }
                                } else {
                                    NotNull notNull = field.getAnnotation(NotNull.class);
                                    if (notNull != null) {
                                        RuleResult ruleResult = new RuleResult();
                                        ruleResult.setMessage("Collection is required");
                                        ruleResult.setEntityClassName(
                                                validateModel.getDataObject().getClass().getSimpleName());
                                        ruleResult.setFieldName(field.getName());
                                        ruleResult.setValidationRule("Requires value");
                                        ruleResults.add(ruleResult);
                                    }
                                }
                            } catch (NoSuchMethodException | SecurityException | IllegalAccessException
                                    | IllegalArgumentException | InvocationTargetException ex) {
                                throw new OpenStorefrontRuntimeException(ex);
                            }
                        }

                    } else {
                        //simple case
                        for (BaseRule rule : rules) {
                            //Stanize if requested
                            if (validateModel.getSantize()) {
                                Sanitize santize = field.getAnnotation(Sanitize.class);
                                if (santize != null) {
                                    try {
                                        Sanitizer santizer = santize.value().newInstance();

                                        Method method = dataClass.getMethod(
                                                "get" + StringUtils.capitalize(field.getName()),
                                                (Class<?>[]) null);
                                        Object returnObj = method.invoke(validateModel.getDataObject(),
                                                (Object[]) null);

                                        Object newValue = santizer.santize(returnObj);

                                        method = dataClass.getMethod(
                                                "set" + StringUtils.capitalize(field.getName()), String.class);
                                        method.invoke(validateModel.getDataObject(), newValue);

                                    } catch (InstantiationException | IllegalAccessException
                                            | NoSuchMethodException | SecurityException
                                            | InvocationTargetException ex) {
                                        throw new OpenStorefrontRuntimeException(ex);
                                    }
                                }
                            }

                            RuleResult validationResult = rule.processField(field,
                                    validateModel.getDataObject());
                            if (validationResult != null) {
                                ruleResults.add(validationResult);
                            }
                        }
                    }
                }
            }
        }
    }

    return ruleResults;
}

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

/**
 * This method generates the default name of a configuration parameter that is defined by an
 * {@link org.uimafit.descriptor.ConfigurationParameter} annotation when no name is given
 *///from  w w w. ja  v  a2  s .  co m
public static String getConfigurationParameterName(Field field) {
    if (isConfigurationParameterField(field)) {
        org.uimafit.descriptor.ConfigurationParameter annotation = field
                .getAnnotation(org.uimafit.descriptor.ConfigurationParameter.class);
        String name = annotation.name();
        if (name.equals(org.uimafit.descriptor.ConfigurationParameter.USE_FIELD_NAME)) {
            name = field.getDeclaringClass().getName() + "." + field.getName();
        }
        return name;
    }
    return null;
}

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

/**
 * A factory method for creating a ConfigurationParameter from a given field definition
 *//* w ww.  j  a  v a 2  s. c om*/
public static ConfigurationParameter createPrimitiveParameter(Field field) {
    if (isConfigurationParameterField(field)) {
        org.uimafit.descriptor.ConfigurationParameter annotation = field
                .getAnnotation(org.uimafit.descriptor.ConfigurationParameter.class);
        String name = getConfigurationParameterName(field);
        boolean multiValued = isMultiValued(field);
        String parameterType = getConfigurationParameterType(field);
        return createPrimitiveParameter(name, parameterType, annotation.description(), multiValued,
                annotation.mandatory());
    } else {
        throw new IllegalArgumentException("field is not annotated with annotation of type "
                + org.uimafit.descriptor.ConfigurationParameter.class.getName());
    }
}

From source file:eagle.log.entity.meta.EntityDefinitionManager.java

@SuppressWarnings("unchecked")
public static EntityDefinition createEntityDefinition(Class<? extends TaggedLogAPIEntity> cls) {

    final EntityDefinition ed = new EntityDefinition();

    ed.setEntityClass(cls);//from  w  ww  .  j  av  a  2s  .c o  m
    // parse cls' annotations
    Table table = cls.getAnnotation(Table.class);
    if (table == null || table.value().isEmpty()) {
        throw new IllegalArgumentException(
                "Entity class must have a non-empty table name annotated with @Table");
    }
    String tableName = table.value();
    if (EagleConfigFactory.load().isTableNamePrefixedWithEnvironment()) {
        tableName = EagleConfigFactory.load().getEnv() + "_" + tableName;
    }
    ed.setTable(tableName);

    ColumnFamily family = cls.getAnnotation(ColumnFamily.class);
    if (family == null || family.value().isEmpty()) {
        throw new IllegalArgumentException(
                "Entity class must have a non-empty column family name annotated with @ColumnFamily");
    }
    ed.setColumnFamily(family.value());

    Prefix prefix = cls.getAnnotation(Prefix.class);
    if (prefix == null || prefix.value().isEmpty()) {
        throw new IllegalArgumentException(
                "Entity class must have a non-empty prefix name annotated with @Prefix");
    }
    ed.setPrefix(prefix.value());

    TimeSeries ts = cls.getAnnotation(TimeSeries.class);
    if (ts == null) {
        throw new IllegalArgumentException(
                "Entity class must have a non-empty timeseries name annotated with @TimeSeries");
    }
    ed.setTimeSeries(ts.value());

    Service service = cls.getAnnotation(Service.class);
    if (service == null || service.value().isEmpty()) {
        ed.setService(cls.getSimpleName());
    } else {
        ed.setService(service.value());
    }

    Metric m = cls.getAnnotation(Metric.class);
    Map<String, Class<?>> dynamicFieldTypes = new HashMap<String, Class<?>>();
    if (m != null) {
        // metric has to be timeseries
        if (!ts.value()) {
            throw new IllegalArgumentException("Metric entity must be time series as well");
        }
        MetricDefinition md = new MetricDefinition();
        md.setInterval(m.interval());
        ed.setMetricDefinition(md);
    }

    java.lang.reflect.Field[] fields = cls.getDeclaredFields();
    for (java.lang.reflect.Field f : fields) {
        Column column = f.getAnnotation(Column.class);
        if (column == null || column.value().isEmpty()) {
            continue;
        }
        Class<?> fldCls = f.getType();
        // intrusive check field type for metric entity
        checkFieldTypeForMetric(ed.getMetricDefinition(), f.getName(), fldCls, dynamicFieldTypes);
        Qualifier q = new Qualifier();
        q.setDisplayName(f.getName());
        q.setQualifierName(column.value());
        EntitySerDeser<?> serDeser = _serDeserMap.get(fldCls);
        if (serDeser == null) {
            throw new IllegalArgumentException(fldCls.getName() + " in field " + f.getName() + " of entity "
                    + cls.getSimpleName() + " has no serializer associated ");
        } else {
            q.setSerDeser((EntitySerDeser<Object>) serDeser);
        }
        ed.getQualifierNameMap().put(q.getQualifierName(), q);
        ed.getDisplayNameMap().put(q.getDisplayName(), q);
        // TODO: should refine rules, consider fields like "hCol", getter method should be gethCol() according to org.apache.commons.beanutils.PropertyUtils
        final String propertyName = f.getName().substring(0, 1).toUpperCase() + f.getName().substring(1);
        String getterName = "get" + propertyName;
        try {
            Method method = cls.getMethod(getterName);
            ed.getQualifierGetterMap().put(f.getName(), method);
        } catch (Exception e) {
            // Check if the type is boolean
            getterName = "is" + propertyName;
            try {
                Method method = cls.getMethod(getterName);
                ed.getQualifierGetterMap().put(f.getName(), method);
            } catch (Exception e1) {
                throw new IllegalArgumentException(
                        "Field " + f.getName() + " hasn't defined valid getter method: " + getterName, e);
            }
        }
        if (LOG.isDebugEnabled())
            LOG.debug("Field registered " + q);
    }

    // TODO: Lazy create because not used at all
    // dynamically create bean class
    if (ed.getMetricDefinition() != null) {
        Class<?> metricCls = createDynamicClassForMetric(cls.getName() + "_SingleTimestamp", dynamicFieldTypes);
        ed.getMetricDefinition().setSingleTimestampEntityClass(metricCls);
    }

    final Partition partition = cls.getAnnotation(Partition.class);
    if (partition != null) {
        final String[] partitions = partition.value();
        ed.setPartitions(partitions);
        // Check if partition fields are all tag fields. Partition field can't be column field, must be tag field.
        for (String part : partitions) {
            if (!ed.isTag(part)) {
                throw new IllegalArgumentException("Partition field can't be column field, must be tag field. "
                        + "Partition name: " + part);
            }
        }
    }

    final Indexes indexes = cls.getAnnotation(Indexes.class);
    if (indexes != null) {
        final Index[] inds = indexes.value();
        final IndexDefinition[] indexDefinitions = new IndexDefinition[inds.length];
        for (int i = 0; i < inds.length; ++i) {
            final Index ind = inds[i];
            indexDefinitions[i] = new IndexDefinition(ed, ind);
        }
        ed.setIndexes(indexDefinitions);
    }

    final ServicePath path = cls.getAnnotation(ServicePath.class);
    if (path != null) {
        if (path.path() != null && (!path.path().isEmpty())) {
            ed.setServiceCreationPath(path.path());
        }
    }

    return ed;
}

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

private static List<FieldInfo> convertFields(List<FieldInfo> fields, Class baseEntity) {

    for (Field field : baseEntity.getDeclaredFields()) {
        FieldInfo fi;//from   w  ww . j av a 2 s.  c om
        Class type = field.getType();
        String name = field.getName();
        Column column = field.getAnnotation(Column.class);
        if (field.isAnnotationPresent(Embedded.class)) {
            if (field.isAnnotationPresent(AttributeOverride.class)) {
                fi = new FieldInfo(type, name, field.getAnnotation(AttributeOverride.class));
            } else {
                fi = new FieldInfo(type, name, field.getAnnotation(AttributeOverrides.class));
            }
        } else if (field.isAnnotationPresent(Enumerated.class)) {
            fi = new FieldInfo(type, name, true, column);
        } else if (column != null && !field.isAnnotationPresent(CollectionTable.class)) {
            if (type.isPrimitive()) {
                if (type.equals(Boolean.TYPE)) {
                    type = Boolean.class;
                } else if (type.equals(Long.TYPE)) {
                    type = Long.class;
                } else if (type.equals(Integer.TYPE)) {
                    type = Integer.class;
                } else if (type.equals(Short.TYPE)) {
                    type = Short.class;
                } else if (type.equals(Byte.TYPE)) {
                    type = Byte.class;
                } else if (type.equals(Double.TYPE)) {
                    type = Double.class;
                } else if (type.equals(Float.TYPE)) {
                    type = Float.class;
                } else if (type.equals(Character.TYPE)) {
                    type = Character.class;
                }
            }
            fi = new FieldInfo(type, name, false, column);
        } else if ((field.isAnnotationPresent(ManyToOne.class) && !field.isAnnotationPresent(JoinTable.class))
                || (field.isAnnotationPresent(OneToOne.class)
                        && StringUtils.isEmpty(field.getAnnotation(OneToOne.class).mappedBy()))) {
            String columnName = field.isAnnotationPresent(JoinColumn.class)
                    ? field.getAnnotation(JoinColumn.class).name()
                    : field.getName();
            fi = getIdFieldInfo(type, name, columnName);
        } else if (!field.isAnnotationPresent(Transient.class)
                && (Collection.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type))
                && (field.isAnnotationPresent(JoinColumn.class) || field.isAnnotationPresent(JoinTable.class)
                        || field.isAnnotationPresent(CollectionTable.class))) {
            fi = new FieldInfo(type, name);
        } else {
            continue;
        }
        if (field.isAnnotationPresent(Type.class)) {
            fi.addAnnotation(field.getAnnotation(Type.class));
        }
        fi.setField(field);
        fields.add(fi);
    }

    return fields;
}

From source file:info.archinnov.achilles.internal.metadata.parsing.PropertyParser.java

public static String getIndexName(Field field) {
    log.debug("Check @Index annotation on field {} of class {}", field.getName(),
            field.getDeclaringClass().getCanonicalName());
    String indexName = null;/*from  ww w. j  a  va2s .  c o  m*/
    Index index = field.getAnnotation(Index.class);
    if (index != null) {
        indexName = index.name();
    }
    return indexName;
}