org.springframework.http.codec.HttpMessageReader Java Examples

The following examples show how to use org.springframework.http.codec.HttpMessageReader. 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: DefaultClientResponseTests.java    From spring-analysis-note with MIT License 8 votes vote down vote up
@Test
public void toEntityList() {
	DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
	DefaultDataBuffer dataBuffer =
			factory.wrap(ByteBuffer.wrap("foo".getBytes(StandardCharsets.UTF_8)));
	Flux<DataBuffer> body = Flux.just(dataBuffer);
	mockTextPlainResponse(body);

	List<HttpMessageReader<?>> messageReaders = Collections
			.singletonList(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes()));
	given(mockExchangeStrategies.messageReaders()).willReturn(messageReaders);

	ResponseEntity<List<String>> result = defaultClientResponse.toEntityList(String.class).block();
	assertEquals(Collections.singletonList("foo"), result.getBody());
	assertEquals(HttpStatus.OK, result.getStatusCode());
	assertEquals(HttpStatus.OK.value(), result.getStatusCodeValue());
	assertEquals(MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
}
 
Example #2
Source File: DefaultServerRequest.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private <T> T bodyInternal(BodyExtractor<T, ? super ServerHttpRequest> extractor, Map<String, Object> hints) {
	return extractor.extract(request(),
			new BodyExtractor.Context() {
				@Override
				public List<HttpMessageReader<?>> messageReaders() {
					return messageReaders;
				}
				@Override
				public Optional<ServerHttpResponse> serverResponse() {
					return Optional.of(exchange().getResponse());
				}
				@Override
				public Map<String, Object> hints() {
					return hints;
				}
			});
}
 
Example #3
Source File: BaseDefaultCodecs.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Return Object readers (JSON, XML, SSE).
 */
final List<HttpMessageReader<?>> getObjectReaders() {
	if (!this.registerDefaults) {
		return Collections.emptyList();
	}
	List<HttpMessageReader<?>> readers = new ArrayList<>();
	if (jackson2Present) {
		readers.add(new DecoderHttpMessageReader<>(getJackson2JsonDecoder()));
	}
	if (jackson2SmilePresent) {
		readers.add(new DecoderHttpMessageReader<>(new Jackson2SmileDecoder()));
	}
	if (jaxb2Present) {
		Decoder<?> decoder = this.jaxb2Decoder != null ? this.jaxb2Decoder : new Jaxb2XmlDecoder();
		readers.add(new DecoderHttpMessageReader<>(decoder));
	}
	extendObjectReaders(readers);
	return readers;
}
 
Example #4
Source File: DefaultClientResponseTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void toEntityList() {
	DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
	DefaultDataBuffer dataBuffer =
			factory.wrap(ByteBuffer.wrap("foo".getBytes(StandardCharsets.UTF_8)));
	Flux<DataBuffer> body = Flux.just(dataBuffer);
	mockTextPlainResponse(body);

	List<HttpMessageReader<?>> messageReaders = Collections
			.singletonList(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes()));
	when(mockExchangeStrategies.messageReaders()).thenReturn(messageReaders);

	ResponseEntity<List<String>> result = defaultClientResponse.toEntityList(String.class).block();
	assertEquals(Collections.singletonList("foo"), result.getBody());
	assertEquals(HttpStatus.OK, result.getStatusCode());
	assertEquals(HttpStatus.OK.value(), result.getStatusCodeValue());
	assertEquals(MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
}
 
