Search in sources :

Example 1 with HttpPayloadWriter

use of io.servicetalk.http.api.HttpPayloadWriter in project servicetalk by apple.

the class GracefulConnectionClosureHandlingTest method setUp.

void setUp(HttpProtocol protocol, boolean initiateClosureFromClient, boolean useUds, boolean viaProxy) throws Exception {
    this.protocol = protocol;
    this.initiateClosureFromClient = initiateClosureFromClient;
    if (useUds) {
        Assumptions.assumeTrue(SERVER_CTX.ioExecutor().isUnixDomainSocketSupported(), "Server's IoExecutor does not support UnixDomainSocket");
        Assumptions.assumeTrue(CLIENT_CTX.ioExecutor().isUnixDomainSocketSupported(), "Client's IoExecutor does not support UnixDomainSocket");
        assumeFalse(viaProxy, "UDS cannot be used via proxy");
    }
    assumeFalse(protocol == HTTP_2 && viaProxy, "Proxy is not supported with HTTP/2");
    HttpServerBuilder serverBuilder = (useUds ? forAddress(newSocketAddress()) : forAddress(localAddress(0))).protocols(protocol.config).ioExecutor(SERVER_CTX.ioExecutor()).executor(SERVER_CTX.executor()).executionStrategy(defaultStrategy()).enableWireLogging("servicetalk-tests-wire-logger", TRACE, () -> true).appendConnectionAcceptorFilter(original -> new DelegatingConnectionAcceptor(original) {

        @Override
        public Completable accept(final ConnectionContext context) {
            if (!initiateClosureFromClient) {
                ((NettyConnectionContext) context).onClosing().whenFinally(onClosing::countDown).subscribe();
            }
            context.onClose().whenFinally(serverConnectionClosed::countDown).subscribe();
            connectionAccepted.countDown();
            return completed();
        }
    });
    HostAndPort proxyAddress = null;
    if (viaProxy) {
        // Dummy proxy helps to emulate old intermediate systems that do not support half-closed TCP connections
        proxyTunnel = new ProxyTunnel();
        proxyAddress = proxyTunnel.startProxy();
        serverBuilder.sslConfig(new ServerSslConfigBuilder(DefaultTestCerts::loadServerPem, DefaultTestCerts::loadServerKey).build());
    } else {
        proxyTunnel = null;
    }
    serverContext = serverBuilder.listenBlockingStreamingAndAwait((ctx, request, response) -> {
        serverReceivedRequest.countDown();
        response.addHeader(CONTENT_LENGTH, valueOf(RESPONSE_CONTENT.length()));
        serverSendResponse.await();
        try (HttpPayloadWriter<String> writer = response.sendMetaData(RAW_STRING_SERIALIZER)) {
            // Subscribe to the request payload body before response writer closes
            BlockingIterator<Buffer> iterator = request.payloadBody().iterator();
            // Consume request payload body asynchronously:
            ctx.executionContext().executor().submit(() -> {
                int receivedSize = 0;
                while (iterator.hasNext()) {
                    Buffer chunk = iterator.next();
                    assert chunk != null;
                    receivedSize += chunk.readableBytes();
                }
                serverReceivedRequestPayload.add(receivedSize);
            }).beforeOnError(cause -> {
                LOGGER.error("failure while reading request", cause);
                serverReceivedRequestPayload.add(-1);
            }).toFuture();
            serverSendResponsePayload.await();
            writer.write(RESPONSE_CONTENT);
        }
    });
    serverContext.onClose().whenFinally(serverContextClosed::countDown).subscribe();
    client = (viaProxy ? forSingleAddress(serverHostAndPort(serverContext)).proxyAddress(proxyAddress).sslConfig(new ClientSslConfigBuilder(DefaultTestCerts::loadServerCAPem).peerHost(serverPemHostname()).build()) : forResolvedAddress(serverContext.listenAddress())).protocols(protocol.config).executor(CLIENT_CTX.executor()).ioExecutor(CLIENT_CTX.ioExecutor()).executionStrategy(defaultStrategy()).enableWireLogging("servicetalk-tests-wire-logger", TRACE, Boolean.TRUE::booleanValue).appendConnectionFactoryFilter(ConnectionFactoryFilter.withStrategy(cf -> initiateClosureFromClient ? new OnClosingConnectionFactoryFilter<>(cf, onClosing) : cf, ExecutionStrategy.offloadNone())).buildStreaming();
    connection = client.reserveConnection(client.get("/")).toFuture().get();
    connection.onClose().whenFinally(clientConnectionClosed::countDown).subscribe();
    // wait until server accepts connection
    connectionAccepted.await();
    toClose = initiateClosureFromClient ? connection : serverContext;
}
Also used : SocketAddress(java.net.SocketAddress) HttpProtocol.values(io.servicetalk.http.netty.HttpProtocol.values) PlatformDependent.throwException(io.servicetalk.utils.internal.PlatformDependent.throwException) ServerSslConfigBuilder(io.servicetalk.transport.api.ServerSslConfigBuilder) LoggerFactory(org.slf4j.LoggerFactory) HttpSerializers.stringStreamingSerializer(io.servicetalk.http.api.HttpSerializers.stringStreamingSerializer) ZERO(io.servicetalk.http.api.HttpHeaderValues.ZERO) Future(java.util.concurrent.Future) CloseEvent(io.servicetalk.transport.netty.internal.CloseHandler.CloseEvent) HttpExecutionStrategies.defaultStrategy(io.servicetalk.http.api.HttpExecutionStrategies.defaultStrategy) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Arrays.asList(java.util.Arrays.asList) Assumptions.assumeFalse(org.junit.jupiter.api.Assumptions.assumeFalse) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) MethodSource(org.junit.jupiter.params.provider.MethodSource) GRACEFUL_USER_CLOSING(io.servicetalk.transport.netty.internal.CloseHandler.CloseEvent.GRACEFUL_USER_CLOSING) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) Collection(java.util.Collection) HttpClients.forSingleAddress(io.servicetalk.http.netty.HttpClients.forSingleAddress) ConnectionFactoryFilter(io.servicetalk.client.api.ConnectionFactoryFilter) CompositeCloseable(io.servicetalk.concurrent.api.CompositeCloseable) CHANNEL_CLOSED_INBOUND(io.servicetalk.transport.netty.internal.CloseHandler.CloseEvent.CHANNEL_CLOSED_INBOUND) BlockingQueue(java.util.concurrent.BlockingQueue) AsyncCloseables.newCompositeCloseable(io.servicetalk.concurrent.api.AsyncCloseables.newCompositeCloseable) Arguments(org.junit.jupiter.params.provider.Arguments) CONTENT_LENGTH(io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH) HttpClients.forResolvedAddress(io.servicetalk.http.netty.HttpClients.forResolvedAddress) DefaultTestCerts.serverPemHostname(io.servicetalk.test.resources.DefaultTestCerts.serverPemHostname) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) CountDownLatch(java.util.concurrent.CountDownLatch) HttpsProxyTest.safeClose(io.servicetalk.http.netty.HttpsProxyTest.safeClose) Buffer(io.servicetalk.buffer.api.Buffer) DelegatingConnectionAcceptor(io.servicetalk.transport.api.DelegatingConnectionAcceptor) TransportObserver(io.servicetalk.transport.api.TransportObserver) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) HTTP_2(io.servicetalk.http.netty.HttpProtocol.HTTP_2) Matchers.is(org.hamcrest.Matchers.is) BlockingIterator(io.servicetalk.concurrent.BlockingIterator) ReservedStreamingHttpConnection(io.servicetalk.http.api.ReservedStreamingHttpConnection) Matchers.anyOf(org.hamcrest.Matchers.anyOf) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) TRACE(io.servicetalk.logging.api.LogLevel.TRACE) HttpServers.forAddress(io.servicetalk.http.netty.HttpServers.forAddress) FilterableStreamingHttpConnection(io.servicetalk.http.api.FilterableStreamingHttpConnection) ArrayList(java.util.ArrayList) HttpPayloadWriter(io.servicetalk.http.api.HttpPayloadWriter) ExecutionStrategy(io.servicetalk.transport.api.ExecutionStrategy) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) CloseEventObservedException(io.servicetalk.transport.netty.internal.CloseHandler.CloseEventObservedException) Objects.requireNonNull(java.util.Objects.requireNonNull) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) AsyncCloseable(io.servicetalk.concurrent.api.AsyncCloseable) NettyConnectionContext(io.servicetalk.transport.netty.internal.NettyConnectionContext) Matchers.contentEqualTo(io.servicetalk.buffer.api.Matchers.contentEqualTo) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) DelegatingConnectionFactory(io.servicetalk.client.api.DelegatingConnectionFactory) Publisher.from(io.servicetalk.concurrent.api.Publisher.from) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) Nullable(javax.annotation.Nullable) ConnectionContext(io.servicetalk.transport.api.ConnectionContext) ConnectionFactory(io.servicetalk.client.api.ConnectionFactory) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) Logger(org.slf4j.Logger) AddressUtils.newSocketAddress(io.servicetalk.transport.netty.internal.AddressUtils.newSocketAddress) ServerContext(io.servicetalk.transport.api.ServerContext) ClosedChannelException(java.nio.channels.ClosedChannelException) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Single(io.servicetalk.concurrent.api.Single) Completable(io.servicetalk.concurrent.api.Completable) ExecutionContextExtension(io.servicetalk.transport.netty.internal.ExecutionContextExtension) IOException(java.io.IOException) OK(io.servicetalk.http.api.HttpResponseStatus.OK) Integer.parseInt(java.lang.Integer.parseInt) ExecutionException(java.util.concurrent.ExecutionException) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) String.valueOf(java.lang.String.valueOf) Assumptions(org.junit.jupiter.api.Assumptions) Executable(org.junit.jupiter.api.function.Executable) Completable.completed(io.servicetalk.concurrent.api.Completable.completed) HttpStreamingSerializer(io.servicetalk.http.api.HttpStreamingSerializer) HostAndPort(io.servicetalk.transport.api.HostAndPort) Buffer(io.servicetalk.buffer.api.Buffer) Completable(io.servicetalk.concurrent.api.Completable) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) DelegatingConnectionAcceptor(io.servicetalk.transport.api.DelegatingConnectionAcceptor) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) HostAndPort(io.servicetalk.transport.api.HostAndPort) NettyConnectionContext(io.servicetalk.transport.netty.internal.NettyConnectionContext) ConnectionContext(io.servicetalk.transport.api.ConnectionContext) HttpPayloadWriter(io.servicetalk.http.api.HttpPayloadWriter) BlockingIterator(io.servicetalk.concurrent.BlockingIterator) ServerSslConfigBuilder(io.servicetalk.transport.api.ServerSslConfigBuilder)

