Example usage for java.lang.reflect AnnotatedElement getAnnotation

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

Introduction

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

Prototype

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

Source Link

Document

Returns this element's annotation for the specified type if such an annotation is present, else null.

Usage

From source file:org.apache.sling.models.impl.model.AbstractInjectableElement.java

private static Object getDefaultValue(AnnotatedElement element, Type type,
        InjectAnnotationProcessor2 annotationProcessor) {
    if (annotationProcessor != null && annotationProcessor.hasDefault()) {
        return annotationProcessor.getDefault();
    }//  ww  w  .  java2s  . c  om

    Default defaultAnnotation = element.getAnnotation(Default.class);
    if (defaultAnnotation == null) {
        return null;
    }

    Object value = null;

    if (type instanceof Class) {
        Class<?> injectedClass = (Class<?>) type;
        if (injectedClass.isArray()) {
            Class<?> componentType = injectedClass.getComponentType();
            if (componentType == String.class) {
                value = defaultAnnotation.values();
            } else if (componentType == Integer.TYPE) {
                value = defaultAnnotation.intValues();
            } else if (componentType == Integer.class) {
                value = ArrayUtils.toObject(defaultAnnotation.intValues());
            } else if (componentType == Long.TYPE) {
                value = defaultAnnotation.longValues();
            } else if (componentType == Long.class) {
                value = ArrayUtils.toObject(defaultAnnotation.longValues());
            } else if (componentType == Boolean.TYPE) {
                value = defaultAnnotation.booleanValues();
            } else if (componentType == Boolean.class) {
                value = ArrayUtils.toObject(defaultAnnotation.booleanValues());
            } else if (componentType == Short.TYPE) {
                value = defaultAnnotation.shortValues();
            } else if (componentType == Short.class) {
                value = ArrayUtils.toObject(defaultAnnotation.shortValues());
            } else if (componentType == Float.TYPE) {
                value = defaultAnnotation.floatValues();
            } else if (componentType == Float.class) {
                value = ArrayUtils.toObject(defaultAnnotation.floatValues());
            } else if (componentType == Double.TYPE) {
                value = defaultAnnotation.doubleValues();
            } else if (componentType == Double.class) {
                value = ArrayUtils.toObject(defaultAnnotation.doubleValues());
            } else {
                log.warn("Default values for {} are not supported", componentType);
            }
        } else {
            if (injectedClass == String.class) {
                value = defaultAnnotation.values().length == 0 ? "" : defaultAnnotation.values()[0];
            } else if (injectedClass == Integer.class) {
                value = defaultAnnotation.intValues().length == 0 ? 0 : defaultAnnotation.intValues()[0];
            } else if (injectedClass == Long.class) {
                value = defaultAnnotation.longValues().length == 0 ? 0l : defaultAnnotation.longValues()[0];
            } else if (injectedClass == Boolean.class) {
                value = defaultAnnotation.booleanValues().length == 0 ? false
                        : defaultAnnotation.booleanValues()[0];
            } else if (injectedClass == Short.class) {
                value = defaultAnnotation.shortValues().length == 0 ? ((short) 0)
                        : defaultAnnotation.shortValues()[0];
            } else if (injectedClass == Float.class) {
                value = defaultAnnotation.floatValues().length == 0 ? 0f : defaultAnnotation.floatValues()[0];
            } else if (injectedClass == Double.class) {
                value = defaultAnnotation.doubleValues().length == 0 ? 0d : defaultAnnotation.doubleValues()[0];
            } else {
                log.warn("Default values for {} are not supported", injectedClass);
            }
        }
    } else {
        log.warn("Cannot provide default for {}", type);
    }
    return value;
}

From source file:org.apache.sling.models.impl.ReflectionUtil.java

/**
 * Get an annotation from either the element itself or on any of the
 * element's annotations (meta-annotations).
 * // w w w  . j a v a  2  s .co  m
 * @param element the element
 * @param annotationClass the annotation class
 * @return the found annotation or null
 */
