org.springframework.core.annotation.AnnotationUtils Java Examples

The following examples show how to use org.springframework.core.annotation.AnnotationUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: AthenaServing   Author: xfyun   File: ApiRequestMappingHandlerMapping.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 创建匹配条件
 *
 * @param clazz
 * @return
 */
private static RequestCondition<ApiVersionCondition> createCondition(Class<?> clazz) {
    RequestMapping classRequestMapping = AnnotationUtils.findAnnotation(clazz, RequestMapping.class);
    if (classRequestMapping == null) {
        return null;
    }
    StringBuilder mappingUrlBuilder = new StringBuilder();
    if (classRequestMapping.value().length > 0) {
        mappingUrlBuilder.append(classRequestMapping.value()[0]);
    }
    String mappingUrl = mappingUrlBuilder.toString();
    if (!mappingUrl.contains("{version}") || !mappingUrl.contains("{v}")) {
        return null;
    }
    ApiVersion apiVersion = AnnotationUtils.findAnnotation(clazz, ApiVersion.class);
    return apiVersion == null ? new ApiVersionCondition(1) : new ApiVersionCondition(apiVersion.value());
}
 
Example #2
Source Project: schedule-spring-boot-starter   Author: fuzhengwei   File: DcsSchedulingConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean);
    if (this.nonAnnotatedClasses.contains(targetClass)) return bean;
    Method[] methods = ReflectionUtils.getAllDeclaredMethods(bean.getClass());
    if (methods == null) return bean;
    for (Method method : methods) {
        DcsScheduled dcsScheduled = AnnotationUtils.findAnnotation(method, DcsScheduled.class);
        if (null == dcsScheduled || 0 == method.getDeclaredAnnotations().length) continue;
        List<ExecOrder> execOrderList = Constants.execOrderMap.computeIfAbsent(beanName, k -> new ArrayList<>());
        ExecOrder execOrder = new ExecOrder();
        execOrder.setBean(bean);
        execOrder.setBeanName(beanName);
        execOrder.setMethodName(method.getName());
        execOrder.setDesc(dcsScheduled.desc());
        execOrder.setCron(dcsScheduled.cron());
        execOrder.setAutoStartup(dcsScheduled.autoStartup());
        execOrderList.add(execOrder);
        this.nonAnnotatedClasses.add(targetClass);
    }
    return bean;
}
 
Example #3
Source Project: spring4-understanding   Author: langtianya   File: AnnotationAttributesReadingVisitor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void doVisitEnd(Class<?> annotationClass) {
	super.doVisitEnd(annotationClass);
	List<AnnotationAttributes> attributes = this.attributesMap.get(this.annotationType);
	if (attributes == null) {
		this.attributesMap.add(this.annotationType, this.attributes);
	}
	else {
		attributes.add(0, this.attributes);
	}
	Set<String> metaAnnotationTypeNames = new LinkedHashSet<String>();
	Annotation[] metaAnnotations = AnnotationUtils.getAnnotations(annotationClass);
	if (!ObjectUtils.isEmpty(metaAnnotations)) {
		for (Annotation metaAnnotation : metaAnnotations) {
			if (!AnnotationUtils.isInJavaLangAnnotationPackage(metaAnnotation)) {
				recursivelyCollectMetaAnnotations(metaAnnotationTypeNames, metaAnnotation);
			}
		}
	}
	if (this.metaAnnotationMap != null) {
		this.metaAnnotationMap.put(annotationClass.getName(), metaAnnotationTypeNames);
	}
}
 
Example #4
Source Project: citrus-admin   Author: citrusframework   File: ConfigurationProvider.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Enriches configuration instance with system properties and/or environment variables as field value when applicable.
 *
 * @param configuration
 * @param <T>
 * @return
 */
