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:org.uimafit.component.initialize.ConfigurationParameterInitializer.java

/**
 * Initialize a component from an {@link UimaContext} This code can be a little confusing
 * because the configuration parameter annotations are used in two contexts: in describing the
 * component and to initialize member variables from a {@link UimaContext}. Here we are
 * performing the latter task. It is important to remember that the {@link UimaContext} passed
 * in to this method may or may not have been derived using reflection of the annotations (i.e.
 * using {@link ConfigurationParameterFactory} via e.g. a call to a AnalysisEngineFactory.create
 * method). It is just as possible for the description of the component to come directly from an
 * XML descriptor file. So, for example, just because a configuration parameter specifies a
 * default value, this does not mean that the passed in context will have a value for that
 * configuration parameter. It should be possible for a descriptor file to specify its own value
 * or to not provide one at all. If the context does not have a configuration parameter, then
 * the default value provided by the developer as specified by the defaultValue element of the
 * {@link ConfigurationParameter} will be used. See comments in the code for additional details.
 *
 * @param component the component to initialize.
 * @param context a UIMA context with configuration parameters.
 *//*from w  w w .ja  va  2s  .c  o m*/
public static void initialize(final Object component, final UimaContext context)
        throws ResourceInitializationException {
    MutablePropertyValues values = new MutablePropertyValues();
    List<String> mandatoryValues = new ArrayList<String>();

    for (Field field : ReflectionUtil.getFields(component)) { // component.getClass().getDeclaredFields())
        if (ConfigurationParameterFactory.isConfigurationParameterField(field)) {
            org.uimafit.descriptor.ConfigurationParameter annotation = field
                    .getAnnotation(org.uimafit.descriptor.ConfigurationParameter.class);

            Object parameterValue;
            String parameterName = ConfigurationParameterFactory.getConfigurationParameterName(field);

            // Obtain either from the context - or - if the context does not provide the
            // parameter, check if there is a default value. Note there are three possibilities:
            // 1) Parameter present and set
            // 2) Parameter present and set to null (null value)
            // 3) Parameter not present (also provided as null value by UIMA)
            // Unfortunately we cannot make a difference between case 2 and 3 since UIMA does 
            // not allow us to actually get a list of the parameters set in the context. We can
            // only get a list of the declared parameters. Thus we have to rely on the null
            // value.
            parameterValue = context.getConfigParameterValue(parameterName);
            if (parameterValue == null) {
                parameterValue = ConfigurationParameterFactory.getDefaultValue(field);
            }

            if (parameterValue != null) {
                values.addPropertyValue(field.getName(), parameterValue);
            }

            // TODO does this check really belong here? It seems that
            // this check is already performed by UIMA
            if (annotation.mandatory()) {
                mandatoryValues.add(field.getName());

                //               if (parameterValue == null) {
                //                  final String key = ResourceInitializationException.CONFIG_SETTING_ABSENT;
                //                  throw new ResourceInitializationException(key,
                //                        new Object[] { configurationParameterName });
                //               }
            }
            //            else {
            //               if (parameterValue == null) {
            //                  continue;
            //               }
            //            }
            //            final Object fieldValue = convertValue(field, parameterValue);
            //            try {
            //               setParameterValue(component, field, fieldValue);
            //            }
            //            catch (Exception e) {
            //               throw new ResourceInitializationException(e);
            //            }
        }
    }

    DataBinder binder = new DataBinder(component) {
        @Override
        protected void checkRequiredFields(MutablePropertyValues mpvs) {
            String[] requiredFields = getRequiredFields();
            if (!ObjectUtils.isEmpty(requiredFields)) {
                Map<String, PropertyValue> propertyValues = new HashMap<String, PropertyValue>();
                PropertyValue[] pvs = mpvs.getPropertyValues();
                for (PropertyValue pv : pvs) {
                    String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName());
                    propertyValues.put(canonicalName, pv);
                }
                for (String field : requiredFields) {
                    PropertyValue pv = propertyValues.get(field);
                    boolean empty = (pv == null || pv.getValue() == null);
                    // For our purposes, empty Strings or empty String arrays do not count as
                    // empty. Empty is only "null".
                    //                  if (!empty) {
                    //                     if (pv.getValue() instanceof String) {
                    //                        empty = !StringUtils.hasText((String) pv.getValue());
                    //                     }
                    //                     else if (pv.getValue() instanceof String[]) {
                    //                        String[] values = (String[]) pv.getValue();
                    //                        empty = (values.length == 0 || !StringUtils.hasText(values[0]));
                    //                     }
                    //                  }
                    if (empty) {
                        // Use bind error processor to create FieldError.
                        getBindingErrorProcessor().processMissingFieldError(field, getInternalBindingResult());
                        // Remove property from property values to bind:
                        // It has already caused a field error with a rejected value.
                        if (pv != null) {
                            mpvs.removePropertyValue(pv);
                            propertyValues.remove(field);
                        }
                    }
                }
            }
        }
    };
    binder.initDirectFieldAccess();
    PropertyEditorUtil.registerUimaFITEditors(binder);
    binder.setRequiredFields(mandatoryValues.toArray(new String[mandatoryValues.size()]));
    binder.bind(values);
    if (binder.getBindingResult().hasErrors()) {
        StringBuilder sb = new StringBuilder();
        sb.append("Errors initializing [" + component.getClass() + "]");
        for (ObjectError error : binder.getBindingResult().getAllErrors()) {
            if (sb.length() > 0) {
                sb.append("\n");
            }
            sb.append(error.getDefaultMessage());
        }
        throw new IllegalArgumentException(sb.toString());
    }
}