public static <T extends Annotation> T getAnnotation(AnnotatedElement element, Class<T> annotationClass) {
    T annotation = element.getAnnotation(annotationClass);
    if (annotation != null) {
        return annotation;
    } else {
        for (Annotation ann : element.getAnnotations()) {
            annotation = ann.annotationType().getAnnotation(annotationClass);
            if (annotation != null) {
                return annotation;
            }
        }
    }
    return null;
}

From source file:org.castor.cpa.jpa.processors.fieldprocessors.JPAJoinColumnProcessor.java

/**
 * {@inheritDoc}//from  w  ww.  j  a v a 2s.c o  m
 * 
 * @see org.castor.core.annotationprocessing.TargetAwareAnnotationProcessor#
 *      processAnnotation(BaseNature, AnnotatedElement)
 */
public <I extends BaseNature, A extends Annotation> boolean processAnnotation(final I info, final A annotation,
        final AnnotatedElement target) {
    if ((info instanceof JPAFieldNature) && (annotation instanceof JoinColumn)
            && ((target instanceof Field) || (target instanceof Method))) {
        _log.debug("processing field annotation " + annotation.toString());

        boolean targetValid = false;
        if (target.getAnnotation(OneToOne.class) != null) {
            targetValid = true;
        }
        if (target.getAnnotation(ManyToOne.class) != null) {
            targetValid = true;
        }
        if (target.getAnnotation(OneToMany.class) != null) {
            targetValid = true;
        }
        if (!targetValid) {
            _log.error("JoinTable annotation on " + ((Member) target).getName()
                    + " is not valid! Needs a relationship annotation! Ignoring @JoinTable!");
            return false;
        }

        JPAFieldNature jpaFieldNature = (JPAFieldNature) info;

        JoinColumn joinColumn = (JoinColumn) annotation;
        jpaFieldNature.setJoinColumnName(joinColumn.name());
        jpaFieldNature.setJoinColumnReferencedColumnName(joinColumn.referencedColumnName());
        jpaFieldNature.setJoinColumnUnique(joinColumn.unique());
        jpaFieldNature.setJoinColumnNullable(joinColumn.nullable());
        jpaFieldNature.setJoinColumnInsertable(joinColumn.insertable());
        jpaFieldNature.setJoinColumnUpdatable(joinColumn.updatable());
        jpaFieldNature.setJoinColumnColumnDefinition(joinColumn.columnDefinition());
        jpaFieldNature.setJoinColumnTable(joinColumn.table());

        return true;
    }
    return false;
}

From source file:org.castor.cpa.jpa.processors.fieldprocessors.JPAJoinTableProcessor.java

/**
 * {@inheritDoc}/*from w  w  w  .  j av  a2s  .  c  o  m*/
 * 
 * @see org.castor.core.annotationprocessing.TargetAwareAnnotationProcessor#
 *      processAnnotation(BaseNature, AnnotatedElement)
 */
public <I extends BaseNature, A extends Annotation> boolean processAnnotation(final I info, final A annotation,
        final AnnotatedElement target) throws AnnotationTargetException {

    if ((info instanceof JPAFieldNature) && (annotation instanceof JoinTable)
            && ((target instanceof Field) || (target instanceof Method))) {
        _log.debug("processing field annotation " + annotation.toString());

        boolean targetValid = false;
        if (target.getAnnotation(OneToMany.class) != null) {
            targetValid = true;
        }
        if (target.getAnnotation(ManyToMany.class) != null) {
            targetValid = true;
        }
        if (!targetValid) {
            _log.error("JoinTable annotation on " + ((Member) target).getName()
                    + " is not valid! Needs a ManyToMany or unidiretional OneToMany "
                    + "relationship annotation! Ignoring @JoinTable!");
            return false;
        }

        JPAFieldNature jpaFieldNature = (JPAFieldNature) info;

        JoinTable joinTable = (JoinTable) annotation;

        jpaFieldNature.setJoinTableName(joinTable.name());
        jpaFieldNature.setJoinTableCatalog(joinTable.catalog());
        jpaFieldNature.setJoinTableSchema(joinTable.schema());
        jpaFieldNature.setJoinTableJoinColumns(joinTable.joinColumns());
        jpaFieldNature.setJoinTableInverseJoinColumns(joinTable.inverseJoinColumns());

        if (joinTable.catalog().length() != 0) {
            _log.warn("Castor does not support catalog definition for tables. " + "Use global definition.");
        }
        if (joinTable.schema().length() != 0) {
            _log.warn("Castor does not support schema definition for tables. " + "Use global definition.");
        }
        if (joinTable.uniqueConstraints().length != 0) {
            _log.warn("Castor does not support unique constraint definition for tables.");
        }

    }

    return false;
}

