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

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

Introduction

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

Prototype

@Nullable
public static <A extends Annotation> A findAnnotation(Class<?> clazz, @Nullable Class<A> annotationType) 

Source Link

Document

Find a single Annotation of annotationType on the supplied Class , traversing its interfaces, annotations, and superclasses if the annotation is not directly present on the given class itself.

Usage

From source file:org.springframework.cloud.stream.binder.kafka.streams.KafkaStreamsStreamListenerSetupMethodOrchestrator.java

private static String[] getOutboundBindingTargetNames(Method method) {
    SendTo sendTo = AnnotationUtils.findAnnotation(method, SendTo.class);
    if (sendTo != null) {
        Assert.isTrue(!ObjectUtils.isEmpty(sendTo.value()), StreamListenerErrorMessages.ATLEAST_ONE_OUTPUT);
        Assert.isTrue(sendTo.value().length >= 1, "At least one outbound destination need to be provided.");
        return sendTo.value();
    }/*from w  w w  .  ja  v a  2s .  c  o m*/
    return null;
}

From source file:org.springframework.cloud.stream.binder.kafka.streams.KafkaStreamsStreamListenerSetupMethodOrchestrator.java

@SuppressWarnings({ "unchecked" })
private static KafkaStreamsStateStoreProperties buildStateStoreSpec(Method method) {
    KafkaStreamsStateStore spec = AnnotationUtils.findAnnotation(method, KafkaStreamsStateStore.class);
    if (spec != null) {
        Assert.isTrue(!ObjectUtils.isEmpty(spec.name()), "name cannot be empty");
        Assert.isTrue(spec.name().length() >= 1, "name cannot be empty.");
        KafkaStreamsStateStoreProperties props = new KafkaStreamsStateStoreProperties();
        props.setName(spec.name());//w  ww .ja v  a  2  s  .  co m
        props.setType(spec.type());
        props.setLength(spec.lengthMs());
        props.setKeySerdeString(spec.keySerde());
        props.setRetention(spec.retentionMs());
        props.setValueSerdeString(spec.valueSerde());
        props.setCacheEnabled(spec.cache());
        props.setLoggingDisabled(!spec.logging());
        return props;
    }
    return null;
}

From source file:org.springframework.cloud.stream.binding.BindableProxyFactory.java

@Override
public synchronized Object invoke(MethodInvocation invocation) throws Throwable {
    Method method = invocation.getMethod();

    // try to use cached target
    Object boundTarget = targetCache.get(method);
    if (boundTarget != null) {
        return boundTarget;
    }/*ww  w .jav  a 2  s.c  o m*/

    Input input = AnnotationUtils.findAnnotation(method, Input.class);
    if (input != null) {
        String name = BindingBeanDefinitionRegistryUtils.getBindingTargetName(input, method);
        boundTarget = this.inputHolders.get(name).getBoundTarget();
        targetCache.put(method, boundTarget);
        return boundTarget;
    } else {
        Output output = AnnotationUtils.findAnnotation(method, Output.class);
        if (output != null) {
            String name = BindingBeanDefinitionRegistryUtils.getBindingTargetName(output, method);
            boundTarget = this.outputHolders.get(name).getBoundTarget();
            targetCache.put(method, boundTarget);
            return boundTarget;
        }
    }
    return null;
}

From source file:org.springframework.cloud.stream.binding.BindableProxyFactory.java