Example #5
Source File: ServerCodecConfigurerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void defaultReaders() {
	List<HttpMessageReader<?>> readers = this.configurer.getReaders();
	assertEquals(13, readers.size());
	assertEquals(ByteArrayDecoder.class, getNextDecoder(readers).getClass());
	assertEquals(ByteBufferDecoder.class, getNextDecoder(readers).getClass());
	assertEquals(DataBufferDecoder.class, getNextDecoder(readers).getClass());
	assertEquals(ResourceHttpMessageReader.class, readers.get(this.index.getAndIncrement()).getClass());
	assertStringDecoder(getNextDecoder(readers), true);
	assertEquals(ProtobufDecoder.class, getNextDecoder(readers).getClass());
	assertEquals(FormHttpMessageReader.class, readers.get(this.index.getAndIncrement()).getClass());
	assertEquals(DefaultMultipartMessageReader.class, readers.get(this.index.getAndIncrement()).getClass());
	assertEquals(MultipartHttpMessageReader.class, readers.get(this.index.getAndIncrement()).getClass());
	assertEquals(Jackson2JsonDecoder.class, getNextDecoder(readers).getClass());
	assertEquals(Jackson2SmileDecoder.class, getNextDecoder(readers).getClass());
	assertEquals(Jaxb2XmlDecoder.class, getNextDecoder(readers).getClass());
	assertStringDecoder(getNextDecoder(readers), false);
}
 
Example #6
Source File: DefaultClientResponseTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void toEntityTypeReference() {
	DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
	DefaultDataBuffer dataBuffer =
			factory.wrap(ByteBuffer.wrap("foo".getBytes(StandardCharsets.UTF_8)));
	Flux<DataBuffer> body = Flux.just(dataBuffer);
	mockTextPlainResponse(body);

	List<HttpMessageReader<?>> messageReaders = Collections
			.singletonList(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes()));
	when(mockExchangeStrategies.messageReaders()).thenReturn(messageReaders);

	ResponseEntity<String> result = defaultClientResponse.toEntity(
			new ParameterizedTypeReference<String>() {
			}).block();
	assertEquals("foo", result.getBody());
	assertEquals(HttpStatus.OK, result.getStatusCode());
	assertEquals(HttpStatus.OK.value(), result.getStatusCodeValue());
	assertEquals(MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
}
 
Example #7
Source File: BodyExtractors.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private static <T, S extends Publisher<T>> S readWithMessageReaders(
		ReactiveHttpInputMessage message, BodyExtractor.Context context, ResolvableType elementType,
		Function<HttpMessageReader<T>, S> readerFunction,
		Function<UnsupportedMediaTypeException, S> errorFunction,
		Supplier<S> emptySupplier) {

	if (VOID_TYPE.equals(elementType)) {
		return emptySupplier.get();
	}
	MediaType contentType = Optional.ofNullable(message.getHeaders().getContentType())
			.orElse(MediaType.APPLICATION_OCTET_STREAM);

	return context.messageReaders().stream()
			.filter(reader -> reader.canRead(elementType, contentType))
			.findFirst()
			.map(BodyExtractors::<T>cast)
			.map(readerFunction)
			.orElseGet(() -> {
				List<MediaType> mediaTypes = context.messageReaders().stream()
						.flatMap(reader -> reader.getReadableMediaTypes().stream())
						.collect(Collectors.toList());
				return errorFunction.apply(
						new UnsupportedMediaTypeException(contentType, mediaTypes, elementType));
			});
}
 
Example #8
Source File: DefaultClientResponseTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void toEntity() {
	DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
	DefaultDataBuffer dataBuffer =
			factory.wrap(ByteBuffer.wrap("foo".getBytes(StandardCharsets.UTF_8)));
	Flux<DataBuffer> body = Flux.just(dataBuffer);
	mockTextPlainResponse(body);

	List<HttpMessageReader<?>> messageReaders = Collections
			.singletonList(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes()));
	when(mockExchangeStrategies.messageReaders()).thenReturn(messageReaders);

	ResponseEntity<String> result = defaultClientResponse.toEntity(String.class).block();
	assertEquals("foo", result.getBody());
	assertEquals(HttpStatus.OK, result.getStatusCode());
	assertEquals(HttpStatus.OK.value(), result.getStatusCodeValue());
	assertEquals(MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
}
 
