Java Code Examples for org.springframework.core.annotation.AnnotationUtils#getValue()

The following examples show how to use org.springframework.core.annotation.AnnotationUtils#getValue() . 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: GenericXmlContextLoaderResourceLocationsTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void assertContextConfigurationLocations() throws Exception {

	final ContextConfiguration contextConfig = this.testClass.getAnnotation(ContextConfiguration.class);
	final ContextLoader contextLoader = new GenericXmlContextLoader();
	final String[] configuredLocations = (String[]) AnnotationUtils.getValue(contextConfig);
	final String[] processedLocations = contextLoader.processLocations(this.testClass, configuredLocations);

	if (logger.isDebugEnabled()) {
		logger.debug("----------------------------------------------------------------------");
		logger.debug("Configured locations: " + ObjectUtils.nullSafeToString(configuredLocations));
		logger.debug("Expected   locations: " + ObjectUtils.nullSafeToString(this.expectedLocations));
		logger.debug("Processed  locations: " + ObjectUtils.nullSafeToString(processedLocations));
	}

	assertArrayEquals("Verifying locations for test [" + this.testClass + "].", this.expectedLocations,
		processedLocations);
}
 
Example 2
Source File: PayloadArgumentResolver.java    From java-technology-stack with 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 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 3
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 4
Source File: GenericXmlContextLoaderResourceLocationsTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void assertContextConfigurationLocations() throws Exception {

	final ContextConfiguration contextConfig = this.testClass.getAnnotation(ContextConfiguration.class);
	final ContextLoader contextLoader = new GenericXmlContextLoader();
	final String[] configuredLocations = (String[]) AnnotationUtils.getValue(contextConfig);
	final String[] processedLocations = contextLoader.processLocations(this.testClass, configuredLocations);

	if (logger.isDebugEnabled()) {
		logger.debug("----------------------------------------------------------------------");
		logger.debug("Configured locations: " + ObjectUtils.nullSafeToString(configuredLocations));
		logger.debug("Expected   locations: " + ObjectUtils.nullSafeToString(this.expectedLocations));
		logger.debug("Processed  locations: " + ObjectUtils.nullSafeToString(processedLocations));
	}

	assertArrayEquals("Verifying locations for test [" + this.testClass + "].", this.expectedLocations,
		processedLocations);
}
 
Example 5
Source File: GenericXmlContextLoaderResourceLocationsTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void assertContextConfigurationLocations() throws Exception {

	final ContextConfiguration contextConfig = this.testClass.getAnnotation(ContextConfiguration.class);
	final ContextLoader contextLoader = new GenericXmlContextLoader();
	final String[] configuredLocations = (String[]) AnnotationUtils.getValue(contextConfig);
	final String[] processedLocations = contextLoader.processLocations(this.testClass, configuredLocations);

	if (logger.isDebugEnabled()) {
		logger.debug("----------------------------------------------------------------------");
		logger.debug("Configured locations: " + ObjectUtils.nullSafeToString(configuredLocations));
		logger.debug("Expected   locations: " + ObjectUtils.nullSafeToString(this.expectedLocations));
		logger.debug("Processed  locations: " + ObjectUtils.nullSafeToString(processedLocations));
	}

	assertArrayEquals("Verifying locations for test [" + this.testClass + "].", this.expectedLocations,
		processedLocations);
}
 
Example 6
Source File: SendToMethodReturnValueHandler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
protected String[] getTargetDestinations(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 7
Source File: AbstractMessageReaderArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Check if the given MethodParameter requires validation and if so return
 * a (possibly empty) Object[] with validation hints. A return value of
 * {@code null} indicates that validation is not required.
 */
@Nullable
private Object[] extractValidationHints(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));
			return (hints instanceof Object[] ? (Object[]) hints : new Object[] {hints});
		}
	}
	return null;
}
 
Example 8
Source File: CommunityServiceImplTest.java    From cloudstreetmarket.com with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void delete_methodSecured() throws NoSuchMethodException {
	Annotation[] annotations = AnnotationUtils.getAnnotations(CommunityServiceImpl.class.getMethod("delete", String.class));
	List<Annotation> annotationsList = Arrays.asList(annotations);
	
	Optional<Annotation> securedOpt = annotationsList.stream()
												.filter(a -> a.annotationType().isAssignableFrom(Secured.class))
												.findFirst();
	
	assertTrue(securedOpt.isPresent());
	Annotation securedAnnotation = securedOpt.get();
	String[] values = (String[]) AnnotationUtils.getValue(securedAnnotation);
	assertTrue(Arrays.asList(values).contains(Role.ADMIN));
	assertTrue(Arrays.asList(values).contains(Role.SYSTEM));
}
 
