org.springframework.http.codec.HttpMessageWriter Java Examples

The following examples show how to use org.springframework.http.codec.HttpMessageWriter. 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: ClientCodecConfigurerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void defaultWriters() {
	List<HttpMessageWriter<?>> writers = this.configurer.getWriters();
	assertEquals(11, writers.size());
	assertEquals(ByteArrayEncoder.class, getNextEncoder(writers).getClass());
	assertEquals(ByteBufferEncoder.class, getNextEncoder(writers).getClass());
	assertEquals(DataBufferEncoder.class, getNextEncoder(writers).getClass());
	assertEquals(ResourceHttpMessageWriter.class, writers.get(index.getAndIncrement()).getClass());
	assertStringEncoder(getNextEncoder(writers), true);
	assertEquals(MultipartHttpMessageWriter.class, writers.get(this.index.getAndIncrement()).getClass());
	assertEquals(ProtobufHttpMessageWriter.class, writers.get(index.getAndIncrement()).getClass());
	assertEquals(Jackson2JsonEncoder.class, getNextEncoder(writers).getClass());
	assertEquals(Jackson2SmileEncoder.class, getNextEncoder(writers).getClass());
	assertEquals(Jaxb2XmlEncoder.class, getNextEncoder(writers).getClass());
	assertStringEncoder(getNextEncoder(writers), false);
}
 
Example #2
Source File: DefaultClientRequestBuilderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void bodyParameterizedTypeReference() {
	String body = "foo";
	Publisher<String> publisher = Mono.just(body);
	ParameterizedTypeReference<String> typeReference = new ParameterizedTypeReference<String>() {};
	ClientRequest result = ClientRequest.create(POST, URI.create("http://example.com"))
			.body(publisher, typeReference).build();

	List<HttpMessageWriter<?>> messageWriters = new ArrayList<>();
	messageWriters.add(new EncoderHttpMessageWriter<>(CharSequenceEncoder.allMimeTypes()));

	ExchangeStrategies strategies = mock(ExchangeStrategies.class);
	when(strategies.messageWriters()).thenReturn(messageWriters);

	MockClientHttpRequest request = new MockClientHttpRequest(GET, "/");
	result.writeTo(request, strategies).block();
	assertNotNull(request.getBody());

	StepVerifier.create(request.getBody())
			.expectNextCount(1)
			.verifyComplete();
}
 
Example #3
Source File: ServerCodecConfigurerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void defaultWriters() {
	List<HttpMessageWriter<?>> writers = this.configurer.getWriters();
	assertEquals(11, writers.size());
	assertEquals(ByteArrayEncoder.class, getNextEncoder(writers).getClass());
	assertEquals(ByteBufferEncoder.class, getNextEncoder(writers).getClass());
	assertEquals(DataBufferEncoder.class, getNextEncoder(writers).getClass());
	assertEquals(ResourceHttpMessageWriter.class, writers.get(index.getAndIncrement()).getClass());
	assertStringEncoder(getNextEncoder(writers), true);
	assertEquals(ProtobufHttpMessageWriter.class, writers.get(index.getAndIncrement()).getClass());
	assertEquals(Jackson2JsonEncoder.class, getNextEncoder(writers).getClass());
	assertEquals(Jackson2SmileEncoder.class, getNextEncoder(writers).getClass());
	assertEquals(Jaxb2XmlEncoder.class, getNextEncoder(writers).getClass());
	assertSseWriter(writers);
	assertStringEncoder(getNextEncoder(writers), false);
}
 
Example #4
Source File: BaseDefaultCodecs.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Return Object writers (JSON, XML, SSE).
 * @param forMultipart whether to returns writers for general use ("false"),
 * or for multipart requests only ("true"). Generally the two sets are the
 * same except for the multipart writer itself.
 */