Example #9
Source File: DefaultServerWebExchange.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static Mono<MultiValueMap<String, Part>> initMultipartData(ServerHttpRequest request,
		ServerCodecConfigurer configurer, String logPrefix) {

	try {
		MediaType contentType = request.getHeaders().getContentType();
		if (MediaType.MULTIPART_FORM_DATA.isCompatibleWith(contentType)) {
			return ((HttpMessageReader<MultiValueMap<String, Part>>) configurer.getReaders().stream()
					.filter(reader -> reader.canRead(MULTIPART_DATA_TYPE, MediaType.MULTIPART_FORM_DATA))
					.findFirst()
					.orElseThrow(() -> new IllegalStateException("No multipart HttpMessageReader.")))
					.readMono(MULTIPART_DATA_TYPE, request, Hints.from(Hints.LOG_PREFIX_HINT, logPrefix))
					.switchIfEmpty(EMPTY_MULTIPART_DATA)
					.cache();
		}
	}
	catch (InvalidMediaTypeException ex) {
		// Ignore
	}
	return EMPTY_MULTIPART_DATA;
}
 
Example #10
Source File: DefaultClientResponse.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public <T> T body(BodyExtractor<T, ? super ClientHttpResponse> extractor) {
	return extractor.extract(this.response, new BodyExtractor.Context() {
		@Override
		public List<HttpMessageReader<?>> messageReaders() {
			return strategies.messageReaders();
		}
		@Override
		public Optional<ServerHttpResponse> serverResponse() {
			return Optional.empty();
		}
		@Override
		public Map<String, Object> hints() {
			return Hints.from(Hints.LOG_PREFIX_HINT, logPrefix);
		}
	});
}
 
Example #11
Source File: DefaultServerRequestBuilder.java    From java-technology-stack with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static Mono<MultiValueMap<String, String>> initFormData(ServerHttpRequest request,
		List<HttpMessageReader<?>> readers) {

	try {
		MediaType contentType = request.getHeaders().getContentType();
		if (MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(contentType)) {
			return ((HttpMessageReader<MultiValueMap<String, String>>) readers.stream()
					.filter(reader -> reader.canRead(FORM_DATA_TYPE, MediaType.APPLICATION_FORM_URLENCODED))
					.findFirst()
					.orElseThrow(() -> new IllegalStateException("No form data HttpMessageReader.")))
					.readMono(FORM_DATA_TYPE, request, Hints.none())
					.switchIfEmpty(EMPTY_FORM_DATA)
					.cache();
		}
	}
	catch (InvalidMediaTypeException ex) {
		// Ignore
	}
	return EMPTY_FORM_DATA;
}
 
Example #12
Source File: MockServerRequest.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private MockServerRequest(HttpMethod method, URI uri, String contextPath, MockHeaders headers,
		MultiValueMap<String, HttpCookie> cookies, @Nullable Object body,
		Map<String, Object> attributes, MultiValueMap<String, String> queryParams,
		Map<String, String> pathVariables, @Nullable WebSession session, @Nullable Principal principal,
		@Nullable InetSocketAddress remoteAddress, List<HttpMessageReader<?>> messageReaders,
		@Nullable ServerWebExchange exchange) {

	this.method = method;
	this.uri = uri;
	this.pathContainer = RequestPath.parse(uri, contextPath);
	this.headers = headers;
	this.cookies = cookies;
	this.body = body;
	this.attributes = attributes;
	this.queryParams = queryParams;
	this.pathVariables = pathVariables;
	this.session = session;
	this.principal = principal;
	this.remoteAddress = remoteAddress;
	this.messageReaders = messageReaders;
	this.exchange = exchange;
}
 
Example #13
Source File: DefaultServerWebExchange.java    From java-technology-stack with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static Mono<MultiValueMap<String, Part>> initMultipartData(ServerHttpRequest request,
		ServerCodecConfigurer configurer, String logPrefix) {

	try {
		MediaType contentType = request.getHeaders().getContentType();
		if (MediaType.MULTIPART_FORM_DATA.isCompatibleWith(contentType)) {
			return ((HttpMessageReader<MultiValueMap<String, Part>>) configurer.getReaders().stream()
					.filter(reader -> reader.canRead(MULTIPART_DATA_TYPE, MediaType.MULTIPART_FORM_DATA))
					.findFirst()
					.orElseThrow(() -> new IllegalStateException("No multipart HttpMessageReader.")))
					.readMono(MULTIPART_DATA_TYPE, request, Hints.from(Hints.LOG_PREFIX_HINT, logPrefix))
					.switchIfEmpty(EMPTY_MULTIPART_DATA)
					.cache();
		}
	}
	catch (InvalidMediaTypeException ex) {
		// Ignore
	}
	return EMPTY_MULTIPART_DATA;
}
 
