Java Code Examples for org.springframework.core.ResolvableType#forMethodParameter()

The following examples show how to use org.springframework.core.ResolvableType#forMethodParameter() . 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: AbstractEncoderMethodReturnValueHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Flux<DataBuffer> encodeContent(
		@Nullable Object content, MethodParameter returnType, DataBufferFactory bufferFactory,
		@Nullable MimeType mimeType, Map<String, Object> hints) {

	ResolvableType returnValueType = ResolvableType.forMethodParameter(returnType);
	ReactiveAdapter adapter = getAdapterRegistry().getAdapter(returnValueType.resolve(), content);

	Publisher<?> publisher;
	ResolvableType elementType;
	if (adapter != null) {
		publisher = adapter.toPublisher(content);
		boolean isUnwrapped = KotlinDetector.isKotlinReflectPresent() &&
				KotlinDetector.isKotlinType(returnType.getContainingClass()) &&
				KotlinDelegate.isSuspend(returnType.getMethod()) &&
				!COROUTINES_FLOW_CLASS_NAME.equals(returnValueType.toClass().getName());
		ResolvableType genericType = isUnwrapped ? returnValueType : returnValueType.getGeneric();
		elementType = getElementType(adapter, genericType);
	}
	else {
		publisher = Mono.justOrEmpty(content);
		elementType = (returnValueType.toClass() == Object.class && content != null ?
				ResolvableType.forInstance(content) : returnValueType);
	}

	if (elementType.resolve() == void.class || elementType.resolve() == Void.class) {
		return Flux.from(publisher).cast(DataBuffer.class);
	}

	Encoder<?> encoder = getEncoder(elementType, mimeType);
	return Flux.from((Publisher) publisher).map(value ->
			encodeValue(value, elementType, encoder, bufferFactory, mimeType, hints));
}
 
Example 2
Source File: WxMessageReturnValueHandler.java    From FastBootWeixin with Apache License 2.0 5 votes vote down vote up
@Override
public boolean supportsReturnType(MethodParameter returnType) {
    if (returnType.hasMethodAnnotation(WxMapping.class)) {
        return false;
    }
    ResolvableType resolvableType = ResolvableType.forMethodParameter(returnType);
    ResolvableType arrayType = ResolvableType.forArrayComponent(ResolvableType.forClass(WxMessage.class));
    ResolvableType iterableType = ResolvableType.forClassWithGenerics(Iterable.class, WxMessage.class);
    return arrayType.isAssignableFrom(resolvableType) || iterableType.isAssignableFrom(resolvableType);
}
 
Example 3
Source File: TypeDescriptor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new type descriptor from a {@link MethodParameter}.
 * <p>Use this constructor when a source or target conversion point is a
 * constructor parameter, method parameter, or method return value.
 * @param methodParameter the method parameter
 */
public TypeDescriptor(MethodParameter methodParameter) {
	Assert.notNull(methodParameter, "MethodParameter must not be null");
	this.resolvableType = ResolvableType.forMethodParameter(methodParameter);
	this.type = this.resolvableType.resolve(methodParameter.getParameterType());
	this.annotations = (methodParameter.getParameterIndex() == -1 ?
			nullSafeAnnotations(methodParameter.getMethodAnnotations()) :
			nullSafeAnnotations(methodParameter.getParameterAnnotations()));
}
 
Example 4
Source File: TypeDescriptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a new type descriptor from a {@link MethodParameter}.
 * <p>Use this constructor when a source or target conversion point is a
 * constructor parameter, method parameter, or method return value.
 * @param methodParameter the method parameter
 */
public TypeDescriptor(MethodParameter methodParameter) {
	this.resolvableType = ResolvableType.forMethodParameter(methodParameter);
	this.type = this.resolvableType.resolve(methodParameter.getParameterType());
	this.annotatedElement = new AnnotatedElementAdapter(methodParameter.getParameterIndex() == -1 ?
			methodParameter.getMethodAnnotations() : methodParameter.getParameterAnnotations());
}
 
Example 5
Source File: DependencyDescriptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Build a ResolvableType object for the wrapped parameter/field.
 * @since 4.0
 */