@Override
public void afterPropertiesSet() throws Exception {
    Assert.notEmpty(BindableProxyFactory.this.bindingTargetFactories,
            "'bindingTargetFactories' cannot be empty");
    ReflectionUtils.doWithMethods(this.type, new ReflectionUtils.MethodCallback() {
        @Override/*w ww . j ava2s.c om*/
        public void doWith(Method method) throws IllegalArgumentException {
            Input input = AnnotationUtils.findAnnotation(method, Input.class);
            if (input != null) {
                String name = BindingBeanDefinitionRegistryUtils.getBindingTargetName(input, method);
                Class<?> returnType = method.getReturnType();
                Object sharedBindingTarget = locateSharedBindingTarget(name, returnType);
                if (sharedBindingTarget != null) {
                    BindableProxyFactory.this.inputHolders.put(name,
                            new BoundTargetHolder(sharedBindingTarget, false));
                } else {
                    BindableProxyFactory.this.inputHolders.put(name,
                            new BoundTargetHolder(getBindingTargetFactory(returnType).createInput(name), true));
                }
            }
        }
    });
    ReflectionUtils.doWithMethods(this.type, new ReflectionUtils.MethodCallback() {
        @Override
        public void doWith(Method method) throws IllegalArgumentException {
            Output output = AnnotationUtils.findAnnotation(method, Output.class);
            if (output != null) {
                String name = BindingBeanDefinitionRegistryUtils.getBindingTargetName(output, method);
                Class<?> returnType = method.getReturnType();
                Object sharedBindingTarget = locateSharedBindingTarget(name, returnType);
                if (sharedBindingTarget != null) {
                    BindableProxyFactory.this.outputHolders.put(name,
                            new BoundTargetHolder(sharedBindingTarget, false));
                } else {
                    BindableProxyFactory.this.outputHolders.put(name, new BoundTargetHolder(
                            getBindingTargetFactory(returnType).createOutput(name), true));
                }
            }
        }
    });
}

From source file:org.springframework.data.document.web.bind.annotation.support.HandlerMethodInvoker.java

public final Object invokeHandlerMethod(Method handlerMethod, Object handler, NativeWebRequest webRequest,
        ExtendedModelMap implicitModel) throws Exception {

    Method handlerMethodToInvoke = BridgeMethodResolver.findBridgedMethod(handlerMethod);
    try {/*ww  w .  ja va2s  .  c o  m*/
        boolean debug = logger.isDebugEnabled();
        for (String attrName : this.methodResolver.getActualSessionAttributeNames()) {
            Object attrValue = this.sessionAttributeStore.retrieveAttribute(webRequest, attrName);
            if (attrValue != null) {
                implicitModel.addAttribute(attrName, attrValue);
            }
        }
        for (Method attributeMethod : this.methodResolver.getModelAttributeMethods()) {
            Method attributeMethodToInvoke = BridgeMethodResolver.findBridgedMethod(attributeMethod);
            Object[] args = resolveHandlerArguments(attributeMethodToInvoke, handler, webRequest,
                    implicitModel);
            if (debug) {
                logger.debug("Invoking model attribute method: " + attributeMethodToInvoke);
            }
            String attrName = AnnotationUtils.findAnnotation(attributeMethod, ModelAttribute.class).value();
            if (!"".equals(attrName) && implicitModel.containsAttribute(attrName)) {
                continue;
            }
            ReflectionUtils.makeAccessible(attributeMethodToInvoke);
            Object attrValue = attributeMethodToInvoke.invoke(handler, args);
            if ("".equals(attrName)) {
                Class resolvedType = GenericTypeResolver.resolveReturnType(attributeMethodToInvoke,
                        handler.getClass());
                attrName = Conventions.getVariableNameForReturnType(attributeMethodToInvoke, resolvedType,
                        attrValue);
            }
            if (!implicitModel.containsAttribute(attrName)) {
                implicitModel.addAttribute(attrName, attrValue);
            }
        }
        Object[] args = resolveHandlerArguments(handlerMethodToInvoke, handler, webRequest, implicitModel);
        if (debug) {
            logger.debug("Invoking request handler method: " + handlerMethodToInvoke);
        }
        ReflectionUtils.makeAccessible(handlerMethodToInvoke);
        return handlerMethodToInvoke.invoke(handler, args);
    } catch (IllegalStateException ex) {
        // Internal assertion failed (e.g. invalid signature):
        // throw exception with full handler method context...
        throw new HandlerMethodInvocationException(handlerMethodToInvoke, ex);
    } catch (InvocationTargetException ex) {
        // User-defined @ModelAttribute/@InitBinder/@RequestMapping method threw an exception...
        ReflectionUtils.rethrowException(ex.getTargetException());
        return null;
    }
}