Example #14
Source File: DefaultClientResponseTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void toEntityListTypeReference() {
	DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
	DefaultDataBuffer dataBuffer =
			factory.wrap(ByteBuffer.wrap("foo".getBytes(StandardCharsets.UTF_8)));
	Flux<DataBuffer> body = Flux.just(dataBuffer);

	mockTextPlainResponse(body);

	List<HttpMessageReader<?>> messageReaders = Collections
			.singletonList(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes()));
	given(mockExchangeStrategies.messageReaders()).willReturn(messageReaders);

	ResponseEntity<List<String>> result = defaultClientResponse.toEntityList(
			new ParameterizedTypeReference<String>() {
			}).block();
	assertEquals(Collections.singletonList("foo"), result.getBody());
	assertEquals(HttpStatus.OK, result.getStatusCode());
	assertEquals(HttpStatus.OK.value(), result.getStatusCodeValue());
	assertEquals(MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
}
 
Example #15
Source File: DefaultClientResponseTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void bodyToMonoTypeReference() {
	DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
	DefaultDataBuffer dataBuffer =
			factory.wrap(ByteBuffer.wrap("foo".getBytes(StandardCharsets.UTF_8)));
	Flux<DataBuffer> body = Flux.just(dataBuffer);
	mockTextPlainResponse(body);

	List<HttpMessageReader<?>> messageReaders = Collections
			.singletonList(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes()));
	given(mockExchangeStrategies.messageReaders()).willReturn(messageReaders);

	Mono<String> resultMono =
			defaultClientResponse.bodyToMono(new ParameterizedTypeReference<String>() {
			});
	assertEquals("foo", resultMono.block());
}
 
Example #16
Source File: DefaultClientResponseTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void bodyToFluxTypeReference() {
	DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
	DefaultDataBuffer dataBuffer =
			factory.wrap(ByteBuffer.wrap("foo".getBytes(StandardCharsets.UTF_8)));
	Flux<DataBuffer> body = Flux.just(dataBuffer);
	mockTextPlainResponse(body);

	List<HttpMessageReader<?>> messageReaders = Collections
			.singletonList(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes()));
	given(mockExchangeStrategies.messageReaders()).willReturn(messageReaders);

	Flux<String> resultFlux =
			defaultClientResponse.bodyToFlux(new ParameterizedTypeReference<String>() {
			});
	Mono<List<String>> result = resultFlux.collectList();
	assertEquals(Collections.singletonList("foo"), result.block());
}
 
Example #17
Source File: DefaultClientResponseTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void toEntity() {
	DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
	DefaultDataBuffer dataBuffer =
			factory.wrap(ByteBuffer.wrap("foo".getBytes(StandardCharsets.UTF_8)));
	Flux<DataBuffer> body = Flux.just(dataBuffer);
	mockTextPlainResponse(body);

	List<HttpMessageReader<?>> messageReaders = Collections
			.singletonList(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes()));
	given(mockExchangeStrategies.messageReaders()).willReturn(messageReaders);

	ResponseEntity<String> result = defaultClientResponse.toEntity(String.class).block();
	assertEquals("foo", result.getBody());
	assertEquals(HttpStatus.OK, result.getStatusCode());
	assertEquals(HttpStatus.OK.value(), result.getStatusCodeValue());
	assertEquals(MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
}
 