Example 2 with HttpPayloadWriter

use of io.servicetalk.http.api.HttpPayloadWriter in project servicetalk by apple.

the class RequestResponseContextTest method service.

@Override
void service(final StreamingHttpService service) {
    final StreamingHttpService newService;
    assert api != null;
    switch(api) {
        case AsyncAggregated:
            newService = toStreamingHttpService((HttpService) (ctx, request, responseFactory) -> {
                HttpResponse response = responseFactory.ok().payloadBody(request.payloadBody());
                transferContext(request, response);
                return succeeded(response);
            }, offloadNone()).adaptor();
            break;
        case AsyncStreaming:
            newService = (ctx, request, responseFactory) -> {
                StreamingHttpResponse response = responseFactory.ok().payloadBody(request.payloadBody());
                transferContext(request, response);
                return succeeded(response);
            };
            break;
        case BlockingAggregated:
            newService = toStreamingHttpService((BlockingHttpService) (ctx, request, responseFactory) -> {
                HttpResponse response = responseFactory.ok().payloadBody(request.payloadBody());
                transferContext(request, response);
                return response;
            }, offloadNone()).adaptor();
            break;
        case BlockingStreaming:
            newService = toStreamingHttpService((ctx, request, response) -> {
                transferContext(request, response);
                try (HttpPayloadWriter<Buffer> writer = response.sendMetaData()) {
                    for (Buffer chunk : request.payloadBody()) {
                        writer.write(chunk);
                    }
                }
            }, offloadNone()).adaptor();
            break;
        default:
            throw new IllegalStateException("Unknown api: " + api);
    }
    super.service(newService);
}
Also used : TestUtils.assertNoAsyncErrors(io.servicetalk.test.resources.TestUtils.assertNoAsyncErrors) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) HttpResponseMetaData(io.servicetalk.http.api.HttpResponseMetaData) Key.newKey(io.servicetalk.context.api.ContextMap.Key.newKey) Collections.singletonList(java.util.Collections.singletonList) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) HttpPayloadWriter(io.servicetalk.http.api.HttpPayloadWriter) HttpRequest(io.servicetalk.http.api.HttpRequest) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) BlockingStreamingHttpResponse(io.servicetalk.http.api.BlockingStreamingHttpResponse) HttpClient(io.servicetalk.http.api.HttpClient) Matchers.hasSize(org.hamcrest.Matchers.hasSize) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) HttpApiConversions.toStreamingHttpService(io.servicetalk.http.api.HttpApiConversions.toStreamingHttpService) HttpExecutionStrategies.offloadNone(io.servicetalk.http.api.HttpExecutionStrategies.offloadNone) Matchers.contentEqualTo(io.servicetalk.buffer.api.Matchers.contentEqualTo) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Nullable(javax.annotation.Nullable) CACHED_SERVER(io.servicetalk.http.netty.AbstractNettyHttpServerTest.ExecutorSupplier.CACHED_SERVER) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) HttpService(io.servicetalk.http.api.HttpService) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) Single(io.servicetalk.concurrent.api.Single) HttpResponse(io.servicetalk.http.api.HttpResponse) SVC_ECHO(io.servicetalk.http.netty.TestServiceStreaming.SVC_ECHO) StreamingHttpConnectionFilter(io.servicetalk.http.api.StreamingHttpConnectionFilter) OK(io.servicetalk.http.api.HttpResponseStatus.OK) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) BlockingStreamingHttpClient(io.servicetalk.http.api.BlockingStreamingHttpClient) HttpRequestMetaData(io.servicetalk.http.api.HttpRequestMetaData) Test(org.junit.jupiter.api.Test) List(java.util.List) Buffer(io.servicetalk.buffer.api.Buffer) CACHED(io.servicetalk.http.netty.AbstractNettyHttpServerTest.ExecutorSupplier.CACHED) String.valueOf(java.lang.String.valueOf) ContextMap(io.servicetalk.context.api.ContextMap) BlockingHttpService(io.servicetalk.http.api.BlockingHttpService) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) Matchers.contains(org.hamcrest.Matchers.contains) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) Matchers.is(org.hamcrest.Matchers.is) Queue(java.util.Queue) BlockingStreamingHttpRequest(io.servicetalk.http.api.BlockingStreamingHttpRequest) HTTP_1_1(io.servicetalk.http.api.HttpProtocolVersion.HTTP_1_1) Buffer(io.servicetalk.buffer.api.Buffer) HttpApiConversions.toStreamingHttpService(io.servicetalk.http.api.HttpApiConversions.toStreamingHttpService) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) BlockingStreamingHttpResponse(io.servicetalk.http.api.BlockingStreamingHttpResponse) HttpResponse(io.servicetalk.http.api.HttpResponse) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) BlockingStreamingHttpResponse(io.servicetalk.http.api.BlockingStreamingHttpResponse)

