Example usage for org.springframework.core.annotation AnnotationUtils getAnnotation

List of usage examples for org.springframework.core.annotation AnnotationUtils getAnnotation

Introduction

In this page you can find the example usage for org.springframework.core.annotation AnnotationUtils getAnnotation.

Prototype

@Nullable
public static <A extends Annotation> A getAnnotation(Method method, Class<A> annotationType) 

Source Link

Document

Get a single Annotation of annotationType from the supplied Method , where the annotation is either present or meta-present on the method.

Usage

From source file:de.escalon.hypermedia.spring.AffordanceBuilderFactory.java

private ActionDescriptor createActionDescriptor(Method invokedMethod, Map<String, Object> values,
        Object[] arguments) {//from  www .j av  a2  s. com
    RequestMethod httpMethod = getHttpMethod(invokedMethod);
    Type genericReturnType = invokedMethod.getGenericReturnType();

    ActionDescriptor actionDescriptor = new ActionDescriptor(invokedMethod.getName(), httpMethod.name());

    actionDescriptor.setCardinality(getCardinality(invokedMethod, httpMethod, genericReturnType));

    final Action actionAnnotation = AnnotationUtils.getAnnotation(invokedMethod, Action.class);
    if (actionAnnotation != null) {
        actionDescriptor.setSemanticActionType(actionAnnotation.value());
    }

    Map<String, ActionInputParameter> requestBodyMap = getActionInputParameters(RequestBody.class,
            invokedMethod, arguments);
    Assert.state(requestBodyMap.size() < 2, "found more than one request body on " + invokedMethod.getName());
    for (ActionInputParameter value : requestBodyMap.values()) {
        actionDescriptor.setRequestBody(value);
    }

    // the action descriptor needs to know the param type, value and name
    Map<String, ActionInputParameter> requestParamMap = getActionInputParameters(RequestParam.class,
            invokedMethod, arguments);
    for (Map.Entry<String, ActionInputParameter> entry : requestParamMap.entrySet()) {
        ActionInputParameter value = entry.getValue();
        if (value != null) {
            final String key = entry.getKey();
            actionDescriptor.addRequestParam(key, value);
            if (!value.isRequestBody()) {
                values.put(key, value.getCallValueFormatted());
            }
        }
    }

    Map<String, ActionInputParameter> pathVariableMap = getActionInputParameters(PathVariable.class,
            invokedMethod, arguments);
    for (Map.Entry<String, ActionInputParameter> entry : pathVariableMap.entrySet()) {
        ActionInputParameter actionInputParameter = entry.getValue();
        if (actionInputParameter != null) {
            final String key = entry.getKey();
            actionDescriptor.addPathVariable(key, actionInputParameter);
            if (!actionInputParameter.isRequestBody()) {
                values.put(key, actionInputParameter.getCallValueFormatted());
            }
        }
    }

    Map<String, ActionInputParameter> requestHeadersMap = getActionInputParameters(RequestHeader.class,
            invokedMethod, arguments);

    for (Map.Entry<String, ActionInputParameter> entry : pathVariableMap.entrySet()) {
        ActionInputParameter actionInputParameter = entry.getValue();
        if (actionInputParameter != null) {
            final String key = entry.getKey();
            actionDescriptor.addRequestHeader(key, actionInputParameter);
            if (!actionInputParameter.isRequestBody()) {
                values.put(key, actionInputParameter.getCallValueFormatted());
            }
        }
    }

    return actionDescriptor;
}

From source file:org.apache.james.container.spring.lifecycle.osgi.AbstractOSGIAnnotationBeanPostProcessor.java

private void injectServices(final Object bean, final String beanName) {
    ReflectionUtils.doWithMethods(bean.getClass(), new ReflectionUtils.MethodCallback() {

        public void doWith(Method method) {
            A s = AnnotationUtils.getAnnotation(method, getAnnotation());
            if (s != null && method.getParameterTypes().length == 1) {
                try {
                    if (logger.isDebugEnabled())
                        logger.debug("Processing annotation [" + s + "] for [" + bean.getClass().getName() + "."
                                + method.getName() + "()] on bean [" + beanName + "]");
                    method.invoke(bean, getServiceImporter(s, method, beanName).getObject());
                } catch (Exception e) {
                    throw new IllegalArgumentException("Error processing annotation " + s, e);
                }/*  w w  w  .  ja  v a 2s. co m*/
            }
        }
    });
}

From source file:org.javelin.sws.ext.bind.SweJaxbContext.java

/**
 * <p>Get a representation of a class and it's (JAXB2) metadata as a <i>pattern</i> of static and dynamic {@link XMLEvent XML events}.</p>
 * /* ww w .  jav  a 2 s  . co m*/
 * <p>A class which is to be known by the registry should be directly convertible to a series of XML events. What is not mandatory here is
 * the root element of the marshalled object.</p>
 * 
 * <p>The produced pattern is automatically cached in the registry. Also the metadata for {@link XmlRootElement} annotated classes is cached.</p>
 * 
 * @param cl
 * @return
 */