Example #18
Source File: DefaultClientResponseTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void toEntityTypeReference() {
	DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
	DefaultDataBuffer dataBuffer =
			factory.wrap(ByteBuffer.wrap("foo".getBytes(StandardCharsets.UTF_8)));
	Flux<DataBuffer> body = Flux.just(dataBuffer);
	mockTextPlainResponse(body);

	List<HttpMessageReader<?>> messageReaders = Collections
			.singletonList(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes()));
	given(mockExchangeStrategies.messageReaders()).willReturn(messageReaders);

	ResponseEntity<String> result = defaultClientResponse.toEntity(
			new ParameterizedTypeReference<String>() {
			}).block();
	assertEquals("foo", result.getBody());
	assertEquals(HttpStatus.OK, result.getStatusCode());
	assertEquals(HttpStatus.OK.value(), result.getStatusCodeValue());
	assertEquals(MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
}
 
Example #19
Source File: MessageReaderArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@SuppressWarnings("Convert2MethodRef")
private AbstractMessageReaderArgumentResolver resolver(Decoder<?>... decoders) {
	List<HttpMessageReader<?>> readers = new ArrayList<>();
	Arrays.asList(decoders).forEach(decoder -> readers.add(new DecoderHttpMessageReader<>(decoder)));
	return new AbstractMessageReaderArgumentResolver(readers) {
		@Override
		public boolean supportsParameter(MethodParameter parameter) {
			return false;
		}
		@Override
		public Mono<Object> resolveArgument(MethodParameter p, BindingContext bc, ServerWebExchange e) {
			return null;
		}
	};
}
 
Example #20
Source File: BodyExtractors.java    From java-technology-stack with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T> BodyExtractor<Flux<T>, ReactiveHttpInputMessage> toFlux(ResolvableType elementType) {
	return (inputMessage, context) ->
			readWithMessageReaders(inputMessage, context, elementType,
					(HttpMessageReader<T> reader) -> readToFlux(inputMessage, context, elementType, reader),
					ex -> unsupportedErrorHandler(inputMessage, ex),
					skipBodyAsFlux(inputMessage));
}
 
Example #21
Source File: DefaultClientResponseTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void toEntityWithUnknownStatusCode() throws Exception {
	DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
	DefaultDataBuffer dataBuffer
			= factory.wrap(ByteBuffer.wrap("foo".getBytes(StandardCharsets.UTF_8)));
	Flux<DataBuffer> body = Flux.just(dataBuffer);

	HttpHeaders httpHeaders = new HttpHeaders();
	httpHeaders.setContentType(MediaType.TEXT_PLAIN);
	given(mockResponse.getHeaders()).willReturn(httpHeaders);
	given(mockResponse.getStatusCode()).willThrow(new IllegalArgumentException("999"));
	given(mockResponse.getRawStatusCode()).willReturn(999);
	given(mockResponse.getBody()).willReturn(body);

	List<HttpMessageReader<?>> messageReaders = Collections
			.singletonList(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes()));
	given(mockExchangeStrategies.messageReaders()).willReturn(messageReaders);

	ResponseEntity<String> result = defaultClientResponse.toEntity(String.class).block();
	assertEquals("foo", result.getBody());
	try {
		result.getStatusCode();
		fail("Expected IllegalArgumentException");
	}
	catch (IllegalArgumentException ex) {
		// do nothing
	}
	assertEquals(999, result.getStatusCodeValue());
	assertEquals(MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
}
 
Example #22
Source File: ServerDefaultCodecsImpl.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected void extendTypedReaders(List<HttpMessageReader<?>> typedReaders) {
	if (synchronossMultipartPresent) {
		boolean enable = isEnableLoggingRequestDetails();

		SynchronossPartHttpMessageReader partReader = new SynchronossPartHttpMessageReader();
		partReader.setEnableLoggingRequestDetails(enable);
		typedReaders.add(partReader);

		MultipartHttpMessageReader reader = new MultipartHttpMessageReader(partReader);
		reader.setEnableLoggingRequestDetails(enable);
		typedReaders.add(reader);
	}
}
 