final List<HttpMessageWriter<?>> getObjectWriters(boolean forMultipart) {
	if (!this.registerDefaults) {
		return Collections.emptyList();
	}
	List<HttpMessageWriter<?>> writers = new ArrayList<>();
	if (jackson2Present) {
		writers.add(new EncoderHttpMessageWriter<>(getJackson2JsonEncoder()));
	}
	if (jackson2SmilePresent) {
		writers.add(new EncoderHttpMessageWriter<>(new Jackson2SmileEncoder()));
	}
	if (jaxb2Present) {
		Encoder<?> encoder = this.jaxb2Encoder != null ? this.jaxb2Encoder : new Jaxb2XmlEncoder();
		writers.add(new EncoderHttpMessageWriter<>(encoder));
	}
	// No client or server specific multipart writers currently..
	if (!forMultipart) {
		extendObjectWriters(writers);
	}
	return writers;
}
 
Example #5
Source File: BaseDefaultCodecs.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Return writers that support specific types.
 * @param forMultipart whether to returns writers for general use ("false"),
 * or for multipart requests only ("true"). Generally the two sets are the
 * same except for the multipart writer itself.
 */
@SuppressWarnings("unchecked")
final List<HttpMessageWriter<?>> getTypedWriters(boolean forMultipart) {
	if (!this.registerDefaults) {
		return Collections.emptyList();
	}
	List<HttpMessageWriter<?>> writers = new ArrayList<>();
	writers.add(new EncoderHttpMessageWriter<>(new ByteArrayEncoder()));
	writers.add(new EncoderHttpMessageWriter<>(new ByteBufferEncoder()));
	writers.add(new EncoderHttpMessageWriter<>(new DataBufferEncoder()));
	writers.add(new ResourceHttpMessageWriter());
	writers.add(new EncoderHttpMessageWriter<>(CharSequenceEncoder.textPlainOnly()));
	// No client or server specific multipart writers currently..
	if (!forMultipart) {
		extendTypedWriters(writers);
	}
	if (protobufPresent) {
		Encoder<?> encoder = this.protobufEncoder != null ? this.protobufEncoder : new ProtobufEncoder();
		writers.add(new ProtobufHttpMessageWriter((Encoder) encoder));
	}
	return writers;
}
 
Example #6
Source File: DefaultServerResponseBuilder.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected Mono<Void> writeToInternal(ServerWebExchange exchange, Context context) {
	return this.inserter.insert(exchange.getResponse(), new BodyInserter.Context() {
		@Override
		public List<HttpMessageWriter<?>> messageWriters() {
			return context.messageWriters();
		}
		@Override
		public Optional<ServerHttpRequest> serverRequest() {
			return Optional.of(exchange.getRequest());
		}
		@Override
		public Map<String, Object> hints() {
			hints.put(Hints.LOG_PREFIX_HINT, exchange.getLogPrefix());
			return hints;
		}
	});
}
 
Example #7
Source File: DefaultClientRequestBuilderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void bodyClass() {
	String body = "foo";
	Publisher<String> publisher = Mono.just(body);
	ClientRequest result = ClientRequest.create(POST, URI.create("http://example.com"))
			.body(publisher, String.class).build();

	List<HttpMessageWriter<?>> messageWriters = new ArrayList<>();
	messageWriters.add(new EncoderHttpMessageWriter<>(CharSequenceEncoder.allMimeTypes()));

	ExchangeStrategies strategies = mock(ExchangeStrategies.class);
	when(strategies.messageWriters()).thenReturn(messageWriters);

	MockClientHttpRequest request = new MockClientHttpRequest(GET, "/");
	result.writeTo(request, strategies).block();
	assertNotNull(request.getBody());

	StepVerifier.create(request.getBody())
			.expectNextCount(1)
			.verifyComplete();
}
 