From source file:org.castor.cpa.jpa.processors.fieldprocessors.JPAManyToManyProcessor.java

/**
 * Little helper to check if a {@link AnnotatedElement} ({@link Field} or
 * {@link Method}) has a {@link ManyToMany} annotation that is mapped by the
 * given field (Class and name)./*from w  ww.j a v  a  2s .  c  o m*/
 * 
 * @param property
 *            The property to check
 * @param targetClass
 *            The Class that should be targetEntity of the given property
 * @param targetProperty
 *            The name of the field (mapped by the given property)
 * @return true iff the given property has a {@link ManyToMany} annotation
 *         with targetEntity referreing to targetClass and is mapped by the
 *         given field name targetProperty.
 * @throws AnnotationTargetException
 *             if property does not define a targetEntity and is not generic
 *             or the generic definition is not sufficient
 */
private boolean checkMappedByToTarget(final AnnotatedElement property, final Class<?> targetClass,
        final String targetProperty) throws AnnotationTargetException {
    ManyToMany otherManyToMany = property.getAnnotation(ManyToMany.class);
    if (otherManyToMany != null) {
        // if property has manytomany relation, get its targetEntity

        Class<?> otherTargetEntity = otherManyToMany.targetEntity();
        if (void.class.equals(otherTargetEntity)) {
            otherTargetEntity = ReflectionsHelper.getTargetEntityFromGenerics(property);
            if (otherTargetEntity == null) {
                // Error => no generics used!
                String className = ((Member) property).getDeclaringClass().getName();
                String targetName = ((Member) property).getName();
                String message = "Target entity for ManyToMany relation on " + className + "#" + targetName
                        + " not specified - use generics or specify targetEntity!";
                throw new AnnotationTargetException(message);
            }
        }

        if (otherTargetEntity.equals(targetClass)) {
            // if our entity is the targetEntity
            if (targetProperty.equals(otherManyToMany.mappedBy())) {
                // if our field is the owning field
                return true;
            }
        }
    }
    return false;
}

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

private boolean processNonSearchableAnnotations(AnnotatedElement annotatedElement) {
    boolean found = false;
    if (annotatedElement.isAnnotationPresent(SearchConverter.class)) {
        found = true;//from  w w w. j a  va 2s  .  co  m
        bindConverter(annotatedElement.getAnnotation(SearchConverter.class));
    }
    if (annotatedElement.isAnnotationPresent(SearchConverters.class)) {
        found = true;
        SearchConverters searchConverters = annotatedElement.getAnnotation(SearchConverters.class);
        for (SearchConverter searchConverter : searchConverters.value()) {
            bindConverter(searchConverter);
        }
    }
    if (annotatedElement.isAnnotationPresent(SearchAnalyzer.class)) {
        found = true;
        bindAnalyzer(annotatedElement.getAnnotation(SearchAnalyzer.class));
    }
    if (annotatedElement.isAnnotationPresent(SearchAnalyzers.class)) {
        found = true;
        SearchAnalyzers searchAnalyzers = annotatedElement.getAnnotation(SearchAnalyzers.class);
        for (SearchAnalyzer searchAnalyzer : searchAnalyzers.value()) {
            bindAnalyzer(searchAnalyzer);
        }
    }
    if (annotatedElement.isAnnotationPresent(SearchAnalyzerFilter.class)) {
        found = true;
        bindAnalyzerFilter(annotatedElement.getAnnotation(SearchAnalyzerFilter.class));
    }
    if (annotatedElement.isAnnotationPresent(SearchAnalyzerFilters.class)) {
        found = true;
        SearchAnalyzerFilters searchAnalyzerFilters = annotatedElement
                .getAnnotation(SearchAnalyzerFilters.class);
        for (SearchAnalyzerFilter searchAnalyzerFilter : searchAnalyzerFilters.value()) {
            bindAnalyzerFilter(searchAnalyzerFilter);
        }
    }
    return found;
}

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