Example 3 with HttpPayloadWriter

use of io.servicetalk.http.api.HttpPayloadWriter in project servicetalk by apple.

the class BlockingStreamingHttpServiceTest method setRequestMessageBody.

@Test
void setRequestMessageBody() throws Exception {
    BlockingStreamingHttpClient client = context((ctx, request, response) -> {
        response.status(OK);
        try {
            HttpMessageBodyIterator<Buffer> reqItr = request.messageBody().iterator();
            StringBuilder sb = new StringBuilder();
            while (reqItr.hasNext()) {
                sb.append(requireNonNull(reqItr.next()).toString(UTF_8));
            }
            assertThat(sb.toString(), is(HELLO_WORLD));
            HttpHeaders trailers = reqItr.trailers();
            assertThat(trailers, notNullValue());
            assertThat(trailers.get(X_TOTAL_LENGTH).toString(), is(HELLO_WORLD_LENGTH));
        } catch (Throwable cause) {
            HttpPayloadWriter<String> payloadWriter = response.sendMetaData(appSerializerUtf8FixLen());
            payloadWriter.write(cause.toString());
            payloadWriter.close();
            return;
        }
        response.sendMetaData(appSerializerUtf8FixLen()).close();
    });
    BufferAllocator alloc = client.executionContext().bufferAllocator();
    BlockingStreamingHttpRequest req = client.get("/");
    req.setHeader(TRAILER, X_TOTAL_LENGTH);
    int split = HELLO_WORLD.length() / 2;
    final BlockingIterable<Buffer> reqIterable = BlockingIterables.from(asList(alloc.fromAscii(HELLO_WORLD.substring(0, split)), alloc.fromAscii(HELLO_WORLD.substring(split))));
    req.messageBody(() -> new HttpMessageBodyIterator<Buffer>() {

        private final BlockingIterator<Buffer> iterator = reqIterable.iterator();

        @Nullable
        private HttpHeaders trailers;

        private int totalLength;

        @Nullable
        @Override
        public HttpHeaders trailers() {
            if (trailers == null) {
                trailers = DefaultHttpHeadersFactory.INSTANCE.newTrailers();
                trailers.set(X_TOTAL_LENGTH, String.valueOf(totalLength));
            }
            return trailers;
        }

        @Override
        public boolean hasNext(final long timeout, final TimeUnit unit) throws TimeoutException {
            return iterator.hasNext(timeout, unit);
        }

        @Nullable
        @Override
        public Buffer next(final long timeout, final TimeUnit unit) throws TimeoutException {
            return addTotalLength(iterator.next(timeout, unit));
        }

        @Override
        public boolean hasNext() {
            return iterator.hasNext();
        }

        @Nullable
        @Override
        public Buffer next() {
            return addTotalLength(iterator.next());
        }

        @Override
        public void close() throws Exception {
            iterator.close();
        }

        @Nullable
        private Buffer addTotalLength(@Nullable Buffer buffer) {
            if (buffer != null) {
                totalLength += buffer.readableBytes();
            }
            return buffer;
        }
    });
    BlockingStreamingHttpResponse response = client.request(req);
    assertThat(response.status(), is(OK));
    assertThat(stream(response.payloadBody(appSerializerUtf8FixLen()).spliterator(), false).collect(Collectors.toList()), emptyIterable());
}
Also used : Buffer(io.servicetalk.buffer.api.Buffer) HttpHeaders(io.servicetalk.http.api.HttpHeaders) BlockingStreamingHttpClient(io.servicetalk.http.api.BlockingStreamingHttpClient) BlockingStreamingHttpRequest(io.servicetalk.http.api.BlockingStreamingHttpRequest) PlatformDependent.throwException(io.servicetalk.utils.internal.PlatformDependent.throwException) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) BufferAllocator(io.servicetalk.buffer.api.BufferAllocator) BlockingStreamingHttpResponse(io.servicetalk.http.api.BlockingStreamingHttpResponse) TimeUnit(java.util.concurrent.TimeUnit) HttpPayloadWriter(io.servicetalk.http.api.HttpPayloadWriter) Nullable(javax.annotation.Nullable) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.jupiter.api.Test)

