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

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

Introduction

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

Prototype

@Nullable
public static Object getValue(Annotation annotation) 

Source Link

Document

Retrieve the value of the value attribute of a single-element Annotation, given an annotation instance.

Usage

From source file:com.oembedler.moon.graphql.engine.StereotypeUtils.java

private static <T extends Annotation> String getAnnotationValue(AnnotatedElement accessibleObject,
        Class<T> annotationClass, String defaultValue) {
    Assert.noNullElements(new Object[] { accessibleObject, annotationClass, defaultValue },
            "input parameters must not be null");

    String result = defaultValue;
    T annotation = accessibleObject.getAnnotation(annotationClass);
    if (annotation != null && StringUtils.hasText((String) AnnotationUtils.getValue(annotation)))
        result = (String) AnnotationUtils.getValue(annotation);

    return result;
}

From source file:com.stehno.sjdbcx.reflection.extractor.AnnotatedCollaborationExtractor.java

@Override
@SuppressWarnings("unchecked")
public C extract(final Method method) {
    final Annotation annotation = AnnotationUtils.getAnnotation(method, annoType);
    if (annotation != null) {
        final String extractionKey = (String) AnnotationUtils.getValue(annotation);
        if (!StringUtils.isEmpty(extractionKey)) {
            return resolve(extractionKey);
        } else {/*from   w w  w  . jav  a2s.  c o  m*/
            return resolve((Class<C>) AnnotationUtils.getValue(annotation, TYPE_ATTRIBUTE));
        }

    } else {
        return defaultExtractor;
    }
}

From source file:com.oembedler.moon.graphql.engine.dfs.ResolvableTypeAccessor.java

private <T extends Annotation, V> V getAnnotationValue(Class<T> annotationClass, V fallback) {
    V result = fallback;/*from  www .  ja v a  2 s.  c  o  m*/
    T annotation = getAnnotation(annotationClass);
    if (annotation != null && StringUtils.hasText((String) AnnotationUtils.getValue(annotation)))
        result = (V) AnnotationUtils.getValue(annotation);
    return result;
}

From source file:org.synyx.hades.dao.query.QueryMethod.java

/**
 * Returns the query string declared in a {@link Query} annotation or
 * {@literal null} if neither the annotation found nor the attribute was
 * specified.//from   w ww.  ja v a2 s . c  o  m
 * 
 * @return
 */
String getAnnotatedQuery() {

    String query = (String) AnnotationUtils.getValue(getQueryAnnotation());
    return StringUtils.hasText(query) ? query : null;
}

From source file:ch.rasc.wampspring.method.PayloadArgumentResolver.java

protected void validate(Message<?> message, MethodParameter parameter, Object target) {
    if (this.validator == null) {
        return;/*from ww w.  jav  a  2  s  .c om*/
    }
    for (Annotation ann : parameter.getParameterAnnotations()) {
        Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class);
        if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) {
            Object hints = validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann);
            Object[] validationHints = hints instanceof Object[] ? (Object[]) hints : new Object[] { hints };
            BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(target,
                    getParameterName(parameter));
            if (!ObjectUtils.isEmpty(validationHints) && this.validator instanceof SmartValidator) {
                ((SmartValidator) this.validator).validate(target, bindingResult, validationHints);
            } else {
                this.validator.validate(target, bindingResult);
            }
            if (bindingResult.hasErrors()) {
                throw new MethodArgumentNotValidException(message, parameter, bindingResult);
            }
            break;
        }
    }
}

From source file:com.fengduo.bee.commons.component.FormModelMethodArgumentResolver.java

protected void validateComponent(WebDataBinder binder, MethodParameter parameter) throws BindException {

    boolean validateParameter = validateParameter(parameter);
    Annotation[] annotations = binder.getTarget().getClass().getAnnotations();
    for (Annotation annot : annotations) {
        if (annot.annotationType().getSimpleName().startsWith("Valid") && validateParameter) {
            Object hints = AnnotationUtils.getValue(annot);
            binder.validate(hints instanceof Object[] ? (Object[]) hints : new Object[] { hints });
        }/*from  w ww .  j  av  a 2s.  c  o  m*/
    }

    if (binder.getBindingResult().hasErrors()) {
        if (isBindExceptionRequired(binder, parameter)) {
            throw new BindException(binder.getBindingResult());
        }
    }
}