/**
 * Need to be almost exactly as <code>bindClassPropertyMapping</code>.
 *///from   w w  w .  j  a  v  a  2  s  .c  o  m
private void bindClassPropertyIdMapping(SearchableId searchableProp,
        ClassIdPropertyMapping classPropertyMapping, Class<?> clazz, Type type,
        AnnotatedElement annotatedElement) throws MappingException {

    bindConverter(classPropertyMapping, searchableProp.idConverter());

    // No need for type in property id, since it will not be a collection

    classPropertyMapping.setBoost(searchableProp.boost());
    classPropertyMapping.setManagedId(AnnotationsBindingUtils.convert(searchableProp.managedId()));
    classPropertyMapping.setManagedIdIndex(AnnotationsBindingUtils.convert(searchableProp.managedIdIndex()));
    classPropertyMapping.setOverrideByName(searchableProp.override());

    SearchableMetaData metaData = annotatedElement.getAnnotation(SearchableMetaData.class);
    SearchableMetaDatas metaDatas = annotatedElement.getAnnotation(SearchableMetaDatas.class);

    if (StringUtils.hasLength(searchableProp.converter())) {
        classPropertyMapping.setManagedIdConverterName(searchableProp.converter());
    } else {
        classPropertyMapping.setManagedIdConverter(getConverter(clazz, type));
    }

    // check if we need to create a metadata because of the SearchId
    // here we differ from the searchProperty mapping, since it is perfectly
    // fine not to create one if there are no meta-data definitions (an internal
    // one will be created during the process phase)
    if (StringUtils.hasLength(searchableProp.name())) {
        ClassPropertyMetaDataMapping mdMapping = new ClassPropertyMetaDataMapping();
        String name = searchableProp.name();
        if (!StringUtils.hasLength(name)) {
            name = classPropertyMapping.getName();
        }
        mdMapping.setName(valueLookup.lookupMetaDataName(name));
        mdMapping.setPath(new StaticPropertyPath(mdMapping.getName()));
        mdMapping.setBoost(classPropertyMapping.getBoost());

        mdMapping.setAccessor(classPropertyMapping.getAccessor());
        mdMapping.setPropertyName(classPropertyMapping.getPropertyName());

        bindConverter(mdMapping, searchableProp.converter(), clazz, type);
        bindSpellCheck(mdMapping, searchableProp.spellCheck());

        mdMapping.setStore(AnnotationsBindingUtils.convert(searchableProp.store()));
        mdMapping.setIndex(AnnotationsBindingUtils.convert(searchableProp.index()));
        mdMapping.setTermVector(AnnotationsBindingUtils.convert(searchableProp.termVector()));
        mdMapping.setOmitNorms(AnnotationsBindingUtils.convert(searchableProp.omitNorms()));
        mdMapping.setOmitTf(AnnotationsBindingUtils.convert(searchableProp.omitTf()));
        mdMapping.setReverse(AnnotationsBindingUtils.convert(searchableProp.reverse()));

        handleFormat(mdMapping, name, searchableProp.format());

        if (StringUtils.hasLength(searchableProp.analyzer())) {
            mdMapping.setAnalyzer(searchableProp.analyzer());
        } else {
            mdMapping.setAnalyzer(classMapping.getAnalyzer());
        }
        mdMapping.setExcludeFromAll(AnnotationsBindingUtils.convert(searchableProp.excludeFromAll()));

        classPropertyMapping.addMapping(mdMapping);
    }

    if (metaData != null) {
        bindMetaData(metaData, classPropertyMapping, clazz, type);
    }
    if (metaDatas != null) {
        for (SearchableMetaData searchableMetaData : metaDatas.value()) {
            bindMetaData(searchableMetaData, classPropertyMapping, clazz, type);
        }
    }
}

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

/**
 * Need to be almost exactly as <code>bindClassPropertyIdMapping</code>.
 *//*  w  ww  .j  av a  2  s . c  o m*/