From source file:org.springframework.data.document.web.bind.annotation.support.HandlerMethodInvoker.java

protected void initBinder(Object handler, String attrName, WebDataBinder binder, NativeWebRequest webRequest)
        throws Exception {

    if (this.bindingInitializer != null) {
        this.bindingInitializer.initBinder(binder, webRequest);
    }//from  w  ww  .j  a v a 2  s .com
    if (handler != null) {
        Set<Method> initBinderMethods = this.methodResolver.getInitBinderMethods();
        if (!initBinderMethods.isEmpty()) {
            boolean debug = logger.isDebugEnabled();
            for (Method initBinderMethod : initBinderMethods) {
                Method methodToInvoke = BridgeMethodResolver.findBridgedMethod(initBinderMethod);
                String[] targetNames = AnnotationUtils.findAnnotation(initBinderMethod, InitBinder.class)
                        .value();
                if (targetNames.length == 0 || Arrays.asList(targetNames).contains(attrName)) {
                    Object[] initBinderArgs = resolveInitBinderArguments(handler, methodToInvoke, binder,
                            webRequest);
                    if (debug) {
                        logger.debug("Invoking init-binder method: " + methodToInvoke);
                    }
                    ReflectionUtils.makeAccessible(methodToInvoke);
                    Object returnValue = methodToInvoke.invoke(handler, initBinderArgs);
                    if (returnValue != null) {
                        throw new IllegalStateException(
                                "InitBinder methods must not have a return value: " + methodToInvoke);
                    }
                }
            }
        }
    }
}

From source file:org.springframework.data.document.web.bind.annotation.support.HandlerMethodInvoker.java

protected final void addReturnValueAsModelAttribute(Method handlerMethod, Class handlerType, Object returnValue,
        ExtendedModelMap implicitModel) {

    ModelAttribute attr = AnnotationUtils.findAnnotation(handlerMethod, ModelAttribute.class);
    String attrName = (attr != null ? attr.value() : "");
    if ("".equals(attrName)) {
        Class resolvedType = GenericTypeResolver.resolveReturnType(handlerMethod, handlerType);
        attrName = Conventions.getVariableNameForReturnType(handlerMethod, resolvedType, returnValue);
    }/* www .jav a 2 s.co m*/
    implicitModel.addAttribute(attrName, returnValue);
}

From source file:org.springframework.data.gemfire.config.annotation.support.AbstractAnnotationConfigSupport.java

/**
 * Resolves the {@link Annotation} with the given {@link Class type} from the {@link AnnotatedElement}.
 *
 * @param <A> {@link Class Subclass type} of the resolved {@link Annotation}.
 * @param annotatedElement {@link AnnotatedElement} from which to resolve the {@link Annotation}.
 * @param annotationType {@link Class type} of the {@link Annotation} to resolve from the {@link AnnotatedElement}.
 * @return the resolved {@link Annotation}.
 * @see java.lang.annotation.Annotation//w  w  w .  ja  v a  2s  .  c o  m
 * @see java.lang.reflect.AnnotatedElement
 * @see java.lang.Class
 */
protected <A extends Annotation> A resolveAnnotation(AnnotatedElement annotatedElement,
        Class<A> annotationType) {

    return (annotatedElement instanceof Class
            ? AnnotatedElementUtils.findMergedAnnotation(annotatedElement, annotationType)
            : AnnotationUtils.findAnnotation(annotatedElement, annotationType));
}

From source file:org.springframework.faces.mvc.annotation.support.AnnotatedMethodInvoker.java