Example #8
Source File: MessageWriterResultHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
private AbstractMessageWriterResultHandler initResultHandler(HttpMessageWriter<?>... writers) {
	List<HttpMessageWriter<?>> writerList;
	if (ObjectUtils.isEmpty(writers)) {
		writerList = new ArrayList<>();
		writerList.add(new EncoderHttpMessageWriter<>(new ByteBufferEncoder()));
		writerList.add(new EncoderHttpMessageWriter<>(CharSequenceEncoder.allMimeTypes()));
		writerList.add(new ResourceHttpMessageWriter());
		writerList.add(new EncoderHttpMessageWriter<>(new Jaxb2XmlEncoder()));
		writerList.add(new EncoderHttpMessageWriter<>(new Jackson2JsonEncoder()));
	}
	else {
		writerList = Arrays.asList(writers);
	}
	RequestedContentTypeResolver resolver = new RequestedContentTypeResolverBuilder().build();
	return new AbstractMessageWriterResultHandler(writerList, resolver) {};
}
 
Example #9
Source File: DefaultEntityResponseBuilder.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected Mono<Void> writeToInternal(ServerWebExchange exchange, Context context) {
	return inserter().insert(exchange.getResponse(), new BodyInserter.Context() {
		@Override
		public List<HttpMessageWriter<?>> messageWriters() {
			return context.messageWriters();
		}
		@Override
		public Optional<ServerHttpRequest> serverRequest() {
			return Optional.of(exchange.getRequest());
		}
		@Override
		public Map<String, Object> hints() {
			hints.put(Hints.LOG_PREFIX_HINT, exchange.getLogPrefix());
			return hints;
		}
	});
}
 
Example #10
Source File: MessageWriterResultHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private AbstractMessageWriterResultHandler initResultHandler(HttpMessageWriter<?>... writers) {
	List<HttpMessageWriter<?>> writerList;
	if (ObjectUtils.isEmpty(writers)) {
		writerList = new ArrayList<>();
		writerList.add(new EncoderHttpMessageWriter<>(new ByteBufferEncoder()));
		writerList.add(new EncoderHttpMessageWriter<>(CharSequenceEncoder.allMimeTypes()));
		writerList.add(new ResourceHttpMessageWriter());
		writerList.add(new EncoderHttpMessageWriter<>(new Jaxb2XmlEncoder()));
		writerList.add(new EncoderHttpMessageWriter<>(new Jackson2JsonEncoder()));
	}
	else {
		writerList = Arrays.asList(writers);
	}
	RequestedContentTypeResolver resolver = new RequestedContentTypeResolverBuilder().build();
	return new AbstractMessageWriterResultHandler(writerList, resolver) {};
}
 
Example #11
Source File: CodecConfigurerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void defaultsOffWithCustomWriters() {
	Encoder<?> customEncoder1 = mock(Encoder.class);
	Encoder<?> customEncoder2 = mock(Encoder.class);

	given(customEncoder1.canEncode(ResolvableType.forClass(Object.class), null)).willReturn(false);
	given(customEncoder2.canEncode(ResolvableType.forClass(Object.class), null)).willReturn(true);

	HttpMessageWriter<?> customWriter1 = mock(HttpMessageWriter.class);
	HttpMessageWriter<?> customWriter2 = mock(HttpMessageWriter.class);

	given(customWriter1.canWrite(ResolvableType.forClass(Object.class), null)).willReturn(false);
	given(customWriter2.canWrite(ResolvableType.forClass(Object.class), null)).willReturn(true);

	this.configurer.customCodecs().encoder(customEncoder1);
	this.configurer.customCodecs().encoder(customEncoder2);

	this.configurer.customCodecs().writer(customWriter1);
	this.configurer.customCodecs().writer(customWriter2);

	this.configurer.registerDefaults(false);

	List<HttpMessageWriter<?>> writers = this.configurer.getWriters();

	assertEquals(4, writers.size());
	assertSame(customEncoder1, getNextEncoder(writers));
	assertSame(customWriter1, writers.get(this.index.getAndIncrement()));
	assertSame(customEncoder2, getNextEncoder(writers));
	assertSame(customWriter2, writers.get(this.index.getAndIncrement()));
}
 
