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

The following examples show how to use org.springframework.core.ResolvableType#forClass() . 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: Jackson2JsonEncoderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void classLevelJsonView() {
	JacksonViewBean bean = new JacksonViewBean();
	bean.setWithView1("with");
	bean.setWithView2("with");
	bean.setWithoutView("without");
	Mono<JacksonViewBean> input = Mono.just(bean);

	ResolvableType type = ResolvableType.forClass(JacksonViewBean.class);
	Map<String, Object> hints = singletonMap(JSON_VIEW_HINT, MyJacksonView3.class);

	testEncode(input, type, step -> step
					.consumeNextWith(expectString("{\"withoutView\":\"without\"}")
							.andThen(DataBufferUtils::release))
					.verifyComplete(),
			null, hints);
}
 
Example 2
Source File: Jackson2JsonEncoderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void fieldLevelJsonView() {
	JacksonViewBean bean = new JacksonViewBean();
	bean.setWithView1("with");
	bean.setWithView2("with");
	bean.setWithoutView("without");
	Mono<JacksonViewBean> input = Mono.just(bean);

	ResolvableType type = ResolvableType.forClass(JacksonViewBean.class);
	Map<String, Object> hints = singletonMap(JSON_VIEW_HINT, MyJacksonView1.class);

	testEncode(input, type, step -> step
					.consumeNextWith(expectString("{\"withView1\":\"with\"}")
							.andThen(DataBufferUtils::release))
					.verifyComplete(),
			null, hints);
}
 
Example 3
Source File: FunctionTypeUtils.java    From spring-cloud-function with Apache License 2.0 6 votes vote down vote up
public static Type compose(Type originType, Type composedType) {
	ResolvableType resolvableOriginType = ResolvableType.forType(originType);
	ResolvableType resolvableComposedType = ResolvableType.forType(composedType);
	if (FunctionTypeUtils.isSupplier(originType)) {
		if (FunctionTypeUtils.isFunction(composedType)) {
			ResolvableType resolvableLastArgument = resolvableComposedType.getGenerics()[1];
			resolvableLastArgument = FunctionTypeUtils.isPublisher(resolvableOriginType.getGeneric(0).getType())
					? ResolvableType.forClassWithGenerics(resolvableOriginType.getGeneric(0).getRawClass(), resolvableLastArgument)
							: resolvableLastArgument;
					originType = ResolvableType.forClassWithGenerics(Supplier.class, resolvableLastArgument).getType();
		}
	}
	else  {
		ResolvableType outType = FunctionTypeUtils.isConsumer(composedType)
				? ResolvableType.forClass(Void.class)
						: (ObjectUtils.isEmpty(resolvableComposedType.getGenerics())
								? ResolvableType.forClass(Object.class) : resolvableComposedType.getGenerics()[1]);

		originType = ResolvableType.forClassWithGenerics(Function.class,
				ObjectUtils.isEmpty(resolvableOriginType.getGenerics()) ? resolvableOriginType : resolvableOriginType.getGenerics()[0],
						outType).getType();
	}
	return originType;
}
 
Example 4
Source File: ServletInvocableHandlerMethodTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test // SPR-15478
public void wrapConcurrentResult_CollectedValuesListWithResponseEntity() throws Exception {
	List<HttpMessageConverter<?>> converters = Collections.singletonList(new MappingJackson2HttpMessageConverter());
	ResolvableType elementType = ResolvableType.forClass(Bar.class);
	ReactiveTypeHandler.CollectedValuesList result = new ReactiveTypeHandler.CollectedValuesList(elementType);
	result.add(new Bar("foo"));
	result.add(new Bar("bar"));

	ContentNegotiationManager manager = new ContentNegotiationManager();
	this.returnValueHandlers.addHandler(new RequestResponseBodyMethodProcessor(converters, manager));
	ServletInvocableHandlerMethod hm = getHandlerMethod(new ResponseEntityHandler(), "handleFlux");
	hm = hm.wrapConcurrentResult(result);
	hm.invokeAndHandle(this.webRequest, this.mavContainer);

	assertEquals(200, this.response.getStatus());
	assertEquals("[{\"value\":\"foo\"},{\"value\":\"bar\"}]", this.response.getContentAsString());
}
 