From source file:me.xiaopan.android.gohttp.requestobject.RequestParser.java

/**
 * ?True/*from ww w. j  av a  2  s.com*/
 * @param context 
 * @param field ?
 */
public static String parseTrueAnnotation(Context context, Field field) {
    True annotation = field.getAnnotation(True.class);
    if (annotation == null) {
        return null;
    }
    String annotationValue = annotation.value();
    if (annotationValue != null && !"".equals(annotationValue)) {
        return annotationValue;
    } else if (context != null && annotation.resId() > 0) {
        return context.getString(annotation.resId());
    } else {
        return null;
    }
}

From source file:me.xiaopan.android.gohttp.requestobject.RequestParser.java

/**
 * ?False/*ww  w . j a v  a 2  s. co m*/
 * @param context 
 * @param field ?
 */
public static String parseFalseAnnotation(Context context, Field field) {
    False annotation = field.getAnnotation(False.class);
    if (annotation == null) {
        return null;
    }
    String annotationValue = annotation.value();
    if (annotationValue != null && !"".equals(annotationValue)) {
        return annotationValue;
    } else if (context != null && annotation.resId() > 0) {
        return context.getString(annotation.resId());
    } else {
        return null;
    }
}

From source file:me.xiaopan.android.gohttp.requestobject.RequestParser.java

/**
 * ????/*from  w  w  w .j  a  va  2 s . c o  m*/
 * @param context 
 * @param field 
 */
public static String parseParamAnnotation(Context context, Field field) {
    Param annotation = field.getAnnotation(Param.class);
    if (annotation == null) {
        return null;
    }
    String annotationValue = annotation.value();
    if (annotationValue != null && !"".equals(annotationValue)) {
        return annotationValue;
    } else if (context != null && annotation.resId() > 0) {
        return context.getString(annotation.resId());
    } else {
        return null;
    }
}

From source file:me.xiaopan.android.gohttp.requestobject.RequestParser.java

/**
 * ??/*from   w ww.ja  v a2s . c om*/
 * @param context 
 * @param field 
 */
public static String parseValueAnnotation(Context context, Field field) {
    Value annotation = field.getAnnotation(Value.class);
    if (annotation == null) {
        return null;
    }
    String annotationValue = annotation.value();
    if (annotationValue != null && !"".equals(annotationValue)) {
        return annotationValue;
    } else if (context != null && annotation.resId() > 0) {
        return context.getString(annotation.resId());
    } else {
        return null;
    }
}