Example #12
Source File: DefaultEntityResponseBuilderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void bodyInserter() {
	String body = "foo";
	Publisher<String> publisher = Mono.just(body);

	Mono<EntityResponse<Publisher<String>>> result = EntityResponse.fromPublisher(publisher, String.class).build();

	MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("http://localhost"));

	ServerResponse.Context context = new ServerResponse.Context() {
		@Override
		public List<HttpMessageWriter<?>> messageWriters() {
			return Collections.singletonList(new EncoderHttpMessageWriter<>(CharSequenceEncoder.allMimeTypes()));
		}

		@Override
		public List<ViewResolver> viewResolvers() {
			return Collections.emptyList();
		}
	};
	StepVerifier.create(result)
			.consumeNextWith(response -> {
				StepVerifier.create(response.entity())
						.expectNext(body)
						.expectComplete()
						.verify();
				response.writeTo(exchange, context);
			})
			.expectComplete()
			.verify();

	assertNotNull(exchange.getResponse().getBody());
}
 
Example #13
Source File: SpringWebfluxUnhandledExceptionHandlerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Before
public void beforeMethod() {
    generalUtils = ApiExceptionHandlerUtils.DEFAULT_IMPL;
    testProjectApiErrors = ProjectApiErrorsForTesting.withProjectSpecificData(null, null);
    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 SpringWebfluxUnhandledExceptionHandler(
        testProjectApiErrors, generalUtils, springUtilsMock, viewResolversProviderMock, serverCodecConfigurerMock
    ));
}
 
Example #14
Source File: ServerCodecConfigurerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void assertSseWriter(List<HttpMessageWriter<?>> writers) {
	HttpMessageWriter<?> writer = writers.get(this.index.getAndIncrement());
	assertEquals(ServerSentEventHttpMessageWriter.class, writer.getClass());
	Encoder<?> encoder = ((ServerSentEventHttpMessageWriter) writer).getEncoder();
	assertNotNull(encoder);
	assertEquals(Jackson2JsonEncoder.class, encoder.getClass());
}
 
Example #15
Source File: RequestPartMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before
public void setup() throws Exception {
	List<HttpMessageReader<?>> readers = ServerCodecConfigurer.create().getReaders();
	ReactiveAdapterRegistry registry = ReactiveAdapterRegistry.getSharedInstance();
	this.resolver = new RequestPartMethodArgumentResolver(readers, registry);

	List<HttpMessageWriter<?>> writers = ClientCodecConfigurer.create().getWriters();
	this.writer = new MultipartHttpMessageWriter(writers);
}
 
Example #16
Source File: SpringWebfluxApiExceptionHandler.java    From backstopper with Apache License 2.0 5 votes vote down vote up
protected ResponseContext(
    List<HttpMessageWriter<?>> messageWriters,
    List<ViewResolver> viewResolvers
) {
    this.messageWriters = messageWriters;
    this.viewResolvers = viewResolvers;
}
 
Example #17
Source File: BodyInsertersTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before
public void createContext() {
	final List<HttpMessageWriter<?>> messageWriters = new ArrayList<>();
	messageWriters.add(new EncoderHttpMessageWriter<>(new ByteBufferEncoder()));
	messageWriters.add(new EncoderHttpMessageWriter<>(CharSequenceEncoder.textPlainOnly()));
	messageWriters.add(new ResourceHttpMessageWriter());
	messageWriters.add(new EncoderHttpMessageWriter<>(new Jaxb2XmlEncoder()));
	Jackson2JsonEncoder jsonEncoder = new Jackson2JsonEncoder();
	messageWriters.add(new EncoderHttpMessageWriter<>(jsonEncoder));
	messageWriters.add(new ServerSentEventHttpMessageWriter(jsonEncoder));
	messageWriters.add(new FormHttpMessageWriter());
	messageWriters.add(new EncoderHttpMessageWriter<>(CharSequenceEncoder.allMimeTypes()));
	messageWriters.add(new MultipartHttpMessageWriter(messageWriters));

	this.context = new BodyInserter.Context() {
		@Override
		public List<HttpMessageWriter<?>> messageWriters() {
			return messageWriters;
		}
		@Override
		public Optional<ServerHttpRequest> serverRequest() {
			return Optional.empty();
		}
		@Override
		public Map<String, Object> hints() {
			return hints;
		}
	};
	this.hints = new HashMap<>();
}
 