public ResolvableType getResolvableType() {
	ResolvableType resolvableType = this.resolvableType;
	if (resolvableType == null) {
		resolvableType = (this.field != null ?
				ResolvableType.forField(this.field, this.nestingLevel, this.containingClass) :
				ResolvableType.forMethodParameter(this.methodParameter));
		this.resolvableType = resolvableType;
	}
	return resolvableType;
}
 
Example 6
Source File: DependencyDescriptor.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Build a {@link ResolvableType} object for the wrapped parameter/field.
 * @since 4.0
 */
public ResolvableType getResolvableType() {
	ResolvableType resolvableType = this.resolvableType;
	if (resolvableType == null) {
		resolvableType = (this.field != null ?
				ResolvableType.forField(this.field, this.nestingLevel, this.containingClass) :
				ResolvableType.forMethodParameter(obtainMethodParameter()));
		this.resolvableType = resolvableType;
	}
	return resolvableType;
}
 
Example 7
Source File: KStreamStreamListenerParameterAdapter.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public KStream adapt(KStream<?, ?> bindingTarget, MethodParameter parameter) {
	ResolvableType resolvableType = ResolvableType.forMethodParameter(parameter);
	final Class<?> valueClass = (resolvableType.getGeneric(1).getRawClass() != null)
			? (resolvableType.getGeneric(1).getRawClass()) : Object.class;
	if (this.KafkaStreamsBindingInformationCatalogue
			.isUseNativeDecoding(bindingTarget)) {
		return bindingTarget;
	}
	else {
		return this.kafkaStreamsMessageConversionDelegate
				.deserializeOnInbound(valueClass, bindingTarget);
	}
}
 
Example 8
Source File: TypeDescriptor.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Create a new type descriptor from a {@link MethodParameter}.
 * <p>Use this constructor when a source or target conversion point is a
 * constructor parameter, method parameter, or method return value.
 * @param methodParameter the method parameter
 */
public TypeDescriptor(MethodParameter methodParameter) {
	this.resolvableType = ResolvableType.forMethodParameter(methodParameter);
	this.type = this.resolvableType.resolve(methodParameter.getNestedParameterType());
	this.annotatedElement = new AnnotatedElementAdapter(methodParameter.getParameterIndex() == -1 ?
			methodParameter.getMethodAnnotations() : methodParameter.getParameterAnnotations());
}
 
Example 9
Source File: LoggedInUserAccountArgumentResolver.java    From salespoint with Apache License 2.0 5 votes vote down vote up
@Override
public boolean supportsParameter(MethodParameter parameter) {

	if (!parameter.hasParameterAnnotation(LoggedIn.class)) {
		return false;
	}

	ResolvableType type = ResolvableType.forMethodParameter(parameter);
	return USER_ACCOUNT.isAssignableFrom(type) || OPTIONAL_OF_USER_ACCOUNT.isAssignableFrom(type);
}
 
Example 10
Source File: SerializableAnnotationBeanPostProcessor.java    From jdal with Apache License 2.0 5 votes vote down vote up
private ResolvableType getResolvableType(AnnotatedElement element) {
	if (element instanceof Field)
		return ResolvableType.forField((Field) element);
	else if (element instanceof Method)
		return ResolvableType.forMethodParameter(
				new MethodParameter((Method) element, 0));
	
	throw new IllegalArgumentException("SerializableProxy annotation should only be applied on types" +
			", fields or methods but was found in [" + element.toString() + "]");
}
 
Example 11
Source File: DependencyDescriptor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Build a {@link ResolvableType} object for the wrapped parameter/field.
 * @since 4.0
 */
public ResolvableType getResolvableType() {
	ResolvableType resolvableType = this.resolvableType;
	if (resolvableType == null) {
		resolvableType = (this.field != null ?
				ResolvableType.forField(this.field, this.nestingLevel, this.containingClass) :
				ResolvableType.forMethodParameter(obtainMethodParameter()));
		this.resolvableType = resolvableType;
	}
	return resolvableType;
}
 
Example 12
Source File: TypeDescriptor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Create a new type descriptor from a {@link Property}.
 * <p>Use this constructor when a source or target conversion point is a
 * property on a Java class.
 * @param property the property
 */
