Search in sources :

Example 86 with DataBuffer

use of org.springframework.core.io.buffer.DataBuffer in project spring-framework by spring-projects.

the class WebHttpHandlerBuilderTests method writeToResponse.

private static Mono<Void> writeToResponse(ServerWebExchange exchange, String value) {
    byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
    DataBuffer buffer = DefaultDataBufferFactory.sharedInstance.wrap(bytes);
    return exchange.getResponse().writeWith(Flux.just(buffer));
}
Also used : DataBuffer(org.springframework.core.io.buffer.DataBuffer)

Example 87 with DataBuffer

use of org.springframework.core.io.buffer.DataBuffer in project spring-framework by spring-projects.

the class MessagingRSocket method handleAndReply.

@SuppressWarnings("deprecation")
private Flux<Payload> handleAndReply(Payload firstPayload, FrameType frameType, Flux<Payload> payloads) {
    AtomicReference<Flux<Payload>> responseRef = new AtomicReference<>();
    MessageHeaders headers = createHeaders(firstPayload, frameType, responseRef);
    AtomicBoolean read = new AtomicBoolean();
    Flux<DataBuffer> buffers = payloads.map(this::retainDataAndReleasePayload).doOnSubscribe(s -> read.set(true));
    Message<Flux<DataBuffer>> message = MessageBuilder.createMessage(buffers, headers);
    return Mono.defer(() -> this.messageHandler.handleMessage(message)).doFinally(s -> {
        // Subscription should have happened by now due to ChannelSendOperator
        if (!read.get()) {
            firstPayload.release();
        }
    }).thenMany(Flux.defer(() -> responseRef.get() != null ? responseRef.get() : Mono.error(new IllegalStateException("Expected response"))));
}
Also used : PayloadUtils(org.springframework.messaging.rsocket.PayloadUtils) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) DestinationPatternsMessageCondition(org.springframework.messaging.handler.DestinationPatternsMessageCondition) AtomicReference(java.util.concurrent.atomic.AtomicReference) MetadataExtractor(org.springframework.messaging.rsocket.MetadataExtractor) RouteMatcher(org.springframework.util.RouteMatcher) HandlerMethodReturnValueHandler(org.springframework.messaging.handler.invocation.reactive.HandlerMethodReturnValueHandler) MimeType(org.springframework.util.MimeType) RSocket(io.rsocket.RSocket) Map(java.util.Map) DataBufferUtils(org.springframework.core.io.buffer.DataBufferUtils) Nullable(org.springframework.lang.Nullable) Message(org.springframework.messaging.Message) RSocketStrategies(org.springframework.messaging.rsocket.RSocketStrategies) NettyDataBuffer(org.springframework.core.io.buffer.NettyDataBuffer) MessageHeaderAccessor(org.springframework.messaging.support.MessageHeaderAccessor) RSocketRequester(org.springframework.messaging.rsocket.RSocketRequester) FrameType(io.rsocket.frame.FrameType) Publisher(org.reactivestreams.Publisher) Mono(reactor.core.publisher.Mono) DataBuffer(org.springframework.core.io.buffer.DataBuffer) MessageHeaders(org.springframework.messaging.MessageHeaders) Flux(reactor.core.publisher.Flux) Payload(io.rsocket.Payload) ReactiveMessageHandler(org.springframework.messaging.ReactiveMessageHandler) ConnectionSetupPayload(io.rsocket.ConnectionSetupPayload) MessageBuilder(org.springframework.messaging.support.MessageBuilder) Assert(org.springframework.util.Assert) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Flux(reactor.core.publisher.Flux) AtomicReference(java.util.concurrent.atomic.AtomicReference) MessageHeaders(org.springframework.messaging.MessageHeaders) NettyDataBuffer(org.springframework.core.io.buffer.NettyDataBuffer) DataBuffer(org.springframework.core.io.buffer.DataBuffer)

Example 88 with DataBuffer

use of org.springframework.core.io.buffer.DataBuffer in project spring-framework by spring-projects.

the class MessagingRSocket method handle.

private Mono<Void> handle(Payload payload, FrameType frameType) {
    MessageHeaders headers = createHeaders(payload, frameType, null);
    DataBuffer dataBuffer = retainDataAndReleasePayload(payload);
    int refCount = refCount(dataBuffer);
    Message<?> message = MessageBuilder.createMessage(dataBuffer, headers);
    return Mono.defer(() -> this.messageHandler.handleMessage(message)).doFinally(s -> {
        if (refCount(dataBuffer) == refCount) {
            DataBufferUtils.release(dataBuffer);
        }
    });
}
Also used : MessageHeaders(org.springframework.messaging.MessageHeaders) NettyDataBuffer(org.springframework.core.io.buffer.NettyDataBuffer) DataBuffer(org.springframework.core.io.buffer.DataBuffer)

Example 89 with DataBuffer

use of org.springframework.core.io.buffer.DataBuffer in project spring-framework by spring-projects.

the class PayloadMethodArgumentResolver method resolveArgument.

/**
 * Decode the content of the given message payload through a compatible
 * {@link Decoder}.
 *
 * <p>Validation is applied if the method argument is annotated with
 * {@code @jakarta.validation.Valid} or
 * {@link org.springframework.validation.annotation.Validated}. Validation
 * failure results in an {@link MethodArgumentNotValidException}.
 * @param parameter the target method argument that we are decoding to
 * @param message the message from which the content was extracted
 * @return a Mono with the result of argument resolution
 * @see #extractContent(MethodParameter, Message)
 * @see #getMimeType(Message)
 */