Example #18
Source File: WebFluxConfigurationSupportTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void responseEntityResultHandler() throws Exception {
	ApplicationContext context = loadConfig(WebFluxConfig.class);

	String name = "responseEntityResultHandler";
	ResponseEntityResultHandler handler = context.getBean(name, ResponseEntityResultHandler.class);
	assertNotNull(handler);

	assertEquals(0, handler.getOrder());

	List<HttpMessageWriter<?>> writers = handler.getMessageWriters();
	assertEquals(11, writers.size());

	assertHasMessageWriter(writers, forClass(byte[].class), APPLICATION_OCTET_STREAM);
	assertHasMessageWriter(writers, forClass(ByteBuffer.class), APPLICATION_OCTET_STREAM);
	assertHasMessageWriter(writers, forClass(String.class), TEXT_PLAIN);
	assertHasMessageWriter(writers, forClass(Resource.class), IMAGE_PNG);
	assertHasMessageWriter(writers, forClass(Message.class), new MediaType("application", "x-protobuf"));
	assertHasMessageWriter(writers, forClass(TestBean.class), APPLICATION_XML);
	assertHasMessageWriter(writers, forClass(TestBean.class), APPLICATION_JSON);
	assertHasMessageWriter(writers, forClass(TestBean.class), new MediaType("application", "x-jackson-smile"));
	assertHasMessageWriter(writers, forClass(TestBean.class), MediaType.parseMediaType("text/event-stream"));

	name = "webFluxContentTypeResolver";
	RequestedContentTypeResolver resolver = context.getBean(name, RequestedContentTypeResolver.class);
	assertSame(resolver, handler.getContentTypeResolver());
}
 
Example #19
Source File: ServerResponseResultHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) {
	ServerResponse response = (ServerResponse) result.getReturnValue();
	Assert.state(response != null, "No ServerResponse");
	return response.writeTo(exchange, new ServerResponse.Context() {
		@Override
		public List<HttpMessageWriter<?>> messageWriters() {
			return messageWriters;
		}
		@Override
		public List<ViewResolver> viewResolvers() {
			return viewResolvers;
		}
	});
}
 
Example #20
Source File: ClientDefaultCodecsImpl.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected void extendTypedWriters(List<HttpMessageWriter<?>> typedWriters) {

	FormHttpMessageWriter formWriter = new FormHttpMessageWriter();
	formWriter.setEnableLoggingRequestDetails(isEnableLoggingRequestDetails());

	MultipartHttpMessageWriter multipartWriter = new MultipartHttpMessageWriter(getPartWriters(), formWriter);
	multipartWriter.setEnableLoggingRequestDetails(isEnableLoggingRequestDetails());

	typedWriters.add(multipartWriter);
}
 
