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 File: AnnotationUtil.java    From springboot-plus with 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 #2
Source File: DcsSchedulingConfiguration.java    From schedule-spring-boot-starter with 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 File: ResetSpringStaticCaches.java    From HotswapAgent with 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 #4
Source File: NodeMapping.java    From haven-platform with 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 #5
Source File: AnnotationExtractorTest.java    From eclair with 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 #6
Source File: ConfigurationProvider.java    From citrus-admin with 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 #7
Source File: AnnotationAttributesReadingVisitor.java    From spring4-understanding with 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 #8
Source File: AggregateQueryProvider.java    From mongodb-aggregate-query-support with 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 #9
Source File: ResourceInspector.java    From alfresco-remote-api with 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 #10
Source File: GroovyScriptFactoryTests.java    From spring4-understanding with 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 #11
Source File: DefaultListableBeanFactory.java    From java-technology-stack with 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 #12
Source File: GroovyScriptFactoryTests.java    From spring-analysis-note with 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 #13
Source File: AMethod.java    From iaf with 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 #14
Source File: PayloadArgumentResolver.java    From spring4-understanding with 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 #15
Source File: ApiRequestMappingHandlerMapping.java    From AthenaServing with 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 #16
Source File: RaptorClientPostProcessor.java    From raptor with 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 #17
Source File: AnnotationTypeFilter.java    From java-technology-stack with 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 #18
Source File: NodeMapping.java    From haven-platform with 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 #19
Source File: ConfigurationProvider.java    From citrus-admin with 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 #20
Source File: ReflectionTableParser.java    From openemm with 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 #21
Source File: SerializableAnnotationBeanPostProcessor.java    From jdal with 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 #22
Source File: DefaultRequiredPlugin.java    From BlogManagePlatform with 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 File: WebExceptionHandler.java    From etf-webapp with 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 #24
Source File: TestChannelBinderConfiguration.java    From spring-cloud-stream with 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 #25
Source File: SendToMethodReturnValueHandler.java    From java-technology-stack with 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 #26
Source File: DefaultListableBeanFactory.java    From kfs with 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 #27
Source File: QConfigPropertyAnnotationUtil.java    From qconfig with MIT License 5 votes vote down vote up
static Map<String, Properties> loadQConfigFilesInAnnotation(ConfigurableListableBeanFactory beanFactory, ClassLoader beanClassLoader) {
    Map<String, Properties> props = new HashMap<String, Properties>();
    for (String beanDefinitionName : beanFactory.getBeanDefinitionNames()) {
        Class<?> clz = getClassByBeanDefinitionName(beanFactory, beanDefinitionName, beanClassLoader);
        if (clz == null) continue;

        QConfigPropertySource annotation = AnnotationUtils.getAnnotation(clz, QConfigPropertySource.class);
        if (annotation == null) continue;

        String[] files = annotation.files();
        List<String> filtedFiles = new ArrayList<String>();
        for (String file : files) {
            if (!Strings.isNullOrEmpty(file)) {
                if (!props.containsKey(file)) {
                    filtedFiles.add(file);
                }
            }
        }
        if (filtedFiles.isEmpty()) continue;

        try {
            props.putAll(load(filtedFiles, annotation.trimValue(), annotation.timeout(), annotation.ignoreFileNotFound()));
        } catch (Exception e) {
            throw new RuntimeException("从qconfig读取配置文件失败", e);
        }

    }
    return props;
}
 
Example #28
Source File: ControllerExceptionHandler.java    From jframework with Apache License 2.0 5 votes vote down vote up
@ExceptionHandler({Exception.class})
public String handleException(HttpServletRequest request, Exception e) throws Exception {
    log.error("Request URL : {} , Exception : {}", request.getRequestURL(), e.getMessage());

    if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
        throw e;
    }

    return e.getMessage();
}
 
Example #29
Source File: AbstractMessageConverterMethodArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Validate the binding target 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 binder the DataBinder to be used
 * @param parameter the method parameter descriptor
 * @since 4.1.5
 * @see #isBindExceptionRequired
 */
protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) {
	Annotation[] annotations = parameter.getParameterAnnotations();
	for (Annotation ann : annotations) {
		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});
			binder.validate(validationHints);
			break;
		}
	}
}
 
Example #30
Source File: SofaTracerIntroductionInterceptor.java    From sofa-tracer with Apache License 2.0 5 votes vote down vote up
private <T extends Annotation> T findAnnotation(Method method, Class<T> clazz) {
    T annotation = AnnotationUtils.findAnnotation(method, clazz);
    if (annotation == null) {
        try {
            annotation = AnnotationUtils.findAnnotation(
                method.getDeclaringClass().getMethod(method.getName(),
                    method.getParameterTypes()), clazz);
        } catch (NoSuchMethodException | SecurityException ex) {
            SelfLog.warn("Exception occurred while tyring to find the annotation");
        }
    }
    return annotation;
}