public static <T> T load(final T configuration) {
    SystemConfigurable systemConfigurable = AnnotationUtils.findAnnotation(configuration.getClass(), SystemConfigurable.class);

    ReflectionUtils.doWithFields(configuration.getClass(), field -> {
        if (field.getAnnotation(SystemProperty.class) != null) {
            SystemProperty systemProperty = field.getAnnotation(SystemProperty.class);
            Method setter = ReflectionUtils.findMethod(configuration.getClass(), "set" + StringUtils.capitalize(field.getName()), field.getType());

            if (setter != null) {
                if (StringUtils.hasText(systemProperty.name())) {
                    ReflectionUtils.invokeMethod(setter, configuration, System.getProperty((systemConfigurable != null ? systemConfigurable.prefix() : "") + systemProperty.name(), Optional.ofNullable(System.getenv((systemConfigurable != null ? systemConfigurable.environmentPrefix() : "") + systemProperty.environment()))
                            .orElse(getDefaultValue(configuration.getClass(), field, systemProperty, configuration))));
                } else if (StringUtils.hasText(systemProperty.environment())) {
                    ReflectionUtils.invokeMethod(setter, configuration, Optional.ofNullable(System.getenv((systemConfigurable != null ? systemConfigurable.environmentPrefix() : "") + systemProperty.environment()))
                            .orElse(getDefaultValue(configuration.getClass(), field, systemProperty, configuration)));
                } else {
                    ReflectionUtils.invokeMethod(setter, configuration, getDefaultValue(configuration.getClass(), field, systemProperty, configuration));
                }
            }
        }
    });

    return configuration;
}
 
Example #5
Source Project: haven-platform   Author: codeabovelab   File: NodeMapping.java    License: Apache License 2.0 6 votes vote down vote up
private void saveType(String path, T object, KeyValueStorage storage) {
    Class<?> clazz = object.getClass();
    String name = PROP_TYPE;
    String value = clazz.getName();
    JsonTypeInfo typeInfo = AnnotationUtils.findAnnotation(clazz, JsonTypeInfo.class);
    if (typeInfo != null && !clazz.equals(typeInfo.defaultImpl())) {
        JsonTypeInfo.As include = typeInfo.include();
        if(include != JsonTypeInfo.As.PROPERTY &&
           include != JsonTypeInfo.As.EXTERNAL_PROPERTY /* it for capability with jackson oddities */) {
            throw new IllegalArgumentException("On " + clazz + " mapping support only " + JsonTypeInfo.As.PROPERTY + " but find: " + include);
        }
        name = getPropertyName(typeInfo);
        value = getJsonType(clazz, typeInfo);
    }
    storage.set(KvUtils.join(path, name), value);
}
 
Example #6
Source Project: eclair   Author: TinkoffCreditSystems   File: AnnotationExtractorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void synthesizeLogOut() {
    // given
    Map<String, Object> attributes = new HashMap<>();
    attributes.put("level", ERROR);
    attributes.put("ifEnabled", WARN);
    attributes.put("verbose", INFO);
    attributes.put("printer", "printer");
    attributes.put("logger", "logger");
    Log log = AnnotationUtils.synthesizeAnnotation(attributes, Log.class, null);
    // when
    Log.out logOut = annotationExtractor.synthesizeLogOut(log);
    // then
    assertThat(logOut.level(), is(ERROR));
    assertThat(logOut.ifEnabled(), is(WARN));
    assertThat(logOut.verbose(), is(INFO));
    assertThat(logOut.printer(), is("printer"));
    assertThat(logOut.logger(), is("logger"));
}
 
Example #7
Source Project: spring-analysis-note   Author: Vip-Augus   File: PayloadMethodArgumentResolver.java    License: MIT License 6 votes vote down vote up
/**
 * Validate the payload if applicable.
 * <p>The default implementation checks for {@code @javax.validation.Valid},
 * Spring's {@link Validated},
 * and custom annotations whose name starts with "Valid".
 * @param message the currently processed message
 * @param parameter the method parameter
 * @param target the target payload object
 * @throws MethodArgumentNotValidException in case of binding errors
 */
protected void validate(Message<?> message, MethodParameter parameter, Object target) {
	if (this.validator == null) {
		return;
	}
	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;
		}
	}
}
 