Example #21
Source File: CodecConfigurerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void defaultAndCustomWriters() {
	Encoder<?> customEncoder1 = mock(Encoder.class);
	Encoder<?> customEncoder2 = mock(Encoder.class);

	when(customEncoder1.canEncode(ResolvableType.forClass(Object.class), null)).thenReturn(false);
	when(customEncoder2.canEncode(ResolvableType.forClass(Object.class), null)).thenReturn(true);

	HttpMessageWriter<?> customWriter1 = mock(HttpMessageWriter.class);
	HttpMessageWriter<?> customWriter2 = mock(HttpMessageWriter.class);

	when(customWriter1.canWrite(ResolvableType.forClass(Object.class), null)).thenReturn(false);
	when(customWriter2.canWrite(ResolvableType.forClass(Object.class), null)).thenReturn(true);

	this.configurer.customCodecs().encoder(customEncoder1);
	this.configurer.customCodecs().encoder(customEncoder2);

	this.configurer.customCodecs().writer(customWriter1);
	this.configurer.customCodecs().writer(customWriter2);

	List<HttpMessageWriter<?>> writers = this.configurer.getWriters();

	assertEquals(14, writers.size());
	assertEquals(ByteArrayEncoder.class, getNextEncoder(writers).getClass());
	assertEquals(ByteBufferEncoder.class, getNextEncoder(writers).getClass());
	assertEquals(DataBufferEncoder.class, getNextEncoder(writers).getClass());
	assertEquals(ResourceHttpMessageWriter.class, writers.get(index.getAndIncrement()).getClass());
	assertEquals(CharSequenceEncoder.class, getNextEncoder(writers).getClass());
	assertEquals(ProtobufHttpMessageWriter.class, writers.get(index.getAndIncrement()).getClass());
	assertSame(customEncoder1, getNextEncoder(writers));
	assertSame(customWriter1, writers.get(this.index.getAndIncrement()));
	assertEquals(Jackson2JsonEncoder.class, getNextEncoder(writers).getClass());
	assertEquals(Jackson2SmileEncoder.class, getNextEncoder(writers).getClass());
	assertEquals(Jaxb2XmlEncoder.class, getNextEncoder(writers).getClass());
	assertSame(customEncoder2, getNextEncoder(writers));
	assertSame(customWriter2, writers.get(this.index.getAndIncrement()));
	assertEquals(CharSequenceEncoder.class, getNextEncoder(writers).getClass());
}
 
Example #22
Source File: WebFluxConfigurationSupportTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void responseBodyResultHandler() throws Exception {
	ApplicationContext context = loadConfig(WebFluxConfig.class);

	String name = "responseBodyResultHandler";
	ResponseBodyResultHandler handler = context.getBean(name, ResponseBodyResultHandler.class);
	assertNotNull(handler);

	assertEquals(100, handler.getOrder());

	List<HttpMessageWriter<?>> writers = handler.getMessageWriters();
	assertEquals(11, writers.size());

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

	name = "webFluxContentTypeResolver";
	RequestedContentTypeResolver resolver = context.getBean(name, RequestedContentTypeResolver.class);
	assertSame(resolver, handler.getContentTypeResolver());
}
 
Example #23
Source File: ClientDefaultCodecsImpl.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private List<HttpMessageWriter<?>> getPartWriters() {
	if (this.multipartCodecs != null) {
		return this.multipartCodecs.getWriters();
	}
	else if (this.partWritersSupplier != null) {
		return this.partWritersSupplier.get();
	}
	else {
		return Collections.emptyList();
	}
}
 
Example #24
Source File: WebFluxConfigurationSupportTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void responseEntityResultHandler() throws Exception {
	ApplicationContext context = loadConfig(WebFluxConfig.class);

	String name = "responseEntityResultHandler";
	ResponseEntityResultHandler handler = context.getBean(name, ResponseEntityResultHandler.class);
	assertNotNull(handler);

	assertEquals(0, handler.getOrder());

	List<HttpMessageWriter<?>> writers = handler.getMessageWriters();
	assertEquals(11, writers.size());

	assertHasMessageWriter(writers, forClass(byte[].class), APPLICATION_OCTET_STREAM);
	assertHasMessageWriter(writers, forClass(ByteBuffer.class), APPLICATION_OCTET_STREAM);
	assertHasMessageWriter(writers, forClass(String.class), TEXT_PLAIN);
	assertHasMessageWriter(writers, forClass(Resource.class), IMAGE_PNG);
	assertHasMessageWriter(writers, forClass(Message.class), new MediaType("application", "x-protobuf"));
	assertHasMessageWriter(writers, forClass(TestBean.class), APPLICATION_XML);
	assertHasMessageWriter(writers, forClass(TestBean.class), APPLICATION_JSON);
	assertHasMessageWriter(writers, forClass(TestBean.class), new MediaType("application", "x-jackson-smile"));
	assertHasMessageWriter(writers, forClass(TestBean.class), MediaType.parseMediaType("text/event-stream"));

	name = "webFluxContentTypeResolver";
	RequestedContentTypeResolver resolver = context.getBean(name, RequestedContentTypeResolver.class);
	assertSame(resolver, handler.getContentTypeResolver());
}
 
