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:org.javelin.sws.ext.bind.internal.metadata.PropertyCallback.java

/**
 * @param accessors//from  w  w  w. j  ava  2s .  co m
 * @return
 */
private <A extends Annotation> A findJaxbAnnotation(AnnotatedElement[] accessors, Class<A> ann) {
    A annotation = null;
    for (AnnotatedElement ae : accessors) {
        // TODO: throw an exception when JAXB annotation is on both getter and setter
        if (ae != null && (annotation = AnnotationUtils.getAnnotation(ae, ann)) != null)
            return annotation;
    }
    return null;
}

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

/**
 * Writes bean description recursively.//from w ww .  java2  s. co m
 *
 * @param jgen
 *         to write to
 * @param currentVocab
 *         in context
 * @param valueType
 *         class of value
 * @param allRootParameters
 *         of the method that receives the request body
 * @param rootParameter
 *         the request body
 * @param currentCallValue
 *         the value at the current recursion level
 * @param propertyPath
 *         of the current recursion level
 * @throws IntrospectionException
 * @throws IOException
 */
private void recurseSupportedProperties(JsonGenerator jgen, String currentVocab, Class<?> valueType,
        ActionDescriptor allRootParameters, ActionInputParameter rootParameter, Object currentCallValue,
        String propertyPath) throws IntrospectionException, IOException {

    Map<String, ActionInputParameter> properties = new HashMap<String, ActionInputParameter>();

    // collect supported properties from ctor

    Constructor[] constructors = valueType.getConstructors();
    // find default ctor
    Constructor constructor = PropertyUtils.findDefaultCtor(constructors);
    // find ctor with JsonCreator ann
    if (constructor == null) {
        constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class);
    }
    if (constructor == null) {
        // TODO this can be a generic collection, find a way to describe it
        LOG.warn("can't describe supported properties, no default constructor or JsonCreator found for type "
                + valueType.getName());
        return;
    }

    int parameterCount = constructor.getParameterTypes().length;
    if (parameterCount > 0) {
        Annotation[][] annotationsOnParameters = constructor.getParameterAnnotations();

        Class[] parameters = constructor.getParameterTypes();
        int paramIndex = 0;
        for (Annotation[] annotationsOnParameter : annotationsOnParameters) {
            for (Annotation annotation : annotationsOnParameter) {
                if (JsonProperty.class == annotation.annotationType()) {
                    JsonProperty jsonProperty = (JsonProperty) annotation;
                    // TODO use required attribute of JsonProperty
                    String paramName = jsonProperty.value();

                    Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue, paramName);

                    ActionInputParameter constructorParamInputParameter = new SpringActionInputParameter(
                            new MethodParameter(constructor, paramIndex), propertyValue);

                    // TODO collect ctor params, setter params and process
                    // TODO then handle single, collection and bean for both
                    properties.put(paramName, constructorParamInputParameter);
                    paramIndex++; // increase for each @JsonProperty
                }
            }
        }
        Assert.isTrue(parameters.length == paramIndex, "not all constructor arguments of @JsonCreator "
                + constructor.getName() + " are annotated with @JsonProperty");
    }

    // collect supported properties from setters

    // TODO support Option provider by other method args?
    final BeanInfo beanInfo = Introspector.getBeanInfo(valueType);
    final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    // TODO collection and map
    // TODO distinguish which properties should be printed as supported - now just setters
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        final Method writeMethod = propertyDescriptor.getWriteMethod();
        if (writeMethod == null) {
            continue;
        }
        // TODO: the property name must be a valid URI - need to check context for terms?
        String propertyName = getWritableExposedPropertyOrPropertyName(propertyDescriptor);

        Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue,
                propertyDescriptor.getName());

        MethodParameter methodParameter = new MethodParameter(propertyDescriptor.getWriteMethod(), 0);
        ActionInputParameter propertySetterInputParameter = new SpringActionInputParameter(methodParameter,
                propertyValue);

        properties.put(propertyName, propertySetterInputParameter);
    }

    // write all supported properties
    // TODO we are using the annotatedParameter.parameterName but should use the key of properties here:
    for (ActionInputParameter annotatedParameter : properties.values()) {
        String nextPropertyPathLevel = propertyPath.isEmpty() ? annotatedParameter.getParameterName()
                : propertyPath + '.' + annotatedParameter.getParameterName();
        if (DataType.isSingleValueType(annotatedParameter.getParameterType())) {

            final Object[] possiblePropertyValues = rootParameter.getPossibleValues(allRootParameters);

            if (rootParameter.isIncluded(nextPropertyPathLevel)
                    && !rootParameter.isExcluded(nextPropertyPathLevel)) {
                writeSupportedProperty(jgen, currentVocab, annotatedParameter,
                        annotatedParameter.getParameterName(), possiblePropertyValues);
            }
            // TODO collections?
            //                        } else if (DataType.isArrayOrCollection(parameterType)) {
            //                            Object[] callValues = rootParameter.getValues();
            //                            int items = callValues.length;
            //                            for (int i = 0; i < items; i++) {
            //                                Object value;
            //                                if (i < callValues.length) {
            //                                    value = callValues[i];
            //                                } else {
            //                                    value = null;
            //                                }
            //                                recurseSupportedProperties(jgen, currentVocab, rootParameter
            // .getParameterType(),
            //                                        allRootParameters, rootParameter, value);
            //                            }
        } else {
            jgen.writeStartObject();
            jgen.writeStringField("hydra:property", annotatedParameter.getParameterName());
            // TODO: is the property required -> for bean props we need the Access annotation to express that
            jgen.writeObjectFieldStart(getPropertyOrClassNameInVocab(currentVocab, "rangeIncludes",
                    LdContextFactory.HTTP_SCHEMA_ORG, "schema:"));
            Expose expose = AnnotationUtils.getAnnotation(annotatedParameter.getParameterType(), Expose.class);
            String subClass;
            if (expose != null) {
                subClass = expose.value();
            } else {
                subClass = annotatedParameter.getParameterType().getSimpleName();
            }
            jgen.writeStringField(getPropertyOrClassNameInVocab(currentVocab, "subClassOf",
                    "http://www.w3" + ".org/2000/01/rdf-schema#", "rdfs:"), subClass);

            jgen.writeArrayFieldStart("hydra:supportedProperty");

            Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue,
                    annotatedParameter.getParameterName());

            recurseSupportedProperties(jgen, currentVocab, annotatedParameter.getParameterType(),
                    allRootParameters, rootParameter, propertyValue, nextPropertyPathLevel);
            jgen.writeEndArray();

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

From source file:org.alfresco.rest.framework.core.ResourceInspector.java

/**
 * Returns true if the method has been marked as deleted.
 * @param method the method// w w w .  j a  v a  2  s . co  m
 * @return true - if is is marked as deleted.
 */
public static boolean isDeleted(Method method) {
    WebApiDeleted deleted = AnnotationUtils.getAnnotation(method, WebApiDeleted.class);
    return (deleted != null);
}

From source file:org.alfresco.rest.framework.core.ResourceInspector.java

/**
 * Returns true if the method has been marked as no auth required.
 * @param method the method//  w  w w. j a  v a  2 s.c o m
 * @return true - if is is marked as no auth required.
 */
public static boolean isNoAuth(Method method) {
    WebApiNoAuth noAuth = AnnotationUtils.getAnnotation(method, WebApiNoAuth.class);
    return (noAuth != null);
}

From source file:org.apache.rave.synchronization.SynchronizingAspect.java

private Synchronized getAnnotation(Class<?> targetClass, Method method) {
    Method specificMethod = getTargetMethod(targetClass, method);
    return AnnotationUtils.getAnnotation(specificMethod, Synchronized.class);
}

From source file:org.focusns.common.event.support.EventInterceptor.java

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    ///*from  w  w w . jav  a 2s  . c o m*/
    Map<String, Object> beansMap = beanFactory.getBeansWithAnnotation(EventSubscriber.class);
    for (Map.Entry<String, Object> entry : beansMap.entrySet()) {
        String beanName = entry.getKey();
        Object beanObject = entry.getValue();
        Class<?> beanClass = beanObject.getClass();
        //
        Method[] declearedMethods = beanClass.getDeclaredMethods();
        for (Method declearedMethod : declearedMethods) {
            //
            Event event = AnnotationUtils.getAnnotation(declearedMethod, Event.class);
            if (event == null) {
                log.warn(String.format("Event Subscribe method %s must be annotated with @Event(\"xxx\")",
                        declearedMethod));
            } else {
                String eventKey = generateEventKey(event);
                eventMapping.put(eventKey, event);
                eventMethodMapping.put(eventKey, declearedMethod);
                eventSubscriberMapping.put(eventKey, beanName);
            }
        }
    }
}