From source file:com.fengduo.bee.commons.component.FormModelMethodArgumentResolver.java

/**
 * Validate the model attribute if applicable.
 * <p>//from   w w  w.j  a  v a  2  s  .com
 * The default implementation checks for {@code @javax.validation.Valid}.
 * 
 * @param binder the DataBinder to be used
 * @param parameter the method parameter
 */
protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) {
    Annotation[] annotations = parameter.getParameterAnnotations();
    for (Annotation annot : annotations) {
        if (annot.annotationType().getSimpleName().startsWith("Valid")) {
            Object hints = AnnotationUtils.getValue(annot);
            binder.validate(hints instanceof Object[] ? (Object[]) hints : new Object[] { hints });
        }
    }
}

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

@Override
@SuppressWarnings({ "unchecked" })
public Object[] adaptAndRetrieveInboundArguments(Method method, String inboundName,
        ApplicationContext applicationContext,
        StreamListenerParameterAdapter... streamListenerParameterAdapters) {
    Object[] arguments = new Object[method.getParameterTypes().length];
    for (int parameterIndex = 0; parameterIndex < arguments.length; parameterIndex++) {
        MethodParameter methodParameter = MethodParameter.forExecutable(method, parameterIndex);
        Class<?> parameterType = methodParameter.getParameterType();
        Object targetReferenceValue = null;
        if (methodParameter.hasParameterAnnotation(Input.class)) {
            targetReferenceValue = AnnotationUtils
                    .getValue(methodParameter.getParameterAnnotation(Input.class));
            Input methodAnnotation = methodParameter.getParameterAnnotation(Input.class);
            inboundName = methodAnnotation.value();
        } else if (arguments.length == 1 && StringUtils.hasText(inboundName)) {
            targetReferenceValue = inboundName;
        }/*from  w  w w  . j ava2 s.c  o  m*/
        if (targetReferenceValue != null) {
            Assert.isInstanceOf(String.class, targetReferenceValue, "Annotation value must be a String");
            Object targetBean = applicationContext.getBean((String) targetReferenceValue);
            BindingProperties bindingProperties = this.bindingServiceProperties
                    .getBindingProperties(inboundName);
            enableNativeDecodingForKTableAlways(parameterType, bindingProperties);
            //Retrieve the StreamsConfig created for this method if available.
            //Otherwise, create the StreamsBuilderFactory and get the underlying config.
            if (!this.methodStreamsBuilderFactoryBeanMap.containsKey(method)) {
                buildStreamsBuilderAndRetrieveConfig(method, applicationContext, inboundName);
            }
            try {
                StreamsBuilderFactoryBean streamsBuilderFactoryBean = this.methodStreamsBuilderFactoryBeanMap
                        .get(method);
                StreamsBuilder streamsBuilder = streamsBuilderFactoryBean.getObject();
                KafkaStreamsConsumerProperties extendedConsumerProperties = this.kafkaStreamsExtendedBindingProperties
                        .getExtendedConsumerProperties(inboundName);
                //get state store spec
                KafkaStreamsStateStoreProperties spec = buildStateStoreSpec(method);
                Serde<?> keySerde = this.keyValueSerdeResolver.getInboundKeySerde(extendedConsumerProperties);
                Serde<?> valueSerde = this.keyValueSerdeResolver
                        .getInboundValueSerde(bindingProperties.getConsumer(), extendedConsumerProperties);

                final KafkaConsumerProperties.StartOffset startOffset = extendedConsumerProperties
                        .getStartOffset();
                Topology.AutoOffsetReset autoOffsetReset = null;
                if (startOffset != null) {
                    switch (startOffset) {
                    case earliest:
                        autoOffsetReset = Topology.AutoOffsetReset.EARLIEST;
                        break;
                    case latest:
                        autoOffsetReset = Topology.AutoOffsetReset.LATEST;
                        break;
                    default:
                        break;
                    }
                }
                if (extendedConsumerProperties.isResetOffsets()) {
                    LOG.warn("Detected resetOffsets configured on binding " + inboundName + ". "
                            + "Setting resetOffsets in Kafka Streams binder does not have any effect.");
                }

                if (parameterType.isAssignableFrom(KStream.class)) {
                    KStream<?, ?> stream = getkStream(inboundName, spec, bindingProperties, streamsBuilder,
                            keySerde, valueSerde, autoOffsetReset);
                    KStreamBoundElementFactory.KStreamWrapper kStreamWrapper = (KStreamBoundElementFactory.KStreamWrapper) targetBean;
                    //wrap the proxy created during the initial target type binding with real object (KStream)
                    kStreamWrapper.wrap((KStream<Object, Object>) stream);
                    this.kafkaStreamsBindingInformationCatalogue
                            .addStreamBuilderFactory(streamsBuilderFactoryBean);
                    for (StreamListenerParameterAdapter streamListenerParameterAdapter : streamListenerParameterAdapters) {
                        if (streamListenerParameterAdapter.supports(stream.getClass(), methodParameter)) {
                            arguments[parameterIndex] = streamListenerParameterAdapter.adapt(kStreamWrapper,
                                    methodParameter);
                            break;
                        }
                    }
                    if (arguments[parameterIndex] == null
                            && parameterType.isAssignableFrom(stream.getClass())) {
                        arguments[parameterIndex] = stream;
                    }
                    Assert.notNull(arguments[parameterIndex], "Cannot convert argument " + parameterIndex
                            + " of " + method + "from " + stream.getClass() + " to " + parameterType);
                } else if (parameterType.isAssignableFrom(KTable.class)) {
                    String materializedAs = extendedConsumerProperties.getMaterializedAs();
                    String bindingDestination = this.bindingServiceProperties
                            .getBindingDestination(inboundName);
                    KTable<?, ?> table = getKTable(streamsBuilder, keySerde, valueSerde, materializedAs,
                            bindingDestination, autoOffsetReset);
                    KTableBoundElementFactory.KTableWrapper kTableWrapper = (KTableBoundElementFactory.KTableWrapper) targetBean;
                    //wrap the proxy created during the initial target type binding with real object (KTable)
                    kTableWrapper.wrap((KTable<Object, Object>) table);
                    this.kafkaStreamsBindingInformationCatalogue
                            .addStreamBuilderFactory(streamsBuilderFactoryBean);
                    arguments[parameterIndex] = table;
                } else if (parameterType.isAssignableFrom(GlobalKTable.class)) {
                    String materializedAs = extendedConsumerProperties.getMaterializedAs();
                    String bindingDestination = this.bindingServiceProperties
                            .getBindingDestination(inboundName);
                    GlobalKTable<?, ?> table = getGlobalKTable(streamsBuilder, keySerde, valueSerde,
                            materializedAs, bindingDestination, autoOffsetReset);
                    GlobalKTableBoundElementFactory.GlobalKTableWrapper globalKTableWrapper = (GlobalKTableBoundElementFactory.GlobalKTableWrapper) targetBean;
                    //wrap the proxy created during the initial target type binding with real object (KTable)
                    globalKTableWrapper.wrap((GlobalKTable<Object, Object>) table);
                    this.kafkaStreamsBindingInformationCatalogue
                            .addStreamBuilderFactory(streamsBuilderFactoryBean);
                    arguments[parameterIndex] = table;
                }
            } catch (Exception ex) {
                throw new IllegalStateException(ex);
            }
        } else {
            throw new IllegalStateException(StreamListenerErrorMessages.INVALID_DECLARATIVE_METHOD_PARAMETERS);
        }
    }
    return arguments;
}