public TypeDescriptor(Property property) {
	Assert.notNull(property, "Property must not be null");
	this.resolvableType = ResolvableType.forMethodParameter(property.getMethodParameter());
	this.type = this.resolvableType.resolve(property.getType());
	this.annotatedElement = new AnnotatedElementAdapter(property.getAnnotations());
}
 
Example 13
Source File: TypeDescriptor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Create a new type descriptor from a {@link MethodParameter}.
 * <p>Use this constructor when a source or target conversion point is a
 * constructor parameter, method parameter, or method return value.
 * @param methodParameter the method parameter
 */
public TypeDescriptor(MethodParameter methodParameter) {
	this.resolvableType = ResolvableType.forMethodParameter(methodParameter);
	this.type = this.resolvableType.resolve(methodParameter.getNestedParameterType());
	this.annotatedElement = new AnnotatedElementAdapter(methodParameter.getParameterIndex() == -1 ?
			methodParameter.getMethodAnnotations() : methodParameter.getParameterAnnotations());
}
 
Example 14
Source File: HandlerResult.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Create a new {@code HandlerResult}.
 * @param handler the handler that handled the request
 * @param returnValue the return value from the handler possibly {@code null}
 * @param returnType the return value type
 * @param context the binding context used for request handling
 */
public HandlerResult(Object handler, @Nullable Object returnValue, MethodParameter returnType,
		@Nullable BindingContext context) {

	Assert.notNull(handler, "'handler' is required");
	Assert.notNull(returnType, "'returnType' is required");
	this.handler = handler;
	this.returnValue = returnValue;
	this.returnType = ResolvableType.forMethodParameter(returnType);
	this.bindingContext = (context != null ? context : new BindingContext());
}
 
Example 15
Source File: LoggedInUserAccountArgumentResolver.java    From salespoint with Apache License 2.0 5 votes vote down vote up
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
		NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

	Optional<UserAccount> user = authenticationManager.getCurrentUser();
	ResolvableType parameterType = ResolvableType.forMethodParameter(parameter);

	return OPTIONAL_OF_USER_ACCOUNT.isAssignableFrom(parameterType) ? user
			: user.orElseThrow(() -> new ServletRequestBindingException(USER_ACCOUNT_EXPECTED));
}
 
Example 16
Source File: AbstractMessageReaderArgumentResolver.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Read the body from a method argument with {@link HttpMessageReader}.
 * @param bodyParam represents the element type for the body
 * @param actualParam the actual method argument type; possibly different
 * from {@code bodyParam}, e.g. for an {@code HttpEntity} argument
 * @param isBodyRequired true if the body is required
 * @param bindingContext the binding context to use
 * @param exchange the current exchange
 * @return a Mono with the value to use for the method argument
 * @since 5.0.2
 */