@SuppressWarnings("unchecked")
@Override
public <T> TypedPattern<T> determineAndCacheXmlPattern(Class<T> cl) {
    // DESIGNFLAW: some check are done using map.containsKey(), some - using TypedPatternRegistry
    if (this.patterns.containsKey(cl)) {
        return (TypedPattern<T>) this.patterns.get(cl);
    }

    TypedPattern<T> pattern = null;

    log.trace("Mapping {} class to TypedPattern", cl.getName());

    // defaults
    JaxbMetadata meta = this.package2meta.get(cl.getPackage().getName());

    // package customization - cached
    if (!this.package2meta.containsKey(cl.getPackage().getName())) {
        meta = JaxbMetadata.defaultForPackage(cl.getPackage());
        // determine package-level default accessor type
        XmlAccessorType xmlAccessorType = AnnotationUtils.getAnnotation(cl.getPackage(), XmlAccessorType.class);
        XmlSchema xmlSchema = AnnotationUtils.getAnnotation(cl.getPackage(), XmlSchema.class);

        if (xmlAccessorType != null)
            meta.setXmlAccessType(xmlAccessorType.value());
        if (xmlSchema != null) {
            meta.setNamespace(xmlSchema.namespace());
            meta.setElementForm(xmlSchema.elementFormDefault());
            meta.setAttributeForm(xmlSchema.attributeFormDefault());
        }

        this.package2meta.put(cl.getPackage().getName(), meta);
    }

    // class customization - not cached
    XmlAccessorType xmlAccessorType = AnnotationUtils.findAnnotation(cl, XmlAccessorType.class);
    XmlType xmlType = AnnotationUtils.getAnnotation(cl, XmlType.class);

    XmlAccessType xmlAccessType = xmlAccessorType == null ? meta.getXmlAccessType() : xmlAccessorType.value();
    String namespace = xmlType == null || "##default".equals(xmlType.namespace()) ? meta.getNamespace()
            : xmlType.namespace();
    QName typeName = new QName(namespace,
            xmlType == null || "##default".equals(xmlType.name()) ? cl.getSimpleName() : xmlType.name());

    // before stepping into the class we'll add TemporaryTypedPattern to the mapping to be able to analyze cross-dependent classes
    TemporaryTypedPattern<T> txp = TemporaryTypedPattern.newTemporaryTypedPattern(typeName, cl);
    this.patterns.put(cl, txp);

    PropertyCallback<T> pc = new PropertyCallback<T>(this, cl, typeName, xmlAccessType, meta.getElementForm(),
            meta.getAttributeForm());
    // this is where the magic happens
    pattern = pc.analyze();
    txp.setRealPattern(pattern);

    // cache known global elements
    XmlRootElement xmlRootElement = AnnotationUtils.findAnnotation(cl, XmlRootElement.class);
    if (xmlRootElement != null) {
        String rootElementNamespace = "##default".equals(xmlRootElement.namespace()) ? meta.getNamespace()
                : xmlRootElement.namespace();
        String rootElementName = "##default".equals(xmlRootElement.name()) ? cl.getSimpleName()
                : xmlRootElement.name();
        QName rootQName = new QName(rootElementNamespace, rootElementName);

        ElementPattern<?> elementPattern = ElementPattern.newElementPattern(rootQName, pattern);
        this.rootPatterns.put(cl, elementPattern);
        this.rootPatternsForQNames.put(rootQName, elementPattern);
    }

    this.patterns.put(pattern.getJavaType(), pattern);
    this.patternsForTypeQNames.put(pattern.getSchemaType(), pattern);

    // see also
    XmlSeeAlso xmlSeeAlso = AnnotationUtils.findAnnotation(cl, XmlSeeAlso.class);
    if (xmlSeeAlso != null) {
        for (Class<?> c : xmlSeeAlso.value()) {
            log.trace("Analyzing @XmlSeeAlso class {}", c.getName());
            this.determineAndCacheXmlPattern(c);
        }
    }

    return pattern;
}

From source file:com.expedia.seiso.web.assembler.ResourceAssembler.java

/**
 * @param apiVersion/*from   w ww  .ja v  a 2 s .  co m*/
 *            API version
 * @param repoKey
 * @return
 */
public Resource toRepoSearchList(@NonNull ApiVersion apiVersion, @NonNull String repoKey) {
    val itemClass = itemMetaLookup.getItemClass(repoKey);
    val repoInfo = repositories.getRepositoryInformationFor(itemClass);
    val queryMethods = repoInfo.getQueryMethods();

    val resource = new Resource();
    resource.addLink(repoSearchLinks(apiVersion).repoSearchListLink(Relations.SELF, itemClass));
    resource.addLink(itemLinks(apiVersion).repoLink(Relations.UP, itemClass));

    // Query method links
    for (val queryMethod : queryMethods) {
        val restResource = AnnotationUtils.getAnnotation(queryMethod, RestResource.class);
        if (restResource == null) {
            continue;
        }

        val path = restResource.path();
        if (path.isEmpty()) {
            continue;
        }

        val requestParams = new LinkedMultiValueMap<String, String>();
        val methodParams = queryMethod.getParameters();
        for (val methodParam : methodParams) {
            val paramAnn = methodParam.getAnnotation(Param.class);
            if (paramAnn != null) {
                val requestParamName = paramAnn.value();
                // FIXME Formatting the URI template variables belongs with the xxxLinks objects, not here. [WLW]
                requestParams.set(requestParamName, "{" + requestParamName + "}");
            }
        }

        val rel = "s:" + (restResource.rel().isEmpty() ? path : restResource.rel());
        val link = repoSearchLinks(apiVersion).toRepoSearchLinkTemplate(rel, itemClass, path, requestParams);
        resource.addLink(link);
    }

    return resource;
}