From source file:org.springframework.cloud.stream.reactive.StreamEmitterAnnotationBeanPostProcessor.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private void invokeSetupMethodOnToTargetChannel(Method method, Object bean, String outboundName) {
    Object[] arguments = new Object[method.getParameterCount()];
    Object targetBean = null;/*from   ww  w.  j  av a 2  s. c  o  m*/
    for (int parameterIndex = 0; parameterIndex < arguments.length; parameterIndex++) {
        MethodParameter methodParameter = new SynthesizingMethodParameter(method, parameterIndex);
        Class<?> parameterType = methodParameter.getParameterType();
        Object targetReferenceValue = null;
        if (methodParameter.hasParameterAnnotation(Output.class)) {
            targetReferenceValue = AnnotationUtils
                    .getValue(methodParameter.getParameterAnnotation(Output.class));
        } else if (arguments.length == 1 && StringUtils.hasText(outboundName)) {
            targetReferenceValue = outboundName;
        }
        if (targetReferenceValue != null) {
            targetBean = this.applicationContext.getBean((String) targetReferenceValue);
            for (StreamListenerParameterAdapter<?, Object> streamListenerParameterAdapter : this.streamListenerParameterAdapters) {
                if (streamListenerParameterAdapter.supports(targetBean.getClass(), methodParameter)) {
                    arguments[parameterIndex] = streamListenerParameterAdapter.adapt(targetBean,
                            methodParameter);
                    if (arguments[parameterIndex] instanceof FluxSender) {
                        closeableFluxResources.add((FluxSender) arguments[parameterIndex]);
                    }
                    break;
                }
            }
            Assert.notNull(arguments[parameterIndex], "Cannot convert argument " + parameterIndex + " of "
                    + method + "from " + targetBean.getClass() + " to " + parameterType);
        } else {
            throw new IllegalStateException(StreamEmitterErrorMessages.ATLEAST_ONE_OUTPUT);
        }
    }
    Object result;
    try {
        result = method.invoke(bean, arguments);
    } catch (Exception e) {
        throw new BeanInitializationException("Cannot setup StreamEmitter for " + method, e);
    }

    if (!Void.TYPE.equals(method.getReturnType())) {
        if (targetBean == null) {
            targetBean = this.applicationContext.getBean(outboundName);
        }
        boolean streamListenerResultAdapterFound = false;
        for (StreamListenerResultAdapter streamListenerResultAdapter : this.streamListenerResultAdapters) {
            if (streamListenerResultAdapter.supports(result.getClass(), targetBean.getClass())) {
                Closeable fluxDisposable = streamListenerResultAdapter.adapt(result, targetBean);
                closeableFluxResources.add(fluxDisposable);
                streamListenerResultAdapterFound = true;
                break;
            }
        }
        Assert.state(streamListenerResultAdapterFound,
                StreamEmitterErrorMessages.CANNOT_CONVERT_RETURN_TYPE_TO_ANY_AVAILABLE_RESULT_ADAPTERS);
    }
}