/**
 * Initialize the specified data binder by executing all {@link InitBinder} methods.
 * @param handler The underlying handler
 * @param attrName The attribute name being initialized
 * @param binder The data binder to initialize
 * @param request The active web request.
 * @throws Exception on error/*  ww w . j a v a 2  s.  c om*/
 */
protected final void initBinder(Object handler, String attrName, WebDataBinder binder, NativeWebRequest request)
        throws Exception {
    if (this.bindingInitializer != null) {
        this.bindingInitializer.initBinder(binder, request);
    }
    if (handler != null) {
        Set<Method> initBinderMethods = this.methodResolver.getInitBinderMethods();
        if (!initBinderMethods.isEmpty()) {
            boolean debug = logger.isDebugEnabled();
            for (Method initBinderMethod : initBinderMethods) {
                Method methodToInvoke = BridgeMethodResolver.findBridgedMethod(initBinderMethod);
                String[] targetNames = AnnotationUtils.findAnnotation(methodToInvoke, InitBinder.class).value();
                if (targetNames.length == 0 || Arrays.asList(targetNames).contains(attrName)) {
                    Object[] initBinderArgs = resolveInitBinderArguments(handler, methodToInvoke, binder,
                            request);
                    if (debug) {
                        logger.debug("Invoking init-binder method: " + methodToInvoke);
                    }
                    Object returnValue = doInvokeMethod(methodToInvoke, handler, initBinderArgs);
                    if (returnValue != null) {
                        throw new IllegalStateException(
                                "InitBinder methods must not have a return value: " + methodToInvoke);
                    }
                }
            }
        }
    }
}

From source file:org.springframework.flex.config.RemotingAnnotationPostProcessor.java

/**
 * Helper that searches the BeanFactory for beans annotated with @RemotingDestination, being careful not to force
 * eager creation of the beans if it can be avoided.
 * //from   w  ww . ja va 2 s . c o m
 * @param beanFactory the BeanFactory to search
 * @return a set of collected RemotingDestinationMetadata
 */
private Set<RemotingDestinationMetadata> findRemotingDestinations(ConfigurableListableBeanFactory beanFactory) {
    Set<RemotingDestinationMetadata> remotingDestinations = new HashSet<RemotingDestinationMetadata>();
    Set<String> beanNames = new HashSet<String>();
    beanNames.addAll(Arrays.asList(beanFactory.getBeanDefinitionNames()));
    if (beanFactory.getParentBeanFactory() instanceof ListableBeanFactory) {
        beanNames.addAll(Arrays
                .asList(((ListableBeanFactory) beanFactory.getParentBeanFactory()).getBeanDefinitionNames()));
    }
    for (String beanName : beanNames) {
        if (beanName.startsWith("scopedTarget.")) {
            continue;
        }
        RemotingDestination remotingDestination = null;
        BeanDefinition bd = beanFactory.getMergedBeanDefinition(beanName);
        if (bd.isAbstract() || bd.isLazyInit()) {
            continue;
        }
        if (bd instanceof AbstractBeanDefinition) {
            AbstractBeanDefinition abd = (AbstractBeanDefinition) bd;
            if (abd.hasBeanClass()) {
                Class<?> beanClass = abd.getBeanClass();
                remotingDestination = AnnotationUtils.findAnnotation(beanClass, RemotingDestination.class);
                if (remotingDestination != null) {
                    remotingDestinations
                            .add(new RemotingDestinationMetadata(remotingDestination, beanName, beanClass));
                    continue;
                }
            }
        }
        Class<?> handlerType = beanFactory.getType(beanName);
        if (handlerType != null) {
            remotingDestination = AnnotationUtils.findAnnotation(handlerType, RemotingDestination.class);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Could not get type of bean '" + beanName + "' from bean factory.");
            }
        }
        if (remotingDestination != null) {
            remotingDestinations
                    .add(new RemotingDestinationMetadata(remotingDestination, beanName, handlerType));
        }
    }
    return remotingDestinations;
}