Search in sources :

Example 1 with Decoder

use of org.springframework.core.codec.Decoder in project spring-framework by spring-projects.

the class MessageMappingMessageHandlerTests method initMesssageHandler.

private MessageMappingMessageHandler initMesssageHandler() {
    List<Decoder<?>> decoders = Collections.singletonList(StringDecoder.allMimeTypes());
    List<Encoder<?>> encoders = Collections.singletonList(CharSequenceEncoder.allMimeTypes());
    ReactiveAdapterRegistry registry = ReactiveAdapterRegistry.getSharedInstance();
    this.returnValueHandler = new TestEncoderMethodReturnValueHandler(encoders, registry);
    PropertySource<?> source = new MapPropertySource("test", Collections.singletonMap("path", "path123"));
    StaticApplicationContext context = new StaticApplicationContext();
    context.getEnvironment().getPropertySources().addFirst(source);
    context.registerSingleton("testController", TestController.class);
    context.refresh();
    MessageMappingMessageHandler messageHandler = new MessageMappingMessageHandler();
    messageHandler.getReturnValueHandlerConfigurer().addCustomHandler(this.returnValueHandler);
    messageHandler.setApplicationContext(context);
    messageHandler.setEmbeddedValueResolver(new EmbeddedValueResolver(context.getBeanFactory()));
    messageHandler.setDecoders(decoders);
    messageHandler.afterPropertiesSet();
    return messageHandler;
}
Also used : TestEncoderMethodReturnValueHandler(org.springframework.messaging.handler.invocation.reactive.TestEncoderMethodReturnValueHandler) StaticApplicationContext(org.springframework.context.support.StaticApplicationContext) CharSequenceEncoder(org.springframework.core.codec.CharSequenceEncoder) Encoder(org.springframework.core.codec.Encoder) MapPropertySource(org.springframework.core.env.MapPropertySource) ReactiveAdapterRegistry(org.springframework.core.ReactiveAdapterRegistry) EmbeddedValueResolver(org.springframework.beans.factory.config.EmbeddedValueResolver) Decoder(org.springframework.core.codec.Decoder) StringDecoder(org.springframework.core.codec.StringDecoder)

Example 2 with Decoder

use of org.springframework.core.codec.Decoder in project spring-framework by spring-projects.

the class PayloadMethodArgumentResolver method decodeContent.

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.filter(this::nonEmptyDataBuffer).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().filter(this::nonEmptyDataBuffer).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));
}
Also used : Decoder(org.springframework.core.codec.Decoder) Validator(org.springframework.validation.Validator) MethodArgumentNotValidException(org.springframework.messaging.handler.annotation.support.MethodArgumentNotValidException) Conventions(org.springframework.core.Conventions) DecodingException(org.springframework.core.codec.DecodingException) ArrayList(java.util.ArrayList) MimeType(org.springframework.util.MimeType) HandlerMethodArgumentResolver(org.springframework.messaging.handler.invocation.reactive.HandlerMethodArgumentResolver) Map(java.util.Map) MethodParameter(org.springframework.core.MethodParameter) DataBufferUtils(org.springframework.core.io.buffer.DataBufferUtils) Nullable(org.springframework.lang.Nullable) Message(org.springframework.messaging.Message) ResolvableType(org.springframework.core.ResolvableType) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) ReactiveAdapterRegistry(org.springframework.core.ReactiveAdapterRegistry) ReactiveAdapter(org.springframework.core.ReactiveAdapter) Validated(org.springframework.validation.annotation.Validated) Publisher(org.reactivestreams.Publisher) AnnotationUtils(org.springframework.core.annotation.AnnotationUtils) ObjectUtils(org.springframework.util.ObjectUtils) Mono(reactor.core.publisher.Mono) MimeTypeUtils(org.springframework.util.MimeTypeUtils) DataBuffer(org.springframework.core.io.buffer.DataBuffer) MessageHeaders(org.springframework.messaging.MessageHeaders) MethodArgumentResolutionException(org.springframework.messaging.handler.invocation.MethodArgumentResolutionException) Consumer(java.util.function.Consumer) Flux(reactor.core.publisher.Flux) List(java.util.List) CollectionUtils(org.springframework.util.CollectionUtils) SmartValidator(org.springframework.validation.SmartValidator) Annotation(java.lang.annotation.Annotation) Payload(org.springframework.messaging.handler.annotation.Payload) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) Collections(java.util.Collections) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) MethodArgumentResolutionException(org.springframework.messaging.handler.invocation.MethodArgumentResolutionException) ResolvableType(org.springframework.core.ResolvableType) ReactiveAdapter(org.springframework.core.ReactiveAdapter)

Example 3 with Decoder

use of org.springframework.core.codec.Decoder in project spring-framework by spring-projects.

the class CodecConfigurerTests method cloneDefaultCodecs.