From source file:org.springframework.batch.core.jsr.configuration.support.SpringAutowiredAnnotationBeanPostProcessor.java

protected Annotation findAutowiredAnnotation(AccessibleObject ao) {
    for (Class<? extends Annotation> type : this.autowiredAnnotationTypes) {
        Annotation annotation = AnnotationUtils.getAnnotation(ao, type);
        if (annotation != null) {
            return annotation;
        }/*www  .j  a  v  a2  s. co  m*/
    }
    return null;
}

From source file:org.springframework.integration.config.annotation.AbstractMethodAnnotationPostProcessor.java

@Override
public Object postProcess(Object bean, String beanName, Method method, List<Annotation> annotations) {
    if (this.beanAnnotationAware() && AnnotatedElementUtils.isAnnotated(method, Bean.class.getName())) {
        try {//from w  w  w  .  jav a2  s  .  c om
            resolveTargetBeanFromMethodWithBeanAnnotation(method);
        } catch (NoSuchBeanDefinitionException e) {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Skipping endpoint creation; " + e.getMessage()
                        + "; perhaps due to some '@Conditional' annotation.");
            }
            return null;
        }
    }

    List<Advice> adviceChain = extractAdviceChain(beanName, annotations);

    MessageHandler handler = createHandler(bean, method, annotations);

    if (!CollectionUtils.isEmpty(adviceChain) && handler instanceof AbstractReplyProducingMessageHandler) {
        ((AbstractReplyProducingMessageHandler) handler).setAdviceChain(adviceChain);
    }

    if (handler instanceof Orderable) {
        Order orderAnnotation = AnnotationUtils.findAnnotation(method, Order.class);
        if (orderAnnotation != null) {
            ((Orderable) handler).setOrder(orderAnnotation.value());
        }
    }
    if (handler instanceof AbstractMessageProducingHandler || handler instanceof AbstractMessageRouter) {
        String sendTimeout = MessagingAnnotationUtils.resolveAttribute(annotations, "sendTimeout",
                String.class);
        if (sendTimeout != null) {
            Long value = Long.valueOf(this.beanFactory.resolveEmbeddedValue(sendTimeout));
            if (handler instanceof AbstractMessageProducingHandler) {
                ((AbstractMessageProducingHandler) handler).setSendTimeout(value);
            } else {
                ((AbstractMessageRouter) handler).setSendTimeout(value);
            }
        }
    }

    boolean handlerExists = false;
    if (this.beanAnnotationAware() && AnnotatedElementUtils.isAnnotated(method, Bean.class.getName())) {
        Object handlerBean = this.resolveTargetBeanFromMethodWithBeanAnnotation(method);
        handlerExists = handlerBean != null && handler == handlerBean;
    }

    if (!handlerExists) {
        String handlerBeanName = generateHandlerBeanName(beanName, method);
        this.beanFactory.registerSingleton(handlerBeanName, handler);
        handler = (MessageHandler) this.beanFactory.initializeBean(handler, handlerBeanName);
    }

    if (AnnotatedElementUtils.isAnnotated(method, IdempotentReceiver.class.getName())
            && !AnnotatedElementUtils.isAnnotated(method, Bean.class.getName())) {
        String[] interceptors = AnnotationUtils.getAnnotation(method, IdempotentReceiver.class).value();
        for (String interceptor : interceptors) {
            DefaultBeanFactoryPointcutAdvisor advisor = new DefaultBeanFactoryPointcutAdvisor();
            advisor.setAdviceBeanName(interceptor);
            NameMatchMethodPointcut pointcut = new NameMatchMethodPointcut();
            pointcut.setMappedName("handleMessage");
            advisor.setPointcut(pointcut);
            advisor.setBeanFactory(this.beanFactory);

            if (handler instanceof Advised) {
                ((Advised) handler).addAdvisor(advisor);
            } else {
                ProxyFactory proxyFactory = new ProxyFactory(handler);
                proxyFactory.addAdvisor(advisor);
                handler = (MessageHandler) proxyFactory.getProxy(this.beanFactory.getBeanClassLoader());
            }
        }
    }

    if (!CollectionUtils.isEmpty(adviceChain)) {
        for (Advice advice : adviceChain) {
            if (advice instanceof HandleMessageAdvice) {
                NameMatchMethodPointcutAdvisor handlerAdvice = new NameMatchMethodPointcutAdvisor(advice);
                handlerAdvice.addMethodName("handleMessage");
                if (handler instanceof Advised) {
                    ((Advised) handler).addAdvisor(handlerAdvice);
                } else {
                    ProxyFactory proxyFactory = new ProxyFactory(handler);
                    proxyFactory.addAdvisor(handlerAdvice);
                    handler = (MessageHandler) proxyFactory.getProxy(this.beanFactory.getBeanClassLoader());
                }
            }
        }
    }

    AbstractEndpoint endpoint = createEndpoint(handler, method, annotations);
    if (endpoint != null) {
        return endpoint;
    }
    return handler;
}

From source file:org.springframework.integration.config.annotation.AbstractMethodAnnotationPostProcessor.java

protected String resolveTargetBeanName(Method method) {
    String id = null;/*  w  w w .ja v  a2  s .c  o  m*/
    String[] names = AnnotationUtils.getAnnotation(method, Bean.class).name();
    if (!ObjectUtils.isEmpty(names)) {
        id = names[0];
    }
    if (!StringUtils.hasText(id)) {
        id = method.getName();
    }
    return id;
}