Example 5
Source File: GenericTypeAwareAutowireCandidateResolver.java    From blog_demos with Apache License 2.0 6 votes vote down vote up
protected ResolvableType getReturnTypeForFactoryMethod(RootBeanDefinition rbd, DependencyDescriptor descriptor) {
	// Should typically be set for any kind of factory method, since the BeanFactory
	// pre-resolves them before reaching out to the AutowireCandidateResolver...
	Class<?> preResolved = rbd.resolvedFactoryMethodReturnType;
	if (preResolved != null) {
		return ResolvableType.forClass(preResolved);
	}
	else {
		Method resolvedFactoryMethod = rbd.getResolvedFactoryMethod();
		if (resolvedFactoryMethod != null) {
			if (descriptor.getDependencyType().isAssignableFrom(resolvedFactoryMethod.getReturnType())) {
				// Only use factory method metadata if the return type is actually expressive enough
				// for our dependency. Otherwise, the returned instance type may have matched instead
				// in case of a singleton instance having been registered with the container already.
				return ResolvableType.forMethodReturnType(resolvedFactoryMethod);
			}
		}
		return null;
	}
}
 
Example 6
Source File: AbstractMessageWriterResultHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
private ResolvableType getElementType(ReactiveAdapter adapter, ResolvableType genericType) {
	if (adapter.isNoValue()) {
		return ResolvableType.forClass(Void.class);
	}
	else if (genericType != ResolvableType.NONE) {
		return genericType;
	}
	else {
		return ResolvableType.forClass(Object.class);
	}
}
 
Example 7
Source File: Jackson2SmileEncoderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@Test
public void canEncode() {
	ResolvableType pojoType = ResolvableType.forClass(Pojo.class);
	assertTrue(this.encoder.canEncode(pojoType, SMILE_MIME_TYPE));
	assertTrue(this.encoder.canEncode(pojoType, STREAM_SMILE_MIME_TYPE));
	assertTrue(this.encoder.canEncode(pojoType, null));

	// SPR-15464
	assertTrue(this.encoder.canEncode(ResolvableType.NONE, null));
}
 
Example 8
Source File: Jackson2JsonEncoderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void canNotEncode() {
	assertFalse(this.encoder.canEncode(ResolvableType.forClass(String.class), null));
	assertFalse(this.encoder.canEncode(ResolvableType.forClass(Pojo.class), APPLICATION_XML));

	ResolvableType sseType = ResolvableType.forClass(ServerSentEvent.class);
	assertFalse(this.encoder.canEncode(sseType, APPLICATION_JSON));
}
 
Example 9
Source File: ResourceRegionEncoderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void canEncode() {
	ResolvableType resourceRegion = ResolvableType.forClass(ResourceRegion.class);
	MimeType allMimeType = MimeType.valueOf("*/*");

	assertFalse(this.encoder.canEncode(ResolvableType.forClass(Resource.class),
			MimeTypeUtils.APPLICATION_OCTET_STREAM));
	assertFalse(this.encoder.canEncode(ResolvableType.forClass(Resource.class), allMimeType));
	assertTrue(this.encoder.canEncode(resourceRegion, MimeTypeUtils.APPLICATION_OCTET_STREAM));
	assertTrue(this.encoder.canEncode(resourceRegion, allMimeType));

	// SPR-15464
	assertFalse(this.encoder.canEncode(ResolvableType.NONE, null));
}
 
Example 10
Source File: Jackson2SmileEncoderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void canNotEncode() {
	assertFalse(this.encoder.canEncode(ResolvableType.forClass(String.class), null));
	assertFalse(this.encoder.canEncode(ResolvableType.forClass(Pojo.class), APPLICATION_XML));

	ResolvableType sseType = ResolvableType.forClass(ServerSentEvent.class);
	assertFalse(this.encoder.canEncode(sseType, SMILE_MIME_TYPE));
}
 
Example 11
Source File: ResourceRegionEncoderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void canEncode() {
	ResolvableType resourceRegion = ResolvableType.forClass(ResourceRegion.class);
	MimeType allMimeType = MimeType.valueOf("*/*");

	assertFalse(this.encoder.canEncode(ResolvableType.forClass(Resource.class),
			MimeTypeUtils.APPLICATION_OCTET_STREAM));
	assertFalse(this.encoder.canEncode(ResolvableType.forClass(Resource.class), allMimeType));
	assertTrue(this.encoder.canEncode(resourceRegion, MimeTypeUtils.APPLICATION_OCTET_STREAM));
	assertTrue(this.encoder.canEncode(resourceRegion, allMimeType));

	// SPR-15464
	assertFalse(this.encoder.canEncode(ResolvableType.NONE, null));
}
 
Example 12
Source File: HttpMessageWriterView.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> Mono<Void> write(T value, @Nullable MediaType contentType, ServerWebExchange exchange) {
	Publisher<T> input = Mono.justOrEmpty(value);
	ResolvableType elementType = ResolvableType.forClass(value.getClass());
	return ((HttpMessageWriter<T>) this.writer).write(
			input, elementType, contentType, exchange.getResponse(),
			Hints.from(Hints.LOG_PREFIX_HINT, exchange.getLogPrefix()));
}
 