Example 4 with HttpPayloadWriter

use of io.servicetalk.http.api.HttpPayloadWriter in project servicetalk by apple.

the class BlockingProtobufStreamingServer method main.

public static void main(String[] args) throws Exception {
    HttpServers.forPort(8080).listenBlockingStreamingAndAwait((ctx, request, response) -> {
        if (!"/protobuf".equals(request.requestTarget())) {
            response.status(NOT_FOUND).sendMetaData().close();
        } else if (!POST.equals(request.method())) {
            response.status(METHOD_NOT_ALLOWED).addHeader(ALLOW, POST.name()).sendMetaData().close();
        } else {
            BlockingIterable<RequestMessage> values = request.payloadBody(REQ_STREAMING_SERIALIZER);
            response.status(CREATED);
            try (HttpPayloadWriter<ResponseMessage> writer = response.sendMetaData(RESP_STREAMING_SERIALIZER)) {
                for (RequestMessage req : values) {
                    writer.write(ResponseMessage.newBuilder().setLength(req.getMessage().length()).build());
                }
            }
        }
    }).awaitShutdown();
}
Also used : BlockingIterable(io.servicetalk.concurrent.BlockingIterable) CREATED(io.servicetalk.http.api.HttpResponseStatus.CREATED) HttpPayloadWriter(io.servicetalk.http.api.HttpPayloadWriter) NOT_FOUND(io.servicetalk.http.api.HttpResponseStatus.NOT_FOUND) RESP_STREAMING_SERIALIZER(io.servicetalk.examples.http.serialization.protobuf.SerializerUtils.RESP_STREAMING_SERIALIZER) POST(io.servicetalk.http.api.HttpRequestMethod.POST) METHOD_NOT_ALLOWED(io.servicetalk.http.api.HttpResponseStatus.METHOD_NOT_ALLOWED) REQ_STREAMING_SERIALIZER(io.servicetalk.examples.http.serialization.protobuf.SerializerUtils.REQ_STREAMING_SERIALIZER) ResponseMessage(io.servicetalk.examples.http.serialization.protobuf.ExampleProtos.ResponseMessage) ALLOW(io.servicetalk.http.api.HttpHeaderNames.ALLOW) RequestMessage(io.servicetalk.examples.http.serialization.protobuf.ExampleProtos.RequestMessage) HttpServers(io.servicetalk.http.netty.HttpServers) RequestMessage(io.servicetalk.examples.http.serialization.protobuf.ExampleProtos.RequestMessage) ResponseMessage(io.servicetalk.examples.http.serialization.protobuf.ExampleProtos.ResponseMessage)