protected Mono<Object> readBody(MethodParameter bodyParam, @Nullable MethodParameter actualParam,
		boolean isBodyRequired, BindingContext bindingContext, ServerWebExchange exchange) {

	ResolvableType bodyType = ResolvableType.forMethodParameter(bodyParam);
	ResolvableType actualType = (actualParam != null ? ResolvableType.forMethodParameter(actualParam) : bodyType);
	Class<?> resolvedType = bodyType.resolve();
	ReactiveAdapter adapter = (resolvedType != null ? getAdapterRegistry().getAdapter(resolvedType) : null);
	ResolvableType elementType = (adapter != null ? bodyType.getGeneric() : bodyType);
	isBodyRequired = isBodyRequired || (adapter != null && !adapter.supportsEmpty());

	ServerHttpRequest request = exchange.getRequest();
	ServerHttpResponse response = exchange.getResponse();

	MediaType contentType = request.getHeaders().getContentType();
	MediaType mediaType = (contentType != null ? contentType : MediaType.APPLICATION_OCTET_STREAM);
	Object[] hints = extractValidationHints(bodyParam);

	if (logger.isDebugEnabled()) {
		logger.debug(exchange.getLogPrefix() + (contentType != null ?
				"Content-Type:" + contentType :
				"No Content-Type, using " + MediaType.APPLICATION_OCTET_STREAM));
	}

	for (HttpMessageReader<?> reader : getMessageReaders()) {
		if (reader.canRead(elementType, mediaType)) {
			Map<String, Object> readHints = Hints.from(Hints.LOG_PREFIX_HINT, exchange.getLogPrefix());
			if (adapter != null && adapter.isMultiValue()) {
				if (logger.isDebugEnabled()) {
					logger.debug(exchange.getLogPrefix() + "0..N [" + elementType + "]");
				}
				Flux<?> flux = reader.read(actualType, elementType, request, response, readHints);
				flux = flux.onErrorResume(ex -> Flux.error(handleReadError(bodyParam, ex)));
				if (isBodyRequired) {
					flux = flux.switchIfEmpty(Flux.error(() -> handleMissingBody(bodyParam)));
				}
				if (hints != null) {
					flux = flux.doOnNext(target ->
							validate(target, hints, bodyParam, bindingContext, exchange));
				}
				return Mono.just(adapter.fromPublisher(flux));
			}
			else {
				// Single-value (with or without reactive type wrapper)
				if (logger.isDebugEnabled()) {
					logger.debug(exchange.getLogPrefix() + "0..1 [" + elementType + "]");
				}
				Mono<?> mono = reader.readMono(actualType, elementType, request, response, readHints);
				mono = mono.onErrorResume(ex -> Mono.error(handleReadError(bodyParam, ex)));
				if (isBodyRequired) {
					mono = mono.switchIfEmpty(Mono.error(() -> handleMissingBody(bodyParam)));
				}
				if (hints != null) {
					mono = mono.doOnNext(target ->
							validate(target, hints, bodyParam, bindingContext, exchange));
				}
				return (adapter != null ? Mono.just(adapter.fromPublisher(mono)) : Mono.from(mono));
			}
		}
	}

	// No compatible reader but body may be empty..

	HttpMethod method = request.getMethod();
	if (contentType == null && method != null && SUPPORTED_METHODS.contains(method)) {
		Flux<DataBuffer> body = request.getBody().doOnNext(o -> {
			// Body not empty, back to 415..
			throw new UnsupportedMediaTypeStatusException(mediaType, this.supportedMediaTypes, elementType);
		});
		if (isBodyRequired) {
			body = body.switchIfEmpty(Mono.error(() -> handleMissingBody(bodyParam)));
		}
		return (adapter != null ? Mono.just(adapter.fromPublisher(body)) : Mono.from(body));
	}

	return Mono.error(new UnsupportedMediaTypeStatusException(mediaType, this.supportedMediaTypes, elementType));
}
 
Example 17
Source File: ServiceMethodInfo.java    From spring-cloud-sockets with Apache License 2.0 4 votes vote down vote up
private void resolvePayloadType(){
	this.payloadType = ResolvableType.forMethodParameter(this.method, payloadParameter.getParameterIndex());
}
 
Example 18
Source File: AbstractMessageWriterResultHandler.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Write a given body to the response with {@link HttpMessageWriter}.
 * @param body the object to write
 * @param bodyParameter the {@link MethodParameter} of the body to write
 * @param actualParam the actual return type of the method that returned the value;
 * could be different from {@code bodyParameter} when processing {@code HttpEntity}
 * for example
 * @param exchange the current exchange
 * @return indicates completion or error
 * @since 5.0.2
 */