Example #8
Source Project: HotswapAgent   Author: HotswapProjects   File: ResetSpringStaticCaches.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void resetAnnotationUtilsCache() {
    ReflectionHelper.invokeNoException(null, "org.springframework.core.annotation.AnnotationUtils",
            ResetSpringStaticCaches.class.getClassLoader(), "clearCache", new Class<?>[] {});

    Map annotatedInterfaceCache = (Map) ReflectionHelper.getNoException(null, AnnotationUtils.class,
            "annotatedInterfaceCache");
    if (annotatedInterfaceCache != null) {
        annotatedInterfaceCache.clear();
        LOGGER.trace("Cache cleared: AnnotationUtils.annotatedInterfaceCache");
    } else {
        LOGGER.trace("Cache NOT cleared: AnnotationUtils.annotatedInterfaceCache not exists in target Spring verion (pre 3.1.x)");
    }

    Map findAnnotationCache = (Map) ReflectionHelper.getNoException(null, AnnotationUtils.class, "findAnnotationCache");
    if (findAnnotationCache != null) {
        findAnnotationCache.clear();
        LOGGER.trace("Cache cleared: AnnotationUtils.findAnnotationCache");
    } else {
        LOGGER.trace("Cache NOT cleared: AnnotationUtils.findAnnotationCache not exists in target Spring version (pre 4.1)");
    }

}
 
Example #9
Source Project: mongodb-aggregate-query-support   Author: krraghavan   File: AggregateQueryProvider.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"Duplicates"})
@Override
protected void initializeAnnotation(Method method) throws InvalidAggregationQueryException {
  this.aggregateAnnotation = method.getAnnotation(Aggregate.class);
  Class inputType = aggregateAnnotation.inputType();
  this.collectionName = deriveCollectionName(aggregateAnnotation,
                                             (idx) -> mongoParameterAccessor.getValues()[idx].toString(),
                                             () -> {
                                               Document documentAnnotation = AnnotationUtils.findAnnotation(inputType,
                                                                                                            Document.class);
                                               return documentAnnotation != null ? documentAnnotation.collection() : null;
                                             },
                                             (s) -> {
                                               Expression expression = detectExpression(s);
                                               if (expression != null) {
                                                 return expression.getValue(context, String.class);
                                               }
                                               return s;
                                             });
  this.placeholderRepFn = (q) -> replacePlaceholders((String) q);
  // set queryProcessorFactory here - the base class calls createQuery which needs the factory.
  this.queryProcessorFactory = new DefaultPipelineStageQueryProcessorFactory();
}
 
Example #10
Source Project: alfresco-remote-api   Author: Alfresco   File: ResourceInspector.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Inspects the resource to determine what api it belongs to.
 * It does this by looking for the WebApi package annotation.
 * 
 * @return Api
 */
public static Api inspectApi(Class<?> resource)
{
    Package myPackage = resource.getPackage();
    Annotation annot = myPackage.getAnnotation(WebApi.class);
  
    if (annot != null)
    {
        Map<String, Object> annotAttribs =  AnnotationUtils.getAnnotationAttributes(annot);
        String apiName = String.valueOf(annotAttribs.get("name"));
        String apiScope = String.valueOf(annotAttribs.get("scope"));
        String apiVersion = String.valueOf(annotAttribs.get("version"));
        return Api.valueOf(apiName, apiScope, apiVersion);
    }
    return null;
}
 
Example #11
Source Project: spring4-understanding   Author: langtianya   File: GroovyScriptFactoryTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
// Test for SPR-6268
public void testRefreshableFromTagProxyTargetClass() throws Exception {
	ApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd-proxy-target-class.xml",
			getClass());
	assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("refreshableMessenger"));

	Messenger messenger = (Messenger) ctx.getBean("refreshableMessenger");

	assertTrue(AopUtils.isAopProxy(messenger));
	assertTrue(messenger instanceof Refreshable);
	assertEquals("Hello World!", messenger.getMessage());

	assertTrue(ctx.getBeansOfType(ConcreteMessenger.class).values().contains(messenger));

	// Check that AnnotationUtils works with concrete proxied script classes
	assertNotNull(AnnotationUtils.findAnnotation(messenger.getClass(), Component.class));
}
 
Example #12
Source Project: java-technology-stack   Author: codeEngraver   File: DefaultListableBeanFactory.java    License: MIT License 6 votes vote down vote up
/**
 * Find a {@link Annotation} of {@code annotationType} on the specified
 * bean, traversing its interfaces and super classes if no annotation can be
 * found on the given class itself, as well as checking its raw bean class
 * if not found on the exposed bean reference (e.g. in case of a proxy).
 */