Example 5 with HttpPayloadWriter

use of io.servicetalk.http.api.HttpPayloadWriter in project servicetalk by apple.

the class BlockingPojoStreamingServer method main.

public static void main(String[] args) throws Exception {
    HttpServers.forPort(8080).listenBlockingStreamingAndAwait((ctx, request, response) -> {
        if (!"/pojos".equals(request.requestTarget())) {
            response.status(NOT_FOUND).sendMetaData().close();
        } else if (!POST.equals(request.method())) {
            response.status(METHOD_NOT_ALLOWED).addHeader(ALLOW, POST.name()).sendMetaData().close();
        } else {
            BlockingIterable<CreatePojoRequest> values = request.payloadBody(REQ_STREAMING_SERIALIZER);
            response.status(CREATED);
            try (HttpPayloadWriter<PojoResponse> writer = response.sendMetaData(RESP_STREAMING_SERIALIZER)) {
                for (CreatePojoRequest req : values) {
                    writer.write(new PojoResponse(ID_GENERATOR.getAndIncrement(), req.getValue()));
                }
            }
        }
    }).awaitShutdown();
}
Also used : CreatePojoRequest(io.servicetalk.examples.http.serialization.json.CreatePojoRequest) RESP_STREAMING_SERIALIZER(io.servicetalk.examples.http.serialization.json.SerializerUtils.RESP_STREAMING_SERIALIZER) PojoResponse(io.servicetalk.examples.http.serialization.json.PojoResponse) POST(io.servicetalk.http.api.HttpRequestMethod.POST) METHOD_NOT_ALLOWED(io.servicetalk.http.api.HttpResponseStatus.METHOD_NOT_ALLOWED) BlockingIterable(io.servicetalk.concurrent.BlockingIterable) CREATED(io.servicetalk.http.api.HttpResponseStatus.CREATED) REQ_STREAMING_SERIALIZER(io.servicetalk.examples.http.serialization.json.SerializerUtils.REQ_STREAMING_SERIALIZER) HttpPayloadWriter(io.servicetalk.http.api.HttpPayloadWriter) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) NOT_FOUND(io.servicetalk.http.api.HttpResponseStatus.NOT_FOUND) ALLOW(io.servicetalk.http.api.HttpHeaderNames.ALLOW) HttpServers(io.servicetalk.http.netty.HttpServers) CreatePojoRequest(io.servicetalk.examples.http.serialization.json.CreatePojoRequest) PojoResponse(io.servicetalk.examples.http.serialization.json.PojoResponse)