@SuppressWarnings({"unchecked", "rawtypes", "ConstantConditions"})
protected Mono<Void> writeBody(@Nullable Object body, MethodParameter bodyParameter,
		@Nullable MethodParameter actualParam, ServerWebExchange exchange) {

	ResolvableType bodyType = ResolvableType.forMethodParameter(bodyParameter);
	ResolvableType actualType = (actualParam != null ? ResolvableType.forMethodParameter(actualParam) : bodyType);
	ReactiveAdapter adapter = getAdapterRegistry().getAdapter(bodyType.resolve(), body);

	Publisher<?> publisher;
	ResolvableType elementType;
	ResolvableType actualElementType;
	if (adapter != null) {
		publisher = adapter.toPublisher(body);
		boolean isUnwrapped = KotlinDetector.isKotlinReflectPresent() &&
				KotlinDetector.isKotlinType(bodyParameter.getContainingClass()) &&
				KotlinDelegate.isSuspend(bodyParameter.getMethod()) &&
				!COROUTINES_FLOW_CLASS_NAME.equals(bodyType.toClass().getName());
		ResolvableType genericType = isUnwrapped ? bodyType : bodyType.getGeneric();
		elementType = getElementType(adapter, genericType);
		actualElementType = elementType;
	}
	else {
		publisher = Mono.justOrEmpty(body);
		actualElementType = body != null ? ResolvableType.forInstance(body) : bodyType;
		elementType = (bodyType.toClass() == Object.class && body != null ? actualElementType : bodyType);
	}

	if (elementType.resolve() == void.class || elementType.resolve() == Void.class) {
		return Mono.from((Publisher<Void>) publisher);
	}

	MediaType bestMediaType = selectMediaType(exchange, () -> getMediaTypesFor(elementType));
	if (bestMediaType != null) {
		String logPrefix = exchange.getLogPrefix();
		if (logger.isDebugEnabled()) {
			logger.debug(logPrefix +
					(publisher instanceof Mono ? "0..1" : "0..N") + " [" + elementType + "]");
		}
		for (HttpMessageWriter<?> writer : getMessageWriters()) {
			if (writer.canWrite(actualElementType, bestMediaType)) {
				return writer.write((Publisher) publisher, actualType, elementType,
						bestMediaType, exchange.getRequest(), exchange.getResponse(),
						Hints.from(Hints.LOG_PREFIX_HINT, logPrefix));
			}
		}
	}

	List<MediaType> mediaTypes = getMediaTypesFor(elementType);
	if (bestMediaType == null && mediaTypes.isEmpty()) {
		return Mono.error(new IllegalStateException("No HttpMessageWriter for " + elementType));
	}
	return Mono.error(new NotAcceptableStatusException(mediaTypes));
}
 
Example 19
Source File: PayloadMethodArgumentResolver.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private Mono<Object> decodeContent(MethodParameter parameter, Message<?> message,
		boolean isContentRequired, Flux<DataBuffer> content, MimeType mimeType) {

	ResolvableType targetType = ResolvableType.forMethodParameter(parameter);
	Class<?> resolvedType = targetType.resolve();
	ReactiveAdapter adapter = (resolvedType != null ? getAdapterRegistry().getAdapter(resolvedType) : null);
	ResolvableType elementType = (adapter != null ? targetType.getGeneric() : targetType);
	isContentRequired = isContentRequired || (adapter != null && !adapter.supportsEmpty());
	Consumer<Object> validator = getValidator(message, parameter);

	Map<String, Object> hints = Collections.emptyMap();

	for (Decoder<?> decoder : this.decoders) {
		if (decoder.canDecode(elementType, mimeType)) {
			if (adapter != null && adapter.isMultiValue()) {
				Flux<?> flux = content
						.map(buffer -> decoder.decode(buffer, elementType, mimeType, hints))
						.onErrorResume(ex -> Flux.error(handleReadError(parameter, message, ex)));
				if (isContentRequired) {
					flux = flux.switchIfEmpty(Flux.error(() -> handleMissingBody(parameter, message)));
				}
				if (validator != null) {
					flux = flux.doOnNext(validator);
				}
				return Mono.just(adapter.fromPublisher(flux));
			}
			else {
				// Single-value (with or without reactive type wrapper)
				Mono<?> mono = content.next()
						.map(buffer -> decoder.decode(buffer, elementType, mimeType, hints))
						.onErrorResume(ex -> Mono.error(handleReadError(parameter, message, ex)));
				if (isContentRequired) {
					mono = mono.switchIfEmpty(Mono.error(() -> handleMissingBody(parameter, message)));
				}
				if (validator != null) {
					mono = mono.doOnNext(validator);
				}
				return (adapter != null ? Mono.just(adapter.fromPublisher(mono)) : Mono.from(mono));
			}
		}
	}

	return Mono.error(new MethodArgumentResolutionException(
			message, parameter, "Cannot decode to [" + targetType + "]" + message));
}
 
Example 20
Source File: DependencyDescriptor.java    From blog_demos with Apache License 2.0 4 votes vote down vote up
/**
 * Build a ResolvableType object for the wrapped parameter/field.
 */
public ResolvableType getResolvableType() {
	return (this.field != null ? ResolvableType.forField(this.field, this.nestingLevel, this.containingClass) :
			ResolvableType.forMethodParameter(this.methodParameter));
}