@Test
void cloneDefaultCodecs() {
    CodecConfigurer clone = this.configurer.clone();
    Jackson2JsonDecoder jacksonDecoder = new Jackson2JsonDecoder();
    Jackson2JsonEncoder jacksonEncoder = new Jackson2JsonEncoder();
    Jaxb2XmlDecoder jaxb2Decoder = new Jaxb2XmlDecoder();
    Jaxb2XmlEncoder jaxb2Encoder = new Jaxb2XmlEncoder();
    ProtobufDecoder protoDecoder = new ProtobufDecoder();
    ProtobufEncoder protoEncoder = new ProtobufEncoder();
    clone.defaultCodecs().jackson2JsonDecoder(jacksonDecoder);
    clone.defaultCodecs().jackson2JsonEncoder(jacksonEncoder);
    clone.defaultCodecs().jaxb2Decoder(jaxb2Decoder);
    clone.defaultCodecs().jaxb2Encoder(jaxb2Encoder);
    clone.defaultCodecs().protobufDecoder(protoDecoder);
    clone.defaultCodecs().protobufEncoder(protoEncoder);
    // Clone has the customized the customizations
    List<Decoder<?>> decoders = clone.getReaders().stream().filter(reader -> reader instanceof DecoderHttpMessageReader).map(reader -> ((DecoderHttpMessageReader<?>) reader).getDecoder()).collect(Collectors.toList());
    List<Encoder<?>> encoders = clone.getWriters().stream().filter(writer -> writer instanceof EncoderHttpMessageWriter).map(reader -> ((EncoderHttpMessageWriter<?>) reader).getEncoder()).collect(Collectors.toList());
    assertThat(decoders).contains(jacksonDecoder, jaxb2Decoder, protoDecoder);
    assertThat(encoders).contains(jacksonEncoder, jaxb2Encoder, protoEncoder);
    // Original does not have the customizations
    decoders = this.configurer.getReaders().stream().filter(reader -> reader instanceof DecoderHttpMessageReader).map(reader -> ((DecoderHttpMessageReader<?>) reader).getDecoder()).collect(Collectors.toList());
    encoders = this.configurer.getWriters().stream().filter(writer -> writer instanceof EncoderHttpMessageWriter).map(reader -> ((EncoderHttpMessageWriter<?>) reader).getEncoder()).collect(Collectors.toList());
    assertThat(decoders).doesNotContain(jacksonDecoder, jaxb2Decoder, protoDecoder);
    assertThat(encoders).doesNotContain(jacksonEncoder, jaxb2Encoder, protoEncoder);
}
Also used : CharSequenceEncoder(org.springframework.core.codec.CharSequenceEncoder) Decoder(org.springframework.core.codec.Decoder) ByteBufferEncoder(org.springframework.core.codec.ByteBufferEncoder) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ResourceHttpMessageWriter(org.springframework.http.codec.ResourceHttpMessageWriter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) FormHttpMessageReader(org.springframework.http.codec.FormHttpMessageReader) HttpMessageReader(org.springframework.http.codec.HttpMessageReader) ServerSentEventHttpMessageReader(org.springframework.http.codec.ServerSentEventHttpMessageReader) Jackson2JsonEncoder(org.springframework.http.codec.json.Jackson2JsonEncoder) NettyByteBufDecoder(org.springframework.core.codec.NettyByteBufDecoder) KotlinSerializationJsonEncoder(org.springframework.http.codec.json.KotlinSerializationJsonEncoder) EncoderHttpMessageWriter(org.springframework.http.codec.EncoderHttpMessageWriter) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BDDMockito.given(org.mockito.BDDMockito.given) ServerSentEventHttpMessageWriter(org.springframework.http.codec.ServerSentEventHttpMessageWriter) DataBufferDecoder(org.springframework.core.codec.DataBufferDecoder) Jaxb2XmlDecoder(org.springframework.http.codec.xml.Jaxb2XmlDecoder) ResolvableType(org.springframework.core.ResolvableType) ResourceHttpMessageReader(org.springframework.http.codec.ResourceHttpMessageReader) Encoder(org.springframework.core.codec.Encoder) Jackson2SmileDecoder(org.springframework.http.codec.json.Jackson2SmileDecoder) ProtobufDecoder(org.springframework.http.codec.protobuf.ProtobufDecoder) Jackson2JsonDecoder(org.springframework.http.codec.json.Jackson2JsonDecoder) Jaxb2XmlEncoder(org.springframework.http.codec.xml.Jaxb2XmlEncoder) KotlinSerializationJsonDecoder(org.springframework.http.codec.json.KotlinSerializationJsonDecoder) StringDecoder(org.springframework.core.codec.StringDecoder) MediaType(org.springframework.http.MediaType) ByteArrayEncoder(org.springframework.core.codec.ByteArrayEncoder) NettyByteBufEncoder(org.springframework.core.codec.NettyByteBufEncoder) CodecConfigurer(org.springframework.http.codec.CodecConfigurer) MimeTypeUtils(org.springframework.util.MimeTypeUtils) ByteBufferDecoder(org.springframework.core.codec.ByteBufferDecoder) Collectors(java.util.stream.Collectors) ByteArrayDecoder(org.springframework.core.codec.ByteArrayDecoder) DecoderHttpMessageReader(org.springframework.http.codec.DecoderHttpMessageReader) Test(org.junit.jupiter.api.Test) DataBufferEncoder(org.springframework.core.codec.DataBufferEncoder) ProtobufEncoder(org.springframework.http.codec.protobuf.ProtobufEncoder) List(java.util.List) Jackson2SmileEncoder(org.springframework.http.codec.json.Jackson2SmileEncoder) ProtobufHttpMessageWriter(org.springframework.http.codec.protobuf.ProtobufHttpMessageWriter) ExtensionRegistry(com.google.protobuf.ExtensionRegistry) HttpMessageWriter(org.springframework.http.codec.HttpMessageWriter) Mockito.mock(org.mockito.Mockito.mock) DecoderHttpMessageReader(org.springframework.http.codec.DecoderHttpMessageReader) ProtobufEncoder(org.springframework.http.codec.protobuf.ProtobufEncoder) Jackson2JsonDecoder(org.springframework.http.codec.json.Jackson2JsonDecoder) Jaxb2XmlDecoder(org.springframework.http.codec.xml.Jaxb2XmlDecoder) ProtobufDecoder(org.springframework.http.codec.protobuf.ProtobufDecoder) Decoder(org.springframework.core.codec.Decoder) NettyByteBufDecoder(org.springframework.core.codec.NettyByteBufDecoder) DataBufferDecoder(org.springframework.core.codec.DataBufferDecoder) Jaxb2XmlDecoder(org.springframework.http.codec.xml.Jaxb2XmlDecoder) Jackson2SmileDecoder(org.springframework.http.codec.json.Jackson2SmileDecoder) ProtobufDecoder(org.springframework.http.codec.protobuf.ProtobufDecoder) Jackson2JsonDecoder(org.springframework.http.codec.json.Jackson2JsonDecoder) KotlinSerializationJsonDecoder(org.springframework.http.codec.json.KotlinSerializationJsonDecoder) StringDecoder(org.springframework.core.codec.StringDecoder) ByteBufferDecoder(org.springframework.core.codec.ByteBufferDecoder) ByteArrayDecoder(org.springframework.core.codec.ByteArrayDecoder) Jaxb2XmlEncoder(org.springframework.http.codec.xml.Jaxb2XmlEncoder) Jackson2JsonEncoder(org.springframework.http.codec.json.Jackson2JsonEncoder) EncoderHttpMessageWriter(org.springframework.http.codec.EncoderHttpMessageWriter) CharSequenceEncoder(org.springframework.core.codec.CharSequenceEncoder) ByteBufferEncoder(org.springframework.core.codec.ByteBufferEncoder) Jackson2JsonEncoder(org.springframework.http.codec.json.Jackson2JsonEncoder) KotlinSerializationJsonEncoder(org.springframework.http.codec.json.KotlinSerializationJsonEncoder) Encoder(org.springframework.core.codec.Encoder) Jaxb2XmlEncoder(org.springframework.http.codec.xml.Jaxb2XmlEncoder) ByteArrayEncoder(org.springframework.core.codec.ByteArrayEncoder) NettyByteBufEncoder(org.springframework.core.codec.NettyByteBufEncoder) DataBufferEncoder(org.springframework.core.codec.DataBufferEncoder) ProtobufEncoder(org.springframework.http.codec.protobuf.ProtobufEncoder) Jackson2SmileEncoder(org.springframework.http.codec.json.Jackson2SmileEncoder) CodecConfigurer(org.springframework.http.codec.CodecConfigurer) Test(org.junit.jupiter.api.Test)

Aggregations

Decoder (org.springframework.core.codec.Decoder)3 List (java.util.List)2 ReactiveAdapterRegistry (org.springframework.core.ReactiveAdapterRegistry)2 ResolvableType (org.springframework.core.ResolvableType)2 CharSequenceEncoder (org.springframework.core.codec.CharSequenceEncoder)2 Encoder (org.springframework.core.codec.Encoder)2 StringDecoder (org.springframework.core.codec.StringDecoder)2 MimeTypeUtils (org.springframework.util.MimeTypeUtils)2 ExtensionRegistry (com.google.protobuf.ExtensionRegistry)1 Annotation (java.lang.annotation.Annotation)1 ArrayList (java.util.ArrayList)1 Collections (java.util.Collections)1 Map (java.util.Map)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 Consumer (java.util.function.Consumer)1 Collectors (java.util.stream.Collectors)1 Log (org.apache.commons.logging.Log)1 LogFactory (org.apache.commons.logging.LogFactory)1 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)1