From source file:org.springframework.cloud.stream.reactive.StreamEmitterAnnotationBeanPostProcessor.java

private static void validateStreamEmitterMethod(Method method, int outputAnnotationCount,
        String methodAnnotatedOutboundName) {

    if (StringUtils.hasText(methodAnnotatedOutboundName)) {
        Assert.isTrue(outputAnnotationCount == 0, StreamEmitterErrorMessages.INVALID_OUTPUT_METHOD_PARAMETERS);
    } else {//www  .ja  v  a  2 s . c  o m
        Assert.isTrue(outputAnnotationCount > 0, StreamEmitterErrorMessages.NO_OUTPUT_SPECIFIED);
    }

    if (!method.getReturnType().equals(Void.TYPE)) {
        Assert.isTrue(StringUtils.hasText(methodAnnotatedOutboundName),
                StreamEmitterErrorMessages.RETURN_TYPE_NO_OUTBOUND_SPECIFIED);
        Assert.isTrue(method.getParameterCount() == 0, StreamEmitterErrorMessages.RETURN_TYPE_METHOD_ARGUMENTS);
    } else {
        if (!StringUtils.hasText(methodAnnotatedOutboundName)) {
            int methodArgumentsLength = method.getParameterTypes().length;
            for (int parameterIndex = 0; parameterIndex < methodArgumentsLength; parameterIndex++) {
                MethodParameter methodParameter = new MethodParameter(method, parameterIndex);
                if (methodParameter.hasParameterAnnotation(Output.class)) {
                    String outboundName = (String) AnnotationUtils
                            .getValue(methodParameter.getParameterAnnotation(Output.class));
                    Assert.isTrue(StringUtils.hasText(outboundName),
                            StreamEmitterErrorMessages.INVALID_OUTBOUND_NAME);
                } else {
                    throw new IllegalArgumentException(
                            StreamEmitterErrorMessages.OUTPUT_ANNOTATION_MISSING_ON_METHOD_PARAMETERS_VOID_RETURN_TYPE);
                }
            }
        }
    }
}