private void bindClassPropertyMapping(SearchableProperty searchableProp,
        ClassPropertyMapping classPropertyMapping, AnnotatedElement annotatedElement, Class<?> clazz, Type type)
        throws MappingException {

    bindConverter(classPropertyMapping, searchableProp.propertyConverter());

    if (!searchableProp.type().equals(Object.class)) {
        classPropertyMapping.setClassName(searchableProp.type().getName());
    } else {
        // check if it is a colleciton. If it is, try to infer the
        // type using generics
        classPropertyMapping.setClassName(AnnotationsBindingUtils.getCollectionParameterClassName(clazz, type));
    }

    if (StringUtils.hasLength(searchableProp.converter())) {
        classPropertyMapping.setManagedIdConverterName(searchableProp.converter());
    } else {
        classPropertyMapping.setManagedIdConverter(getConverter(clazz, type));
    }

    classPropertyMapping.setBoost(searchableProp.boost());
    classPropertyMapping.setManagedId(AnnotationsBindingUtils.convert(searchableProp.managedId()));
    classPropertyMapping.setManagedIdIndex(AnnotationsBindingUtils.convert(searchableProp.managedIdIndex()));
    classPropertyMapping.setOverrideByName(searchableProp.override());

    SearchableMetaData metaData = annotatedElement.getAnnotation(SearchableMetaData.class);
    SearchableMetaDatas metaDatas = annotatedElement.getAnnotation(SearchableMetaDatas.class);

    boolean hasMetaDataAnnotations = metaData != null || metaDatas != null;

    // check if we need to create a metadata because of the SearchProperty
    if (StringUtils.hasLength(searchableProp.name()) || !hasMetaDataAnnotations) {
        ClassPropertyMetaDataMapping mdMapping = new ClassPropertyMetaDataMapping();
        String name = searchableProp.name();
        if (!StringUtils.hasLength(name)) {
            name = classPropertyMapping.getName();
        }
        mdMapping.setName(valueLookup.lookupMetaDataName(name));
        mdMapping.setPath(new StaticPropertyPath(mdMapping.getName()));
        mdMapping.setBoost(classPropertyMapping.getBoost());

        bindConverter(mdMapping, searchableProp.converter(), clazz, type);
        bindSpellCheck(mdMapping, searchableProp.spellCheck());

        mdMapping.setAccessor(classPropertyMapping.getAccessor());
        mdMapping.setPropertyName(classPropertyMapping.getPropertyName());

        mdMapping.setStore(AnnotationsBindingUtils.convert(searchableProp.store()));
        mdMapping.setIndex(AnnotationsBindingUtils.convert(searchableProp.index()));
        mdMapping.setTermVector(AnnotationsBindingUtils.convert(searchableProp.termVector()));
        mdMapping.setOmitNorms(AnnotationsBindingUtils.convert(searchableProp.omitNorms()));
        mdMapping.setOmitTf(AnnotationsBindingUtils.convert(searchableProp.omitTf()));
        mdMapping.setReverse(AnnotationsBindingUtils.convert(searchableProp.reverse()));

        handleFormat(mdMapping, name, searchableProp.format());

        mdMapping.setInternal(false);

        if (StringUtils.hasLength(searchableProp.analyzer())) {
            mdMapping.setAnalyzer(searchableProp.analyzer());
        } else {
            mdMapping.setAnalyzer(classMapping.getAnalyzer());
        }
        if (StringUtils.hasLength(searchableProp.nullValue())) {
            mdMapping.setNullValue(searchableProp.nullValue());
        }
        mdMapping.setExcludeFromAll(AnnotationsBindingUtils.convert(searchableProp.excludeFromAll()));

        classPropertyMapping.addMapping(mdMapping);
    }

    if (metaData != null) {
        bindMetaData(metaData, classPropertyMapping, clazz, type);
    }
    if (metaDatas != null) {
        for (SearchableMetaData searchableMetaData : metaDatas.value()) {
            bindMetaData(searchableMetaData, classPropertyMapping, clazz, type);
        }
    }
}

From source file:org.glassfish.common.util.admin.MapInjectionResolver.java