Example 9
Source File: AbstractAspectJAdvisorFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private String resolveExpression(A annotation) {
	for (String attributeName : EXPRESSION_ATTRIBUTES) {
		Object val = AnnotationUtils.getValue(annotation, attributeName);
		if (val instanceof String) {
			String str = (String) val;
			if (!str.isEmpty()) {
				return str;
			}
		}
	}
	throw new IllegalStateException("Failed to resolve expression: " + annotation);
}
 
Example 10
Source File: MergedSqlConfig.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Construct a {@code MergedSqlConfig} instance by merging the configuration
 * from the supplied local (potentially method-level) {@code @SqlConfig} annotation
 * with class-level configuration discovered on the supplied {@code testClass}.
 * <p>Local configuration overrides class-level configuration.
 * <p>If the test class is not annotated with {@code @SqlConfig}, no merging
 * takes place and the local configuration is used "as is".
 */
MergedSqlConfig(SqlConfig localSqlConfig, Class<?> testClass) {
	Assert.notNull(localSqlConfig, "Local @SqlConfig must not be null");
	Assert.notNull(testClass, "testClass must not be null");

	// Get global attributes, if any.
	AnnotationAttributes attributes = AnnotatedElementUtils.findMergedAnnotationAttributes(
			testClass, SqlConfig.class.getName(), false, false);

	// Override global attributes with local attributes.
	if (attributes != null) {
		for (String key : attributes.keySet()) {
			Object value = AnnotationUtils.getValue(localSqlConfig, key);
			if (value != null) {
				// Is the value explicit (i.e., not a 'default')?
				if (!value.equals("") && value != TransactionMode.DEFAULT && value != ErrorMode.DEFAULT) {
					attributes.put(key, value);
				}
			}
		}
	}
	else {
		// Otherwise, use local attributes only.
		attributes = AnnotationUtils.getAnnotationAttributes(localSqlConfig, false, false);
	}

	this.dataSource = attributes.getString("dataSource");
	this.transactionManager = attributes.getString("transactionManager");
	this.transactionMode = getEnum(attributes, "transactionMode", TransactionMode.DEFAULT, TransactionMode.INFERRED);
	this.encoding = attributes.getString("encoding");
	this.separator = getString(attributes, "separator", ScriptUtils.DEFAULT_STATEMENT_SEPARATOR);
	this.commentPrefix = getString(attributes, "commentPrefix", ScriptUtils.DEFAULT_COMMENT_PREFIX);
	this.blockCommentStartDelimiter = getString(attributes, "blockCommentStartDelimiter",
			ScriptUtils.DEFAULT_BLOCK_COMMENT_START_DELIMITER);
	this.blockCommentEndDelimiter = getString(attributes, "blockCommentEndDelimiter",
			ScriptUtils.DEFAULT_BLOCK_COMMENT_END_DELIMITER);
	this.errorMode = getEnum(attributes, "errorMode", ErrorMode.DEFAULT, ErrorMode.FAIL_ON_ERROR);
}
 
Example 11
Source File: SolrQueryMethod.java    From dubbox with Apache License 2.0 5 votes vote down vote up
private Integer getAnnotationValueAsIntOrNullIfNegative(Annotation annotation, String attributeName) {
	Integer timeAllowed = (Integer) AnnotationUtils.getValue(annotation, attributeName);
	if (timeAllowed != null && timeAllowed.intValue() > 0) {
		return timeAllowed;
	}
	return null;
}
 
Example 12
Source File: ModelAttributeMethodProcessor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Validate the model attribute 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 methodParam the method parameter
 */