Example 13
Source File: RequestProcessor.java    From spring-cloud-function with Apache License 2.0 4 votes vote down vote up
private Publisher<?> body(Object handler, ServerWebExchange exchange) {
	ResolvableType elementType = ResolvableType
			.forClass(this.inspector.getInputType(handler));

	// we effectively delegate type conversion to FunctionCatalog
	elementType = ResolvableType.forClass(String.class);

	ResolvableType actualType = elementType;

	Class<?> resolvedType = elementType.resolve();
	ReactiveAdapter adapter = (resolvedType != null
			? getAdapterRegistry().getAdapter(resolvedType) : null);

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

	MediaType contentType = request.getHeaders().getContentType();
	MediaType mediaType = (contentType != null ? contentType
			: MediaType.APPLICATION_OCTET_STREAM);

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

	MethodParameter bodyParam = new MethodParameter(handlerMethod(handler), 0);
	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)));
				}
				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).doOnNext(v -> {
							if (logger.isDebugEnabled()) {
								logger.debug("received: " + v);
							}
						});
				mono = mono.onErrorResume(
						ex -> Mono.error(handleReadError(bodyParam, ex)));
				if (isBodyRequired) {
					mono = mono.switchIfEmpty(
							Mono.error(() -> handleMissingBody(bodyParam)));
				}
				return (adapter != null ? Mono.just(adapter.fromPublisher(mono))
						: Mono.from(mono));
			}
		}
	}

	return Mono.error(new UnsupportedMediaTypeStatusException(mediaType,
			Arrays.asList(MediaType.APPLICATION_JSON), elementType));
}
 
Example 14
Source File: MultipartBodyBuilder.java    From spring-analysis-note with MIT License 4 votes vote down vote up
public PublisherPartBuilder(HttpHeaders headers, P body, Class<S> elementClass) {
	super(headers, body);
	this.resolvableType = ResolvableType.forClass(elementClass);
}
 
Example 15
Source File: OneOffSpringWebFluxFrameworkExceptionHandlerListenerTest.java    From backstopper with Apache License 2.0 4 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void handleFluxExceptions_handles_UnsupportedMediaTypeStatusException_as_expected(
    boolean includeDetails
) {
    // given
    MediaType actualMediaType = MediaType.TEXT_PLAIN;
    List<MediaType> supportedMediaTypes = Arrays.asList(
        MediaType.APPLICATION_JSON,
        MediaType.IMAGE_JPEG
    );
    ResolvableType javaBodyType = ResolvableType.forClass(Integer.class);
    UnsupportedMediaTypeStatusException ex =
        (includeDetails)
        ? new UnsupportedMediaTypeStatusException(actualMediaType, supportedMediaTypes, javaBodyType)
        : new UnsupportedMediaTypeStatusException("Some reason");

    List<Pair<String, String>> expectedExtraDetailsForLogging = new ArrayList<>();
    ApiExceptionHandlerUtils.DEFAULT_IMPL.addBaseExceptionMessageToExtraDetailsForLogging(
        ex, expectedExtraDetailsForLogging
    );

    String expectedSupportedMediaTypesValueStr =
        (includeDetails)
        ? supportedMediaTypes.stream().map(Object::toString).collect(Collectors.joining(","))
        : "";
    String expectedJavaBodyTypeValueStr =
        (includeDetails)
        ? javaBodyType.toString()
        : "null";

    expectedExtraDetailsForLogging.add(Pair.of("supported_media_types", expectedSupportedMediaTypesValueStr));
    expectedExtraDetailsForLogging.add(Pair.of("java_body_type", expectedJavaBodyTypeValueStr));

    // when
    ApiExceptionHandlerListenerResult result = listener.handleSpringMvcOrWebfluxSpecificFrameworkExceptions(ex);

    // then
    validateResponse(
        result,
        true,
        singleton(testProjectApiErrors.getUnsupportedMediaTypeApiError()),
        expectedExtraDetailsForLogging
    );
}
 
Example 16
Source File: MultipartBodyBuilder.java    From java-technology-stack with MIT License 4 votes vote down vote up
public PublisherPartBuilder(HttpHeaders headers, P body, Class<S> elementClass) {
	super(headers, body);
	this.resolvableType = ResolvableType.forClass(elementClass);
}
 