Example #23
Source File: ModifyResponseBodyGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
public ModifyResponseBodyGatewayFilterFactory(
		List<HttpMessageReader<?>> messageReaders,
		Set<MessageBodyDecoder> messageBodyDecoders,
		Set<MessageBodyEncoder> messageBodyEncoders) {
	super(Config.class);
	this.messageReaders = messageReaders;
	this.messageBodyDecoders = messageBodyDecoders.stream()
			.collect(Collectors.toMap(MessageBodyDecoder::encodingType, identity()));
	this.messageBodyEncoders = messageBodyEncoders.stream()
			.collect(Collectors.toMap(MessageBodyEncoder::encodingType, identity()));
}
 
Example #24
Source File: ServerDefaultCodecsImpl.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected void extendTypedReaders(List<HttpMessageReader<?>> typedReaders) {

	HttpMessageReader<Part> partReader = getMultipartReader();

	boolean logRequestDetails = isEnableLoggingRequestDetails();
	if (partReader instanceof LoggingCodecSupport) {
		((LoggingCodecSupport) partReader).setEnableLoggingRequestDetails(logRequestDetails);
	}
	typedReaders.add(partReader);

	MultipartHttpMessageReader reader = new MultipartHttpMessageReader(partReader);
	reader.setEnableLoggingRequestDetails(logRequestDetails);
	typedReaders.add(reader);
}
 
Example #25
Source File: ClientResponse.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Create a response builder with the given status code and message body readers.
 * @param statusCode the status code
 * @param messageReaders the message readers
 * @return the created builder
 */
static Builder create(HttpStatus statusCode, List<HttpMessageReader<?>> messageReaders) {
	return create(statusCode, new ExchangeStrategies() {
		@Override
		public List<HttpMessageReader<?>> messageReaders() {
			return messageReaders;
		}
		@Override
		public List<HttpMessageWriter<?>> messageWriters() {
			// not used in the response
			return Collections.emptyList();
		}
	});
}
 
Example #26
Source File: SpringWebfluxApiExceptionHandlerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Before
public void beforeMethod() {
    projectApiErrorsMock = mock(ProjectApiErrors.class);
    listenerList = new SpringWebFluxApiExceptionHandlerListenerList(
        Arrays.asList(mock(ApiExceptionHandlerListener.class), mock(ApiExceptionHandlerListener.class))
    );
    generalUtils = ApiExceptionHandlerUtils.DEFAULT_IMPL;
    springUtilsMock = mock(SpringWebfluxApiExceptionHandlerUtils.class);
    viewResolversProviderMock = mock(ObjectProvider.class);
    serverCodecConfigurerMock = mock(ServerCodecConfigurer.class);
    messageReaders = Arrays.asList(mock(HttpMessageReader.class), mock(HttpMessageReader.class));
    messageWriters = Arrays.asList(mock(HttpMessageWriter.class), mock(HttpMessageWriter.class));
    viewResolvers = Arrays.asList(mock(ViewResolver.class), mock(ViewResolver.class));
    serverWebExchangeMock = mock(ServerWebExchange.class);
    serverHttpRequestMock = mock(ServerHttpRequest.class);
    serverHttpResponseMock = mock(ServerHttpResponse.class);
    serverHttpResponseHeadersMock = mock(HttpHeaders.class);
    uri = URI.create("http://localhost:8080/foo/bar?someQuery=someValue");
    exMock = mock(Throwable.class);

    doAnswer(invocation -> viewResolvers.stream()).when(viewResolversProviderMock).orderedStream();
    doReturn(messageReaders).when(serverCodecConfigurerMock).getReaders();
    doReturn(messageWriters).when(serverCodecConfigurerMock).getWriters();

    doReturn(serverHttpRequestMock).when(serverWebExchangeMock).getRequest();
    doReturn(uri).when(serverHttpRequestMock).getURI();

    doReturn(serverHttpResponseMock).when(serverWebExchangeMock).getResponse();
    doReturn(serverHttpResponseHeadersMock).when(serverHttpResponseMock).getHeaders();

    handlerSpy = spy(new SpringWebfluxApiExceptionHandler(
        projectApiErrorsMock, listenerList, generalUtils, springUtilsMock, viewResolversProviderMock,
        serverCodecConfigurerMock
    ));
}
 