@Override
@Nullable
public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType)
		throws NoSuchBeanDefinitionException {

	A ann = null;
	Class<?> beanType = getType(beanName);
	if (beanType != null) {
		ann = AnnotationUtils.findAnnotation(beanType, annotationType);
	}
	if (ann == null && containsBeanDefinition(beanName)) {
		BeanDefinition bd = getMergedBeanDefinition(beanName);
		if (bd instanceof AbstractBeanDefinition) {
			AbstractBeanDefinition abd = (AbstractBeanDefinition) bd;
			if (abd.hasBeanClass()) {
				Class<?> beanClass = abd.getBeanClass();
				if (beanClass != beanType) {
					ann = AnnotationUtils.findAnnotation(beanClass, annotationType);
				}
			}
		}
	}
	return ann;
}
 
Example #13
Source Project: spring-analysis-note   Author: Vip-Augus   File: GroovyScriptFactoryTests.java    License: MIT License 6 votes vote down vote up
@Test  // SPR-6268
public void testRefreshableFromTagProxyTargetClass() throws Exception {
	ApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd-proxy-target-class.xml",
			getClass());
	assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("refreshableMessenger"));

	Messenger messenger = (Messenger) ctx.getBean("refreshableMessenger");

	assertTrue(AopUtils.isAopProxy(messenger));
	assertTrue(messenger instanceof Refreshable);
	assertEquals("Hello World!", messenger.getMessage());

	assertTrue(ctx.getBeansOfType(ConcreteMessenger.class).values().contains(messenger));

	// Check that AnnotationUtils works with concrete proxied script classes
	assertNotNull(AnnotationUtils.findAnnotation(messenger.getClass(), Component.class));
}
 
Example #14
Source Project: iaf   Author: ibissource   File: AMethod.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get the IbisDoc values of the referred method in IbisDocRef
 *
 * @param className - The full name of the class
 * @param methodName - The method name
 * @return the IbisDoc of the method
 */
public IbisDoc getRefValues(String className, String methodName) {

    IbisDoc ibisDoc = null;
    try {
        Class parentClass = Class.forName(className);
        for (Method parentMethod : parentClass.getDeclaredMethods()) {
            if (parentMethod.getName().equals(methodName)) {

                // Get the IbisDoc values of that method
                ibisDoc = AnnotationUtils.findAnnotation(parentMethod, IbisDoc.class);
                break;
            }
        }

    } catch (ClassNotFoundException e) {
        LOGGER.warn("Super class [" + e +  "] was not found!");
    }

    return ibisDoc;
}
 
Example #15
Source Project: openemm   Author: agnitas-org   File: ReflectionTableParser.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
private Map<String, String> getRowColumnsFromObjectFields(Object object) {
    Class<?> clazz = object.getClass();
    if (Objects.isNull(AnnotationUtils.findAnnotation(clazz, textTableClass))) {
        return Collections.emptyMap();
    }

    Map<String, String> columns = new LinkedHashMap<>();
    for (Field field : clazz.getDeclaredFields()) {
        if (field.isAnnotationPresent(textColumnClass)) {
            TextColumn textColumn = field.getAnnotation(textColumnClass);
            String columnKey = StringUtils.defaultIfEmpty(textColumn.key(), field.getName());
            columns.put(columnKey, getColumnValueFromField(field, object));
        }
    }

    return columns;
}
 
Example #16
Source Project: spring4-understanding   Author: langtianya   File: PayloadArgumentResolver.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Validate the payload if applicable.
 * <p>The default implementation checks for {@code @javax.validation.Valid},
 * Spring's {@link org.springframework.validation.annotation.Validated},
 * and custom annotations whose name starts with "Valid".
 * @param message the currently processed message
 * @param parameter the method parameter
 * @param target the target payload object
 * @throws MethodArgumentNotValidException in case of binding errors
 */
protected void validate(Message<?> message, MethodParameter parameter, Object target) {
	if (this.validator == null) {
		return;
	}
	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;
		}
	}
}
 