Example #25
Source File: HttpMessageWriterView.java    From java-technology-stack 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 #26
Source File: ResourceHandlerFunctionTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before
public void createContext() {
	HandlerStrategies strategies = HandlerStrategies.withDefaults();
	context = new ServerResponse.Context() {
		@Override
		public List<HttpMessageWriter<?>> messageWriters() {
			return strategies.messageWriters();
		}
		@Override
		public List<ViewResolver> viewResolvers() {
			return strategies.viewResolvers();
		}
	};
}
 
Example #27
Source File: AbstractMessageWriterResultHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Constructor with an additional {@link ReactiveAdapterRegistry}.
 * @param messageWriters for serializing Objects to the response body stream
 * @param contentTypeResolver for resolving the requested content type
 * @param adapterRegistry for adapting other reactive types (e.g. rx.Observable,
 * rx.Single, etc.) to Flux or Mono
 */
protected AbstractMessageWriterResultHandler(List<HttpMessageWriter<?>> messageWriters,
		RequestedContentTypeResolver contentTypeResolver, ReactiveAdapterRegistry adapterRegistry) {

	super(contentTypeResolver, adapterRegistry);
	Assert.notEmpty(messageWriters, "At least one message writer is required");
	this.messageWriters = messageWriters;
}
 
Example #28
Source File: BodyInserters.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Mono<Void> insert(ClientHttpRequest outputMessage, Context context) {
	HttpMessageWriter<MultiValueMap<String, HttpEntity<?>>> messageWriter =
			findWriter(context, MULTIPART_DATA_TYPE, MediaType.MULTIPART_FORM_DATA);
	MultiValueMap<String, HttpEntity<?>> body = this.builder.build();
	return messageWriter.write(Mono.just(body), MULTIPART_DATA_TYPE,
			MediaType.MULTIPART_FORM_DATA, outputMessage, context.hints());
}
 
Example #29
Source File: AbstractMessageWriterResultHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private List<MediaType> getMediaTypesFor(ResolvableType elementType) {
	List<MediaType> writableMediaTypes = new ArrayList<>();
	for (HttpMessageWriter<?> converter : getMessageWriters()) {
		if (converter.canWrite(elementType, null)) {
			writableMediaTypes.addAll(converter.getWritableMediaTypes());
		}
	}
	return writableMediaTypes;
}
 
Example #30
Source File: ResponseBodyResultHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void setup() throws Exception {
	List<HttpMessageWriter<?>> writerList = new ArrayList<>(5);
	writerList.add(new EncoderHttpMessageWriter<>(new ByteBufferEncoder()));
	writerList.add(new EncoderHttpMessageWriter<>(CharSequenceEncoder.allMimeTypes()));
	writerList.add(new ResourceHttpMessageWriter());
	writerList.add(new EncoderHttpMessageWriter<>(new Jaxb2XmlEncoder()));
	writerList.add(new EncoderHttpMessageWriter<>(new Jackson2JsonEncoder()));
	RequestedContentTypeResolver resolver = new RequestedContentTypeResolverBuilder().build();
	this.resultHandler = new ResponseBodyResultHandler(writerList, resolver);
}