Example 17
Source File: ViewResolutionResultHandler.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) {
	Mono<Object> valueMono;
	ResolvableType valueType;
	ReactiveAdapter adapter = getAdapter(result);

	if (adapter != null) {
		if (adapter.isMultiValue()) {
			throw new IllegalArgumentException(
					"Multi-value reactive types not supported in view resolution: " + result.getReturnType());
		}

		valueMono = (result.getReturnValue() != null ?
				Mono.from(adapter.toPublisher(result.getReturnValue())) : Mono.empty());

		valueType = (adapter.isNoValue() ? ResolvableType.forClass(Void.class) :
				result.getReturnType().getGeneric());
	}
	else {
		valueMono = Mono.justOrEmpty(result.getReturnValue());
		valueType = result.getReturnType();
	}

	return valueMono
			.switchIfEmpty(exchange.isNotModified() ? Mono.empty() : NO_VALUE_MONO)
			.flatMap(returnValue -> {

				Mono<List<View>> viewsMono;
				Model model = result.getModel();
				MethodParameter parameter = result.getReturnTypeSource();
				Locale locale = LocaleContextHolder.getLocale(exchange.getLocaleContext());

				Class<?> clazz = valueType.toClass();
				if (clazz == Object.class) {
					clazz = returnValue.getClass();
				}

				if (returnValue == NO_VALUE || clazz == void.class || clazz == Void.class) {
					viewsMono = resolveViews(getDefaultViewName(exchange), locale);
				}
				else if (CharSequence.class.isAssignableFrom(clazz) && !hasModelAnnotation(parameter)) {
					viewsMono = resolveViews(returnValue.toString(), locale);
				}
				else if (Rendering.class.isAssignableFrom(clazz)) {
					Rendering render = (Rendering) returnValue;
					HttpStatus status = render.status();
					if (status != null) {
						exchange.getResponse().setStatusCode(status);
					}
					exchange.getResponse().getHeaders().putAll(render.headers());
					model.addAllAttributes(render.modelAttributes());
					Object view = render.view();
					if (view == null) {
						view = getDefaultViewName(exchange);
					}
					viewsMono = (view instanceof String ? resolveViews((String) view, locale) :
							Mono.just(Collections.singletonList((View) view)));
				}
				else if (Model.class.isAssignableFrom(clazz)) {
					model.addAllAttributes(((Model) returnValue).asMap());
					viewsMono = resolveViews(getDefaultViewName(exchange), locale);
				}
				else if (Map.class.isAssignableFrom(clazz) && !hasModelAnnotation(parameter)) {
					model.addAllAttributes((Map<String, ?>) returnValue);
					viewsMono = resolveViews(getDefaultViewName(exchange), locale);
				}
				else if (View.class.isAssignableFrom(clazz)) {
					viewsMono = Mono.just(Collections.singletonList((View) returnValue));
				}
				else {
					String name = getNameForReturnValue(parameter);
					model.addAttribute(name, returnValue);
					viewsMono = resolveViews(getDefaultViewName(exchange), locale);
				}

				updateBindingContext(result.getBindingContext(), exchange);

				return viewsMono.flatMap(views -> render(views, model.asMap(), exchange));
			});
}
 
Example 18
Source File: TypeDescriptor.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * Create a new type descriptor from the given type.
 * <p>Use this to instruct the conversion system to convert an object to a
 * specific target type, when no type location such as a method parameter or
 * field is available to provide additional conversion context.
 * <p>Generally prefer use of {@link #forObject(Object)} for constructing type
 * descriptors from source objects, as it handles the {@code null} object case.
 * @param type the class (may be {@code null} to indicate {@code Object.class})
 * @return the corresponding type descriptor
 */
public static TypeDescriptor valueOf(@Nullable Class<?> type) {
	if (type == null) {
		type = Object.class;
	}
	TypeDescriptor desc = commonTypesCache.get(type);
	return (desc != null ? desc : new TypeDescriptor(ResolvableType.forClass(type), null, null));
}
 
Example 19
Source File: RootBeanDefinition.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Return a {@link ResolvableType} for this bean definition,
 * either from runtime-cached type information or from configuration-time
 * {@link #setTargetType(ResolvableType)} or {@link #setBeanClass(Class)}.
 * @since 5.1
 * @see #getTargetType()
 * @see #getBeanClass()
 */
public ResolvableType getResolvableType() {
	ResolvableType targetType = this.targetType;
	return (targetType != null ? targetType : ResolvableType.forClass(getBeanClass()));
}
 
Example 20
Source File: NoSuchBeanDefinitionException.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Create a new {@code NoSuchBeanDefinitionException}.
 * @param type required type of the missing bean
 * @param message detailed message describing the problem
 */
public NoSuchBeanDefinitionException(Class<?> type, String message) {
	this(ResolvableType.forClass(type), message);
}