protected void validateIfApplicable(WebDataBinder binder, MethodParameter methodParam) {
	Annotation[] annotations = methodParam.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 13
Source File: SimpleDbQueryMethod.java    From spring-data-simpledb with MIT License 5 votes vote down vote up
/**
 * Returns the {@link Query} annotation's attribute casted to the given type or default value if no annotation
 * available.
 * 
 * @param attribute
 * @param type
 * @return
 */
private <T> T getAnnotationValue(String attribute, Class<T> type) {

	Query annotation = method.getAnnotation(Query.class);
	Object value = annotation == null ? AnnotationUtils.getDefaultValue(Query.class, attribute) : AnnotationUtils
			.getValue(annotation, attribute);

	return type.cast(value);
}
 
Example 14
Source File: SolrQueryMethod.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private List<String> getAnnotationValuesAsStringList(Annotation annotation, String attribute) {
	String[] values = (String[]) AnnotationUtils.getValue(annotation, attribute);
	if (values.length > 1 || (values.length == 1 && StringUtils.hasText(values[0]))) {
		return CollectionUtils.arrayToList(values);
	}
	return Collections.emptyList();
}
 
Example 15
Source File: AbstractAspectJAdvisorFactory.java    From java-technology-stack with MIT License 5 votes vote down vote up
private String resolveExpression(A annotation) {
	for (String attributeName : EXPRESSION_ATTRIBUTES) {
		Object val = AnnotationUtils.getValue(annotation, attributeName);
		if (val instanceof String) {
			String str = (String) val;
			if (!str.isEmpty()) {
				return str;
			}
		}
	}
	throw new IllegalStateException("Failed to resolve expression: " + annotation);
}
 
Example 16
Source File: AbstractMessageConverterMethodArgumentResolver.java    From lams with GNU General Public License v2.0 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 17
Source File: FormModelMethodArgumentResolver.java    From distributed-transaction-process with MIT License 5 votes vote down vote up
/**
 * Validate the model attribute if applicable.
 * <p>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});
        }
    }
}
 
Example 18
Source File: AbstractMessageConverterMethodArgumentResolver.java    From java-technology-stack 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 19
Source File: QualifierAnnotationAutowireCandidateResolver.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Extract the value attribute from the given annotation.
 */
protected Object extractValue(Annotation valueAnnotation) {
	Object value = AnnotationUtils.getValue(valueAnnotation);
	if (value == null) {
		throw new IllegalStateException("Value annotation must have a value attribute");
	}
	return value;
}
 
Example 20
Source File: StreamListenerSetupMethodOrchestrator.java    From spring-cloud-stream with Apache License 2.0 4 votes vote down vote up
/**
 * Default implementation for adapting each of the incoming method arguments using an
 * available {@link StreamListenerParameterAdapter} and provide the adapted collection
 * of arguments back to the caller.
 * @param method annotated with {@link StreamListener}
 * @param inboundName inbound binding
 * @param applicationContext spring application context
 * @param streamListenerParameterAdapters used for adapting the method arguments
 * @return adapted incoming arguments
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
default 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));
		}
		else if (methodParameter.hasParameterAnnotation(Output.class)) {
			targetReferenceValue = AnnotationUtils
					.getValue(methodParameter.getParameterAnnotation(Output.class));
		}
		else if (arguments.length == 1 && StringUtils.hasText(inboundName)) {
			targetReferenceValue = inboundName;
		}
		if (targetReferenceValue != null) {
			Assert.isInstanceOf(String.class, targetReferenceValue,
					"Annotation value must be a String");
			Object targetBean = applicationContext
					.getBean((String) targetReferenceValue);
			// Iterate existing parameter adapters first
			for (StreamListenerParameterAdapter streamListenerParameterAdapter : streamListenerParameterAdapters) {
				if (streamListenerParameterAdapter.supports(targetBean.getClass(),
						methodParameter)) {
					arguments[parameterIndex] = streamListenerParameterAdapter
							.adapt(targetBean, methodParameter);
					break;
				}
			}
			if (arguments[parameterIndex] == null
					&& parameterType.isAssignableFrom(targetBean.getClass())) {
				arguments[parameterIndex] = targetBean;
			}
			Assert.notNull(arguments[parameterIndex],
					"Cannot convert argument " + parameterIndex + " of " + method
							+ "from " + targetBean.getClass() + " to "
							+ parameterType);
		}
		else {
			throw new IllegalStateException(
					StreamListenerErrorMessages.INVALID_DECLARATIVE_METHOD_PARAMETERS);
		}
	}
	return arguments;
}