Example #27
Source File: WebFluxConfigurationSupportTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void requestMappingHandlerAdapter() throws Exception {
	ApplicationContext context = loadConfig(WebFluxConfig.class);

	String name = "requestMappingHandlerAdapter";
	RequestMappingHandlerAdapter adapter = context.getBean(name, RequestMappingHandlerAdapter.class);
	assertNotNull(adapter);

	List<HttpMessageReader<?>> readers = adapter.getMessageReaders();
	assertEquals(13, readers.size());

	ResolvableType multiValueMapType = forClassWithGenerics(MultiValueMap.class, String.class, String.class);

	assertHasMessageReader(readers, forClass(byte[].class), APPLICATION_OCTET_STREAM);
	assertHasMessageReader(readers, forClass(ByteBuffer.class), APPLICATION_OCTET_STREAM);
	assertHasMessageReader(readers, forClass(String.class), TEXT_PLAIN);
	assertHasMessageReader(readers, forClass(Resource.class), IMAGE_PNG);
	assertHasMessageReader(readers, forClass(Message.class), new MediaType("application", "x-protobuf"));
	assertHasMessageReader(readers, multiValueMapType, APPLICATION_FORM_URLENCODED);
	assertHasMessageReader(readers, forClass(TestBean.class), APPLICATION_XML);
	assertHasMessageReader(readers, forClass(TestBean.class), APPLICATION_JSON);
	assertHasMessageReader(readers, forClass(TestBean.class), new MediaType("application", "x-jackson-smile"));
	assertHasMessageReader(readers, forClass(TestBean.class), null);

	WebBindingInitializer bindingInitializer = adapter.getWebBindingInitializer();
	assertNotNull(bindingInitializer);
	WebExchangeDataBinder binder = new WebExchangeDataBinder(new Object());
	bindingInitializer.initBinder(binder);

	name = "webFluxConversionService";
	ConversionService service = context.getBean(name, ConversionService.class);
	assertSame(service, binder.getConversionService());

	name = "webFluxValidator";
	Validator validator = context.getBean(name, Validator.class);
	assertSame(validator, binder.getValidator());
}
 
Example #28
Source File: ClientCodecConfigurerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void assertSseReader(List<HttpMessageReader<?>> readers) {
	HttpMessageReader<?> reader = readers.get(this.index.getAndIncrement());
	assertEquals(ServerSentEventHttpMessageReader.class, reader.getClass());
	Decoder<?> decoder = ((ServerSentEventHttpMessageReader) reader).getDecoder();
	assertNotNull(decoder);
	assertEquals(Jackson2JsonDecoder.class, decoder.getClass());
}
 
Example #29
Source File: BaseDefaultCodecs.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Return readers that need to be at the end, after all others.
 */
final List<HttpMessageReader<?>> getCatchAllReaders() {
	if (!this.registerDefaults) {
		return Collections.emptyList();
	}
	List<HttpMessageReader<?>> result = new ArrayList<>();
	result.add(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes()));
	return result;
}
 
Example #30
Source File: AbstractMessageReaderArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Constructor that also accepts a {@link ReactiveAdapterRegistry}.
 * @param messageReaders readers to convert from the request body
 * @param adapterRegistry for adapting to other reactive types from Flux and Mono
 */
protected AbstractMessageReaderArgumentResolver(
		List<HttpMessageReader<?>> messageReaders, ReactiveAdapterRegistry adapterRegistry) {

	super(adapterRegistry);
	Assert.notEmpty(messageReaders, "At least one HttpMessageReader is required");
	Assert.notNull(adapterRegistry, "ReactiveAdapterRegistry is required");
	this.messageReaders = messageReaders;
	this.supportedMediaTypes = messageReaders.stream()
			.flatMap(converter -> converter.getReadableMediaTypes().stream())
			.collect(Collectors.toList());
}