Aggregations

HttpPayloadWriter (io.servicetalk.http.api.HttpPayloadWriter)5 Buffer (io.servicetalk.buffer.api.Buffer)3 Nullable (javax.annotation.Nullable)3 Matchers.contentEqualTo (io.servicetalk.buffer.api.Matchers.contentEqualTo)2 BlockingIterable (io.servicetalk.concurrent.BlockingIterable)2 Single (io.servicetalk.concurrent.api.Single)2 BlockingStreamingHttpClient (io.servicetalk.http.api.BlockingStreamingHttpClient)2 BlockingStreamingHttpRequest (io.servicetalk.http.api.BlockingStreamingHttpRequest)2 BlockingStreamingHttpResponse (io.servicetalk.http.api.BlockingStreamingHttpResponse)2 ALLOW (io.servicetalk.http.api.HttpHeaderNames.ALLOW)2 POST (io.servicetalk.http.api.HttpRequestMethod.POST)2 CREATED (io.servicetalk.http.api.HttpResponseStatus.CREATED)2 METHOD_NOT_ALLOWED (io.servicetalk.http.api.HttpResponseStatus.METHOD_NOT_ALLOWED)2 NOT_FOUND (io.servicetalk.http.api.HttpResponseStatus.NOT_FOUND)2 OK (io.servicetalk.http.api.HttpResponseStatus.OK)2 StreamingHttpClient (io.servicetalk.http.api.StreamingHttpClient)2 StreamingHttpRequest (io.servicetalk.http.api.StreamingHttpRequest)2 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)2 HttpServers (io.servicetalk.http.netty.HttpServers)2 String.valueOf (java.lang.String.valueOf)2