Example #17
Source Project: jdal   Author: chelu   File: SerializableAnnotationBeanPostProcessor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Lookup for {@link SerializableProxy} annotation on fields or methods and 
 * replace value with a Serializable proxy.
 */
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
		throws BeansException {
	
	List<AnnotatedElement> elements = AnnotatedElementAccessor.findAnnotatedElements(SerializableProxy.class, bean.getClass());
	
	for (AnnotatedElement element : elements) {
		ResolvableType type = getResolvableType(element);
		Object value = AnnotatedElementAccessor.getValue(element, bean);
		if (value != null && !(value instanceof SerializableAopProxy)) {
			SerializableProxy ann = AnnotationUtils.getAnnotation(element, SerializableProxy.class);
			boolean proxyTargetClass = !type.resolve().isInterface() || ann.proxyTargetClass();
			Object proxy = getProxy(value, proxyTargetClass, ann.useCache(), 
					getDependencyDescriptor(element), beanName);
			if (proxy != null)
				AnnotatedElementAccessor.setValue(element, bean, proxy);
		}	
	}
	
	return bean;
}
 
Example #18
Source Project: raptor   Author: geekshop   File: RaptorClientPostProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private Object getClientProxy(Class<?> interfaceClass) {
    RaptorInterface raptorInterface = AnnotationUtils.findAnnotation(interfaceClass, RaptorInterface.class);
    if (raptorInterface == null) {
        return null;
    }
    Object clientProxy = this.raptorClientRegistry.get(interfaceClass);
    if (clientProxy != null) {
        return clientProxy;
    }
    List<RaptorClientFactory> factories = this.raptorClientFactories.getIfAvailable();
    for (RaptorClientFactory raptorClientFactory : factories) {
        if (raptorClientFactory.support(interfaceClass)) {
            clientProxy = raptorClientFactory.create(interfaceClass);
            this.raptorClientRegistry.registerClientProxy(interfaceClass, clientProxy);
            break;
        }
    }
    return clientProxy;
}
 
Example #19
Source Project: java-technology-stack   Author: codeEngraver   File: AnnotationTypeFilter.java    License: MIT License 6 votes vote down vote up
@Nullable
protected Boolean hasAnnotation(String typeName) {
	if (Object.class.getName().equals(typeName)) {
		return false;
	}
	else if (typeName.startsWith("java")) {
		if (!this.annotationType.getName().startsWith("java")) {
			// Standard Java types do not have non-standard annotations on them ->
			// skip any load attempt, in particular for Java language interfaces.
			return false;
		}
		try {
			Class<?> clazz = ClassUtils.forName(typeName, getClass().getClassLoader());
			return ((this.considerMetaAnnotations ? AnnotationUtils.getAnnotation(clazz, this.annotationType) :
					clazz.getAnnotation(this.annotationType)) != null);
		}
		catch (Throwable ex) {
			// Class not regularly loadable - can't determine a match that way.
		}
	}
	return null;
}
 
Example #20
Source Project: haven-platform   Author: codeabovelab   File: NodeMapping.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private <S> Class<S> resolveJsonType(String path, Class<S> type) {
    JsonTypeInfo typeInfo = AnnotationUtils.findAnnotation(type, JsonTypeInfo.class);
    if (typeInfo == null) {
        return null;
    }
    String property = getPropertyName(typeInfo);
    String proppath = KvUtils.join(path, property);
    try {
        KvNode node = getStorage().get(proppath);
        if(node == null) {
            return null;
        }
        String str = node.getValue();
        JsonSubTypes subTypes = AnnotationUtils.findAnnotation(type, JsonSubTypes.class);
        for (JsonSubTypes.Type t : subTypes.value()) {
            if (t.name().equals(str)) {
                return (Class<S>) t.value();
            }
        }
    } catch (Exception e) {
        log.error("can't instantiate class", e);
    }
    return null;
}
 
Example #21
Source Project: citrus-admin   Author: citrusframework   File: ConfigurationProvider.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Applies configuration to system properties setting {@link SystemProperty} annotated fields as system properties.
 * @param configurationHolder
 */