@Override
public final Mono<Object> resolveArgument(MethodParameter parameter, Message<?> message) {
    Payload ann = parameter.getParameterAnnotation(Payload.class);
    if (ann != null && StringUtils.hasText(ann.expression())) {
        throw new IllegalStateException("@Payload SpEL expressions not supported by this resolver");
    }
    MimeType mimeType = getMimeType(message);
    mimeType = mimeType != null ? mimeType : MimeTypeUtils.APPLICATION_OCTET_STREAM;
    Flux<DataBuffer> content = extractContent(parameter, message);
    return decodeContent(parameter, message, ann == null || ann.required(), content, mimeType);
}
Also used : Payload(org.springframework.messaging.handler.annotation.Payload) MimeType(org.springframework.util.MimeType) DataBuffer(org.springframework.core.io.buffer.DataBuffer)

Example 90 with DataBuffer

use of org.springframework.core.io.buffer.DataBuffer in project spring-framework by spring-projects.

the class MetadataEncoderTests method compositeMetadata.

@Test
public void compositeMetadata() {
    Mono<String> asyncMeta1 = Mono.delay(Duration.ofMillis(1)).map(aLong -> "Async Metadata 1");
    Mono<String> asyncMeta2 = Mono.delay(Duration.ofMillis(1)).map(aLong -> "Async Metadata 2");
    DataBuffer buffer = new MetadataEncoder(COMPOSITE_METADATA, this.strategies).route("toA").metadata("My metadata", MimeTypeUtils.TEXT_PLAIN).metadata(asyncMeta1, new MimeType("text", "x.test.metadata1")).metadata(Unpooled.wrappedBuffer("Raw data".getBytes(UTF_8)), MimeTypeUtils.APPLICATION_OCTET_STREAM).metadata(asyncMeta2, new MimeType("text", "x.test.metadata2")).encode().block();
    CompositeMetadata entries = new CompositeMetadata(((NettyDataBuffer) buffer).getNativeBuffer(), false);
    Iterator<CompositeMetadata.Entry> iterator = entries.iterator();
    assertThat(iterator.hasNext()).isTrue();
    CompositeMetadata.Entry entry = iterator.next();
    assertThat(entry.getMimeType()).isEqualTo(WellKnownMimeType.MESSAGE_RSOCKET_ROUTING.getString());
    assertRoute("toA", entry.getContent());
    assertThat(iterator.hasNext()).isTrue();
    entry = iterator.next();
    assertThat(entry.getMimeType()).isEqualTo(MimeTypeUtils.TEXT_PLAIN_VALUE);
    assertThat(entry.getContent().toString(UTF_8)).isEqualTo("My metadata");
    assertThat(iterator.hasNext()).isTrue();
    entry = iterator.next();
    assertThat(entry.getMimeType()).isEqualTo("text/x.test.metadata1");
    assertThat(entry.getContent().toString(UTF_8)).isEqualTo("Async Metadata 1");
    assertThat(iterator.hasNext()).isTrue();
    entry = iterator.next();
    assertThat(entry.getMimeType()).isEqualTo(MimeTypeUtils.APPLICATION_OCTET_STREAM_VALUE);
    assertThat(entry.getContent().toString(UTF_8)).isEqualTo("Raw data");
    assertThat(iterator.hasNext()).isTrue();
    entry = iterator.next();
    assertThat(entry.getMimeType()).isEqualTo("text/x.test.metadata2");
    assertThat(entry.getContent().toString(UTF_8)).isEqualTo("Async Metadata 2");
    assertThat(iterator.hasNext()).isFalse();
}
Also used : CompositeMetadata(io.rsocket.metadata.CompositeMetadata) MimeType(org.springframework.util.MimeType) WellKnownMimeType(io.rsocket.metadata.WellKnownMimeType) DataBuffer(org.springframework.core.io.buffer.DataBuffer) NettyDataBuffer(org.springframework.core.io.buffer.NettyDataBuffer) Test(org.junit.jupiter.api.Test)

Aggregations

DataBuffer (org.springframework.core.io.buffer.DataBuffer)230 Test (org.junit.jupiter.api.Test)111 Mono (reactor.core.publisher.Mono)55 Flux (reactor.core.publisher.Flux)52 DefaultDataBuffer (org.springframework.core.io.buffer.DefaultDataBuffer)49 ResolvableType (org.springframework.core.ResolvableType)41 DefaultDataBufferFactory (org.springframework.core.io.buffer.DefaultDataBufferFactory)36 StepVerifier (reactor.test.StepVerifier)36 List (java.util.List)34 Test (org.junit.Test)31 DataBufferUtils (org.springframework.core.io.buffer.DataBufferUtils)29 IOException (java.io.IOException)28 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)27 MockServerHttpRequest (org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest)27 Map (java.util.Map)25 NettyDataBuffer (org.springframework.core.io.buffer.NettyDataBuffer)25 DataBufferFactory (org.springframework.core.io.buffer.DataBufferFactory)24 HttpHeaders (org.springframework.http.HttpHeaders)24 MediaType (org.springframework.http.MediaType)24 ByteBuffer (java.nio.ByteBuffer)23