From source file:edu.usu.sdl.openstorefront.doc.JaxrsProcessor.java

private static void mapComplexTypes(List<APITypeModel> typeModels, Field fields[], boolean onlyConsumeField) {
    //Should strip duplicate types
    Set<String> typesInList = new HashSet<>();
    typeModels.forEach(type -> {// w w w  . jav a 2s  .  com
        typesInList.add(type.getName());
    });

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    for (Field field : fields) {
        boolean capture = true;
        if (onlyConsumeField) {
            ConsumeField consumeField = (ConsumeField) field.getAnnotation(ConsumeField.class);
            if (consumeField == null) {
                capture = false;
            }
        }

        if (capture) {

            Class fieldClass = field.getType();
            DataType dataType = (DataType) field.getAnnotation(DataType.class);
            if (dataType != null) {
                fieldClass = dataType.value();
            }

            if (ReflectionUtil.isComplexClass(fieldClass)) {

                APITypeModel typeModel = new APITypeModel();
                typeModel.setName(fieldClass.getSimpleName());

                APIDescription aPIDescription = (APIDescription) fieldClass.getAnnotation(APIDescription.class);
                if (aPIDescription != null) {
                    typeModel.setDescription(aPIDescription.value());
                }

                Set<String> fieldList = mapValueField(typeModel.getFields(), fieldClass.getDeclaredFields(),
                        onlyConsumeField);
                if (fieldClass.isEnum()) {
                    typeModel.setObject(Arrays.toString(fieldClass.getEnumConstants()));
                } else {
                    if (fieldClass.isInterface() == false) {
                        try {
                            typeModel.setObject(objectMapper.writeValueAsString(fieldClass.newInstance()));

                            String cleanUpJson = StringProcessor.stripeFieldJSON(typeModel.getObject(),
                                    fieldList);
                            typeModel.setObject(cleanUpJson);

                        } catch (InstantiationException | IllegalAccessException | JsonProcessingException ex) {
                            log.log(Level.WARNING,
                                    "Unable to process/map complex field: " + fieldClass.getSimpleName(), ex);
                            typeModel.setObject("{ Unable to view }");
                        }
                        mapComplexTypes(typeModels, fieldClass.getDeclaredFields(), onlyConsumeField);
                    }
                }
                typeModels.add(typeModel);
                typesInList.add(typeModel.getName());
            }

        }
    }
}

From source file:com.zlfun.framework.excel.ExcelUtils.java

private static <T> void parent(T t, Class<?> parentClass, Map<String, String> map) {
    Field[] fs = parentClass.getDeclaredFields();

    for (Field f : fs) {
        String data = get(t, f);//www  .  j  a va  2  s.co  m
        if (data == null) {
            continue;
        }
        WebParam itemField = f.getAnnotation(WebParam.class);
        if (itemField == null) {
            continue;
        }
        if ("".equals(itemField.value())) {
            String fname = f.getName();
            if (!map.containsKey(fname)) {
                map.put(fname, data);
            }
        } else {
            String fname = itemField.value();
            if (!map.containsKey(fname)) {
                map.put(fname, data);
            }
        }

    }
}

From source file:edu.usu.sdl.openstorefront.doc.JaxrsProcessor.java