@Override
public <V> V getValue(Object component, AnnotatedElement target, Type genericType, Class<V> type)
        throws MultiException {
    // look for the name in the list of parameters passed.
    Param param = target.getAnnotation(Param.class);
    String paramName = CommandModel.getParamName(param, target);
    if (param.primary()) {
        // this is the primary parameter for the command
        List<String> value = parameters.get("DEFAULT");
        if ("uri".endsWith(paramName)) {
            try {
                FormatUriToFile();//from w  w  w .  j av a  2s  .  com
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            value = parameters.get("DEFAULT");
        }
        if (value != null && value.size() > 0) {
            /*
             * If the operands are uploaded files, replace the
             * client-provided values with the paths to the uploaded files.
             * XXX - assume the lists are in the same order.
             */
            final List<String> filePaths = getUploadedFileParamValues("DEFAULT", type,
                    optionNameToUploadedFileMap);
            if (filePaths != null) {
                value = filePaths;
                // replace the file name operands with the uploaded files
                parameters.set("DEFAULT", value);
            } else {
                for (String s : value) {
                    checkAgainstAcceptableValues(target, s);
                }

            }
            // let's also copy this value to the cmd with a real name
            parameters.set(paramName, value);
            V paramValue = (V) convertListToObject(target, type, value);
            return paramValue;
        }
    }
    if (param.multiple()) {
        List<String> value = parameters.get(paramName);
        if (value != null && value.size() > 0) {
            final List<String> filePaths = getUploadedFileParamValues(paramName, type,
                    optionNameToUploadedFileMap);
            if (filePaths != null) {
                value = filePaths;
                // replace the file name operands with the uploaded files
                parameters.set(paramName, value);
            } else {
                for (String s : value) {
                    checkAgainstAcceptableValues(target, s);
                }
            }
        }
        parameters.set(paramName, value);
        V paramValue = (V) convertListToObject(target, type, value);
        return paramValue;
    }
    String paramValueStr = getParamValueString(parameters, param, target, context);

    /*
     * If the parameter is an uploaded file, replace the client-provided
     * value with the path to the uploaded file.
     */
    final String fileParamValueStr = getUploadedFileParamValue(paramName, type, optionNameToUploadedFileMap);
    if (fileParamValueStr != null) {
        paramValueStr = fileParamValueStr;
        parameters.set(paramName, paramValueStr);
    }
    checkAgainstAcceptableValues(target, paramValueStr);

    return paramValueStr != null ? (V) convertStringToObject(target, type, paramValueStr)
            : (V) getParamField(component, target);
}

From source file:org.glassfish.common.util.admin.MapInjectionResolver.java

/**
 * Convert the String parameter to the specified type.
 * For example if type is Properties and the String
 * value is: name1=value1:name2=value2:...
 * then this api will convert the String to a Properties
 * class with the values {name1=name2, name2=value2, ...}
 *
 * @param target the target field/*from  w  ww.  j  ava2 s  . c o m*/
 * @param type the type of class to convert
 * @param paramValStr the String value to convert
 * @return Object
 */
// package-private, for testing
static Object convertStringToObject(AnnotatedElement target, Class type, String paramValStr) {
    Param param = target.getAnnotation(Param.class);
    Object paramValue = paramValStr;
    if (type.isAssignableFrom(String.class)) {
        paramValue = paramValStr;
    } else if (type.isAssignableFrom(Properties.class)) {
        paramValue = convertStringToProperties(paramValStr, param.separator());
    } else if (type.isAssignableFrom(List.class)) {
        paramValue = convertStringToList(paramValStr, param.separator());
    } else if (type.isAssignableFrom(Boolean.class) || type.isAssignableFrom(boolean.class)) {
        String paramName = CommandModel.getParamName(param, target);
        paramValue = convertStringToBoolean(paramName, paramValStr);
    } else if (type.isAssignableFrom(Integer.class) || type.isAssignableFrom(int.class)) {
        String paramName = CommandModel.getParamName(param, target);
        paramValue = convertStringToInteger(paramName, paramValStr);
    } else if (type.isAssignableFrom(String[].class)) {
        paramValue = convertStringToStringArray(paramValStr, param.separator());
    } else if (type.isAssignableFrom(File.class)) {
        return new File(paramValStr);
    }
    return paramValue;
}