public static void apply(Object configurationHolder) {
    SystemConfigurable systemConfigurable = AnnotationUtils.findAnnotation(configurationHolder.getClass(), SystemConfigurable.class);
    
    ReflectionUtils.doWithFields(configurationHolder.getClass(), field -> {
        if (field.getAnnotation(SystemProperty.class) != null) {
            SystemProperty configProperty = field.getAnnotation(SystemProperty.class);
            if (StringUtils.hasText(configProperty.name())) {
                Method getter = ReflectionUtils.findMethod(configurationHolder.getClass(), "get" + StringUtils.capitalize(field.getName()));
                if (getter != null) {
                    System.setProperty((systemConfigurable != null ? systemConfigurable.prefix() : "") + configProperty.name(), String.valueOf(ReflectionUtils.invokeMethod(getter, configurationHolder)));
                }
            }
        }
    });
}
 
Example #22
Source Project: BlogManagePlatform   Author: Frodez   File: DefaultRequiredPlugin.java    License: Apache License 2.0 6 votes vote down vote up
private void resolveAnnotatedElement(ModelPropertyContext context) {
	AnnotatedElement annotated = context.getAnnotatedElement().orNull();
	if (annotated == null) {
		return;
	}
	if (AnnotationUtils.findAnnotation(annotated, NotNull.class) != null) {
		context.getBuilder().required(true);
	} else if (AnnotationUtils.findAnnotation(annotated, NotEmpty.class) != null) {
		context.getBuilder().required(true);
	} else if (AnnotationUtils.findAnnotation(annotated, NotBlank.class) != null) {
		context.getBuilder().required(true);
	} else {
		ApiModelProperty annotation = AnnotationUtils.findAnnotation(annotated, ApiModelProperty.class);
		if (annotation != null && annotation.required()) {
			//如果ApiModelProperty上强制要求required为true,则为true
			context.getBuilder().required(true);
		} else {
			context.getBuilder().required(false);
		}
	}
}
 
Example #23
Source Project: spring-cloud-stream   Author: spring-cloud   File: TestChannelBinderConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Utility operation to return an array of configuration classes defined in
 * {@link EnableBinding} annotation. Typically used for tests that do not rely on
 * creating an SCSt boot application annotated with {@link EnableBinding}, yet require
 * full {@link Binder} configuration.
 * @param additionalConfigurationClasses config classes to be added to the default
 * config
 * @return an array of configuration classes defined in {@link EnableBinding}
 * annotation
 */
public static Class<?>[] getCompleteConfiguration(
		Class<?>... additionalConfigurationClasses) {
	List<Class<?>> configClasses = new ArrayList<>();
	configClasses.add(TestChannelBinderConfiguration.class);
	Import annotation = AnnotationUtils.getAnnotation(EnableBinding.class,
			Import.class);
	Map<String, Object> annotationAttributes = AnnotationUtils
			.getAnnotationAttributes(annotation);
	configClasses
			.addAll(Arrays.asList((Class<?>[]) annotationAttributes.get("value")));
	configClasses.add(BindingServiceConfiguration.class);
	if (additionalConfigurationClasses != null) {
		configClasses.addAll(Arrays.asList(additionalConfigurationClasses));
	}
	return configClasses.toArray(new Class<?>[] {});
}
 
Example #24
Source Project: java-technology-stack   Author: codeEngraver   File: SendToMethodReturnValueHandler.java    License: MIT License 6 votes vote down vote up
protected String[] getTargetDestinations(@Nullable Annotation annotation, Message<?> message, String defaultPrefix) {
	if (annotation != null) {
		String[] value = (String[]) AnnotationUtils.getValue(annotation);
		if (!ObjectUtils.isEmpty(value)) {
			return value;
		}
	}

	String name = DestinationPatternsMessageCondition.LOOKUP_DESTINATION_HEADER;
	String destination = (String) message.getHeaders().get(name);
	if (!StringUtils.hasText(destination)) {
		throw new IllegalStateException("No lookup destination header in " + message);
	}

	return (destination.startsWith("/") ?
			new String[] {defaultPrefix + destination} : new String[] {defaultPrefix + '/' + destination});
}
 
Example #25
Source Project: kfs   Author: kuali   File: DefaultListableBeanFactory.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Find a {@link Annotation} of <code>annotationType</code> on the specified
 * bean, traversing its interfaces and super classes if no annotation can be
 * found on the given class itself, as well as checking its raw bean class
 * if not found on the exposed bean reference (e.g. in case of a proxy).
 */