private static void mapParameters(List<APIParamModel> parameterList, Field fields[]) {
    for (Field field : fields) {
        APIParamModel paramModel = new APIParamModel();
        paramModel.setFieldName(field.getName());

        QueryParam queryParam = (QueryParam) field.getAnnotation(QueryParam.class);
        FormParam formParam = (FormParam) field.getAnnotation(FormParam.class);
        MatrixParam matrixParam = (MatrixParam) field.getAnnotation(MatrixParam.class);
        HeaderParam headerParam = (HeaderParam) field.getAnnotation(HeaderParam.class);
        CookieParam cookieParam = (CookieParam) field.getAnnotation(CookieParam.class);
        PathParam pathParam = (PathParam) field.getAnnotation(PathParam.class);
        BeanParam beanParam = (BeanParam) field.getAnnotation(BeanParam.class);

        if (queryParam != null) {
            paramModel.setParameterType(QueryParam.class.getSimpleName());
            paramModel.setParameterName(queryParam.value());
        }/*from   w ww .  jav a2  s .  co  m*/
        if (formParam != null) {
            paramModel.setParameterType(FormParam.class.getSimpleName());
            paramModel.setParameterName(formParam.value());
        }
        if (matrixParam != null) {
            paramModel.setParameterType(MatrixParam.class.getSimpleName());
            paramModel.setParameterName(matrixParam.value());
        }
        if (pathParam != null) {
            paramModel.setParameterType(PathParam.class.getSimpleName());
            paramModel.setParameterName(pathParam.value());
        }
        if (headerParam != null) {
            paramModel.setParameterType(HeaderParam.class.getSimpleName());
            paramModel.setParameterName(headerParam.value());
        }
        if (cookieParam != null) {
            paramModel.setParameterType(CookieParam.class.getSimpleName());
            paramModel.setParameterName(cookieParam.value());
        }

        if (beanParam != null) {
            Class fieldClass = field.getDeclaringClass();
            mapParameters(parameterList, fieldClass.getDeclaredFields());
        }

        if (StringUtils.isNotBlank(paramModel.getParameterType())) {

            APIDescription aPIDescription = (APIDescription) field.getAnnotation(APIDescription.class);
            if (aPIDescription != null) {
                paramModel.setParameterDescription(aPIDescription.value());
            }

            ParameterRestrictions restrictions = (ParameterRestrictions) field
                    .getAnnotation(ParameterRestrictions.class);
            if (restrictions != null) {
                paramModel.setRestrictions(restrictions.value());
            }

            RequiredParam requiredParam = (RequiredParam) field.getAnnotation(RequiredParam.class);
            if (requiredParam != null) {
                paramModel.setRequired(true);
            }

            DefaultValue defaultValue = (DefaultValue) field.getAnnotation(DefaultValue.class);
            if (defaultValue != null) {
                paramModel.setDefaultValue(defaultValue.value());
            }

            parameterList.add(paramModel);
        }
    }
}

From source file:me.xiaopan.android.gohttp.requestobject.RequestParser.java

/**
 * ??ID??//from w w w .java 2s .c  om
 * @param context 
 * @param requestClass class
 */
public static List<String> parseCacheIgnoreParams(Context context, Class<? extends Request> requestClass) {
    List<String> finalHeaders = null;
    for (Field field : getFields(requestClass, true, true, true)) {
        field.setAccessible(true);
        if (field.getAnnotation(CacheIgnore.class) != null) { //?ID
            if (finalHeaders == null) {
                finalHeaders = new LinkedList<String>();
            }
            String requestParamName = parseParamAnnotation(context, field);
            if (requestParamName == null) {
                requestParamName = field.getName();
            }
            finalHeaders.add(requestParamName);
        }
    }
    return finalHeaders;
}

From source file:com.zlfun.framework.excel.ExcelUtils.java

public static <T> Map<String, String> genWebParamMap(T t) {
    Map<String, String> map = new HashMap<String, String>();
    try {/*from w  ww .  j  a v  a 2s .  c o m*/
        Field[] fs = t.getClass().getDeclaredFields();
        for (Field f : fs) {
            String data = get(t, f);
            if (data == null) {
                continue;
            }
            WebParam itemField = f.getAnnotation(WebParam.class);
            if (itemField == null) {
                continue;
            }
            if ("".equals(itemField.value())) {
                String fname = f.getName();
                if (!map.containsKey(fname)) {
                    map.put(fname, data);
                }
            } else {
                String fname = itemField.value();
                if (!map.containsKey(fname)) {
                    map.put(fname, data);
                }
            }
            // ?
            Class<?> parent = t.getClass().getSuperclass();
            while (parent != Object.class) {
                parent(t, parent, map);
                parent = parent.getSuperclass();
            }

        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return map;
}