From source file:com.frank.search.solr.core.ResultHelper.java

private static Object getMappedId(Object o) {
    if (ClassUtils.hasProperty(o.getClass(), "id")) {
        try {//from ww  w . j  a va 2  s.c om
            return FieldUtils.readDeclaredField(o, "id", true);
        } catch (IllegalAccessException e) {
            throw new MappingException("Id property could not be accessed!", e);
        }
    }

    for (java.lang.reflect.Field field : o.getClass().getDeclaredFields()) {
        Annotation annotation = AnnotationUtils.getAnnotation(field, Id.class);
        if (annotation != null) {
            try {
                return FieldUtils.readField(field, o, true);
            } catch (IllegalArgumentException e) {
                throw new MappingException("Id property could not be accessed!", e);
            } catch (IllegalAccessException e) {
                throw new MappingException("Id property could not be accessed!", e);
            }
        }
    }
    throw new MappingException("Id property could not be found!");
}

From source file:de.escalon.hypermedia.spring.de.escalon.hypermedia.spring.jackson.LinkListSerializer.java

private void recurseSupportedProperties(JsonGenerator jgen, String currentVocab, Class<?> beanType,
        ActionDescriptor actionDescriptor, ActionInputParameter actionInputParameter, Object currentCallValue)
        throws IntrospectionException, IOException {
    // TODO support Option provider by other method args?
    final BeanInfo beanInfo = Introspector.getBeanInfo(beanType);
    final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    // TODO collection and map

    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        final Method writeMethod = propertyDescriptor.getWriteMethod();
        if (writeMethod == null) {
            continue;
        }/*  w  w  w .java 2 s  .c o  m*/
        final Class<?> propertyType = propertyDescriptor.getPropertyType();
        // TODO: the property name must be a valid URI - need to check context for terms?
        String propertyName = getWritableExposedPropertyOrPropertyName(propertyDescriptor);
        if (DataType.isScalar(propertyType)) {

            final Property property = new Property(beanType, propertyDescriptor.getReadMethod(),
                    propertyDescriptor.getWriteMethod(), propertyDescriptor.getName());

            Object propertyValue = getPropertyValue(currentCallValue, propertyDescriptor);

            ActionInputParameter propertySetterInputParameter = new ActionInputParameter(
                    new MethodParameter(propertyDescriptor.getWriteMethod(), 0), propertyValue);
            final Object[] possiblePropertyValues = actionInputParameter.getPossibleValues(property,
                    actionDescriptor);

            writeSupportedProperty(jgen, currentVocab, propertySetterInputParameter, propertyName, property,
                    possiblePropertyValues);
        } else {
            jgen.writeStartObject();
            jgen.writeStringField("hydra:property", propertyName);
            // TODO: is the property required -> for bean props we need the Access annotation to express that
            jgen.writeObjectFieldStart(getPropertyOrClassNameInVocab(currentVocab, "rangeIncludes",
                    JacksonHydraSerializer.HTTP_SCHEMA_ORG, "schema:"));
            Expose expose = AnnotationUtils.getAnnotation(propertyType, Expose.class);
            String subClass;
            if (expose != null) {
                subClass = expose.value();
            } else {
                subClass = propertyType.getSimpleName();
            }
            jgen.writeStringField(getPropertyOrClassNameInVocab(currentVocab, "subClassOf",
                    "http://www.w3.org/2000/01/rdf-schema#", "rdfs:"), subClass);

            jgen.writeArrayFieldStart("hydra:supportedProperty");

            Object propertyValue = getPropertyValue(currentCallValue, propertyDescriptor);

            recurseSupportedProperties(jgen, currentVocab, propertyType, actionDescriptor, actionInputParameter,
                    propertyValue);
            jgen.writeEndArray();

            jgen.writeEndObject();
            jgen.writeEndObject();
        }
    }
}

From source file:org.apache.james.container.spring.lifecycle.osgi.AbstractOSGIAnnotationBeanPostProcessor.java

private A hasAnnotatedProperty(PropertyDescriptor propertyDescriptor) {
    Method setter = propertyDescriptor.getWriteMethod();
    return setter != null ? AnnotationUtils.getAnnotation(setter, getAnnotation()) : null;
}

From source file:org.okj.commons.annotations.ServiceReferenceInjectionBeanPostProcessor.java

protected ServiceReference hasServiceProperty(PropertyDescriptor propertyDescriptor) {
    Method setter = propertyDescriptor.getWriteMethod();
    return setter != null ? AnnotationUtils.getAnnotation(setter, ServiceReference.class) : null;
}