@Override
   public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType) {
	A ann = null;
	Class beanType = getType(beanName);
	if (beanType != null) {
		ann = AnnotationUtils.findAnnotation(beanType, annotationType);
	}
	if (ann == null && containsBeanDefinition(beanName)) {
		BeanDefinition bd = getMergedBeanDefinition(beanName);
		if (bd instanceof AbstractBeanDefinition) {
			AbstractBeanDefinition abd = (AbstractBeanDefinition) bd;
			if (abd.hasBeanClass()) {
				ann = AnnotationUtils.findAnnotation(abd.getBeanClass(), annotationType);
			}
		}
	}
	return ann;
}
 
Example #26
Source Project: etf-webapp   Author: etf-validator   File: WebExceptionHandler.java    License: European Union Public License 1.2 6 votes vote down vote up
private ModelAndView createError(final Exception e, final String hint, final String url, boolean submitReport)
        throws Exception {
    if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
        // Not associated with a view
        throw e;
    }

    final ModelAndView mav = new ModelAndView();
    mav.addObject("ex", e);
    if (hint != null) {
        mav.addObject("hint", hint);
    }
    mav.addObject("url", url);
    final UUID exceptionId = UUID.randomUUID();
    mav.addObject("exid", "EXID-" + exceptionId.toString());
    logger.error(
            "EXID-" + exceptionId.toString() + ": An exception occurred while trying to access \"" +
                    url + "\"",
            e);
    mav.addObject("submitReport", submitReport && View.getSubmitAnalysisData().equals("true"));
    mav.setViewName(DEFAULT_ERROR_VIEW);
    return mav;
}
 
Example #27
Source Project: springboot-plus   Author: hdhong   File: AnnotationUtil.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 获取一个类注解的名称和值
 *
 * @param annotationClasss   注解定义类
 * @param useAnnotationClass 使用注解的类
 * @return List<Map<String, Object>>
 * @throws Exception
 */
public List<Map<String, Object>> getAnnotations(Class annotationClasss, Class useAnnotationClass) {
    List<Map<String, Object>> annotationMapList = new ArrayList<>();

    Field[] fields = useAnnotationClass.getDeclaredFields();
    for (Field field : fields) {
        if (field.isAnnotationPresent(annotationClasss)) {
            Annotation p = field.getAnnotation(annotationClasss);
            Map map = AnnotationUtils.getAnnotationAttributes(p);
            map.put("fieldName", field.getName());
            annotationMapList.add(map);
        }
    }

    return annotationMapList;
}
 
Example #28
Source Project: synapse   Author: otto-de   File: EventSourceConsumerBeanPostProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private Set<EventSourceConsumer> consumerAnnotationsOf(final Method method) {
    Set<EventSourceConsumer> listeners = new HashSet<>();
    EventSourceConsumer ann = AnnotationUtils.findAnnotation(method, EventSourceConsumer.class);
    if (ann != null) {
        listeners.add(ann);
    }
    return listeners;
}
 
Example #29
Source Project: lams   Author: lamsfoundation   File: AnnotationJmxAttributeSource.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public org.springframework.jmx.export.metadata.ManagedOperationParameter[] getManagedOperationParameters(Method method)
		throws InvalidMetadataException {

	Set<ManagedOperationParameter> anns = AnnotationUtils.getRepeatableAnnotations(
			method, ManagedOperationParameter.class, ManagedOperationParameters.class);
	return copyPropertiesToBeanArray(anns, org.springframework.jmx.export.metadata.ManagedOperationParameter.class);
}
 
Example #30
Source Project: spring-analysis-note   Author: Vip-Augus   File: PayloadMethodArgumentResolver.java    License: MIT License 5 votes vote down vote up
@Nullable
private Consumer<Object> getValidator(Message<?> message, MethodParameter parameter) {
	if (this.validator == null) {
		return null;
	}
	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});
			String name = Conventions.getVariableNameForParameter(parameter);
			return target -> {
				BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(target, name);
				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);
				}
			};
		}
	}
	return null;
}