Search in sources :

Example 6 with CONTENT_LENGTH

use of io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH in project servicetalk by apple.

the class ContentLengthAndTrailersTest method setUp.

private void setUp(HttpProtocol protocol, String content) {
    this.protocol = protocol;
    this.content = content;
    protocol(protocol.config);
    serviceFilterFactory(service -> new StreamingHttpServiceFilter(service) {

        @Override
        public Single<StreamingHttpResponse> handle(final HttpServiceContext ctx, final StreamingHttpRequest request, final StreamingHttpResponseFactory responseFactory) {
            // Use transform to simulate access to request trailers
            return delegate().handle(ctx, request.transform(new StatelessTrailersTransformer<>()), responseFactory).map(response -> {
                final HttpHeaders headers = request.headers();
                if (headers.contains(CONTENT_LENGTH)) {
                    response.setHeader(CLIENT_CONTENT_LENGTH, mergeValues(headers.values(CONTENT_LENGTH)));
                }
                if (headers.contains(TRANSFER_ENCODING)) {
                    response.setHeader(CLIENT_TRANSFER_ENCODING, mergeValues(headers.values(TRANSFER_ENCODING)));
                }
                return response;
            });
        }
    });
    setUp(CACHED, CACHED_SERVER);
}
Also used : StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) TrailersTransformer(io.servicetalk.http.api.TrailersTransformer) HttpHeaders(io.servicetalk.http.api.HttpHeaders) CONTENT_TYPE(io.servicetalk.http.api.HttpHeaderNames.CONTENT_TYPE) CharSequences.newAsciiString(io.servicetalk.buffer.api.CharSequences.newAsciiString) ArrayList(java.util.ArrayList) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) HttpMetaData(io.servicetalk.http.api.HttpMetaData) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) HttpSerializers.appSerializerUtf8FixLen(io.servicetalk.http.api.HttpSerializers.appSerializerUtf8FixLen) Matchers.nullValue(org.hamcrest.Matchers.nullValue) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) Matchers.contentEqualTo(io.servicetalk.buffer.api.Matchers.contentEqualTo) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Publisher.from(io.servicetalk.concurrent.api.Publisher.from) Nullable(javax.annotation.Nullable) CHUNKED(io.servicetalk.http.api.HttpHeaderValues.CHUNKED) CACHED_SERVER(io.servicetalk.http.netty.AbstractNettyHttpServerTest.ExecutorSupplier.CACHED_SERVER) MethodSource(org.junit.jupiter.params.provider.MethodSource) Single(io.servicetalk.concurrent.api.Single) TRANSFER_ENCODING(io.servicetalk.http.api.HttpHeaderNames.TRANSFER_ENCODING) StatelessTrailersTransformer(io.servicetalk.http.api.StatelessTrailersTransformer) Arguments(org.junit.jupiter.params.provider.Arguments) CONTENT_LENGTH(io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH) OK(io.servicetalk.http.api.HttpResponseStatus.OK) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) List(java.util.List) Buffer(io.servicetalk.buffer.api.Buffer) CACHED(io.servicetalk.http.netty.AbstractNettyHttpServerTest.ExecutorSupplier.CACHED) String.valueOf(java.lang.String.valueOf) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) Matchers.equalTo(org.hamcrest.Matchers.equalTo) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) HTTP_2(io.servicetalk.http.netty.HttpProtocol.HTTP_2) HTTP_1(io.servicetalk.http.netty.HttpProtocol.HTTP_1) HttpHeaders(io.servicetalk.http.api.HttpHeaders) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) Single(io.servicetalk.concurrent.api.Single) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) StatelessTrailersTransformer(io.servicetalk.http.api.StatelessTrailersTransformer) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest)

Example 7 with CONTENT_LENGTH

use of io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH in project servicetalk by apple.

the class MultiAddressUrlHttpClientTest method beforeClass.

@BeforeAll
static void beforeClass() throws Exception {
    afterClassCloseables = newCompositeCloseable();
    client = afterClassCloseables.append(HttpClients.forMultiAddressUrl().followRedirects(new RedirectConfigBuilder().allowNonRelativeRedirects(true).build()).initializer((scheme, address, builder) -> builder.serviceDiscoverer(sdThatSupportsInvalidHostname())).buildStreaming());
    httpService = (ctx, request, factory) -> {
        if (HTTP_1_1.equals(request.version()) && !request.headers().contains(HOST)) {
            return succeeded(factory.badRequest().setHeader(CONTENT_LENGTH, ZERO));
        }
        if (OPTIONS.equals(request.method()) || CONNECT.equals(request.method())) {
            return succeeded(factory.ok().setHeader(CONTENT_LENGTH, ZERO));
        }
        StreamingHttpResponse response;
        try {
            HttpResponseStatus status = HttpResponseStatus.of(parseInt(request.path().substring(1)), "");
            response = factory.newResponse(status);
            final CharSequence locationHeader = request.headers().get(X_REQUESTED_LOCATION);
            if (locationHeader != null) {
                response.headers().set(LOCATION, locationHeader);
            }
        } catch (Exception e) {
            response = factory.badRequest();
        }
        return succeeded(response.setHeader(CONTENT_LENGTH, ZERO).setHeader(X_RECEIVED_REQUEST_TARGET, request.requestTarget()));
    };
    final ServerContext serverCtx = startNewLocalServer(httpService, afterClassCloseables);
    final HostAndPort serverHostAndPort = serverHostAndPort(serverCtx);
    serverHost = serverHostAndPort.hostName();
    serverPort = serverHostAndPort.port();
    hostHeader = hostHeader(serverHostAndPort);
}
Also used : LOCATION(io.servicetalk.http.api.HttpHeaderNames.LOCATION) ServiceDiscovererEvent(io.servicetalk.client.api.ServiceDiscovererEvent) BAD_REQUEST(io.servicetalk.http.api.HttpResponseStatus.BAD_REQUEST) AfterAll(org.junit.jupiter.api.AfterAll) ZERO(io.servicetalk.http.api.HttpHeaderValues.ZERO) CREATED(io.servicetalk.http.api.HttpResponseStatus.CREATED) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) BeforeAll(org.junit.jupiter.api.BeforeAll) Arrays.asList(java.util.Arrays.asList) UNAUTHORIZED(io.servicetalk.http.api.HttpResponseStatus.UNAUTHORIZED) AddressUtils.hostHeader(io.servicetalk.transport.netty.internal.AddressUtils.hostHeader) BlockingTestUtils.awaitIndefinitelyNonNull(io.servicetalk.concurrent.api.BlockingTestUtils.awaitIndefinitelyNonNull) SEE_OTHER(io.servicetalk.http.api.HttpResponseStatus.SEE_OTHER) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) Collection(java.util.Collection) CompositeCloseable(io.servicetalk.concurrent.api.CompositeCloseable) ServiceDiscoverer(io.servicetalk.client.api.ServiceDiscoverer) CONNECT(io.servicetalk.http.api.HttpRequestMethod.CONNECT) AsyncCloseables.newCompositeCloseable(io.servicetalk.concurrent.api.AsyncCloseables.newCompositeCloseable) CONTENT_LENGTH(io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH) InetSocketAddress(java.net.InetSocketAddress) String.format(java.lang.String.format) Test(org.junit.jupiter.api.Test) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) List(java.util.List) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) GlobalDnsServiceDiscoverer.globalDnsServiceDiscoverer(io.servicetalk.http.netty.GlobalDnsServiceDiscoverer.globalDnsServiceDiscoverer) Matchers.is(org.hamcrest.Matchers.is) NOT_IMPLEMENTED(io.servicetalk.http.api.HttpResponseStatus.NOT_IMPLEMENTED) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Publisher(io.servicetalk.concurrent.api.Publisher) BAD_GATEWAY(io.servicetalk.http.api.HttpResponseStatus.BAD_GATEWAY) RedirectConfigBuilder(io.servicetalk.http.api.RedirectConfigBuilder) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) HOST(io.servicetalk.http.api.HttpHeaderNames.HOST) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) OPTIONS(io.servicetalk.http.api.HttpRequestMethod.OPTIONS) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) INTERNAL_SERVER_ERROR(io.servicetalk.http.api.HttpResponseStatus.INTERNAL_SERVER_ERROR) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ServerContext(io.servicetalk.transport.api.ServerContext) MalformedURLException(java.net.MalformedURLException) Completable(io.servicetalk.concurrent.api.Completable) ACCEPTED(io.servicetalk.http.api.HttpResponseStatus.ACCEPTED) OK(io.servicetalk.http.api.HttpResponseStatus.OK) UnknownHostException(java.net.UnknownHostException) SourceAdapters.toSource(io.servicetalk.concurrent.api.SourceAdapters.toSource) Integer.parseInt(java.lang.Integer.parseInt) ExecutionException(java.util.concurrent.ExecutionException) FORBIDDEN(io.servicetalk.http.api.HttpResponseStatus.FORBIDDEN) PERMANENT_REDIRECT(io.servicetalk.http.api.HttpResponseStatus.PERMANENT_REDIRECT) Completable.completed(io.servicetalk.concurrent.api.Completable.completed) TestSingleSubscriber(io.servicetalk.concurrent.test.internal.TestSingleSubscriber) HttpResponseStatus(io.servicetalk.http.api.HttpResponseStatus) HTTP_1_1(io.servicetalk.http.api.HttpProtocolVersion.HTTP_1_1) MOVED_PERMANENTLY(io.servicetalk.http.api.HttpResponseStatus.MOVED_PERMANENTLY) HostAndPort(io.servicetalk.transport.api.HostAndPort) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) HostAndPort(io.servicetalk.transport.api.HostAndPort) ServerContext(io.servicetalk.transport.api.ServerContext) HttpResponseStatus(io.servicetalk.http.api.HttpResponseStatus) RedirectConfigBuilder(io.servicetalk.http.api.RedirectConfigBuilder) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) MalformedURLException(java.net.MalformedURLException) UnknownHostException(java.net.UnknownHostException) ExecutionException(java.util.concurrent.ExecutionException) BeforeAll(org.junit.jupiter.api.BeforeAll)

Example 8 with CONTENT_LENGTH

use of io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH in project servicetalk by apple.

the class ServerGracefulConnectionClosureHandlingTest method setUp.

@BeforeEach
void setUp() throws Exception {
    AtomicReference<Runnable> serverClose = new AtomicReference<>();
    serverContext = forAddress(localAddress(0)).ioExecutor(SERVER_CTX.ioExecutor()).executor(SERVER_CTX.executor()).executionStrategy(offloadNone()).appendConnectionAcceptorFilter(original -> new DelegatingConnectionAcceptor(original) {

        @Override
        public Completable accept(final ConnectionContext context) {
            ((NettyHttpServerConnection) context).onClosing().whenFinally(serverConnectionClosing::countDown).subscribe();
            context.onClose().whenFinally(serverConnectionClosed::countDown).subscribe();
            return completed();
        }
    }).listenStreamingAndAwait((ctx, request, responseFactory) -> succeeded(responseFactory.ok().addHeader(CONTENT_LENGTH, valueOf(RESPONSE_CONTENT.length())).payloadBody(request.payloadBody().ignoreElements().concat(from(RESPONSE_CONTENT)), RAW_STRING_SERIALIZER).transformMessageBody(payload -> payload.whenFinally(serverClose.get()))));
    serverContext.onClose().whenFinally(serverContextClosed::countDown).subscribe();
    serverClose.set(() -> serverContext.closeAsyncGracefully().subscribe());
    serverAddress = (InetSocketAddress) serverContext.listenAddress();
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Socket(java.net.Socket) HttpSerializers.stringStreamingSerializer(io.servicetalk.http.api.HttpSerializers.stringStreamingSerializer) HttpServers.forAddress(io.servicetalk.http.netty.HttpServers.forAddress) AtomicReference(java.util.concurrent.atomic.AtomicReference) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) HttpExecutionStrategies.offloadNone(io.servicetalk.http.api.HttpExecutionStrategies.offloadNone) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Publisher.from(io.servicetalk.concurrent.api.Publisher.from) ConnectionContext(io.servicetalk.transport.api.ConnectionContext) OutputStream(java.io.OutputStream) NettyHttpServerConnection(io.servicetalk.http.netty.NettyHttpServer.NettyHttpServerConnection) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ServerContext(io.servicetalk.transport.api.ServerContext) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Completable(io.servicetalk.concurrent.api.Completable) ExecutionContextExtension(io.servicetalk.transport.netty.internal.ExecutionContextExtension) CONTENT_LENGTH(io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH) InetSocketAddress(java.net.InetSocketAddress) Test(org.junit.jupiter.api.Test) US_ASCII(java.nio.charset.StandardCharsets.US_ASCII) CountDownLatch(java.util.concurrent.CountDownLatch) AfterEach(org.junit.jupiter.api.AfterEach) String.valueOf(java.lang.String.valueOf) DelegatingConnectionAcceptor(io.servicetalk.transport.api.DelegatingConnectionAcceptor) Completable.completed(io.servicetalk.concurrent.api.Completable.completed) Matchers.is(org.hamcrest.Matchers.is) HttpStreamingSerializer(io.servicetalk.http.api.HttpStreamingSerializer) InputStream(java.io.InputStream) Completable(io.servicetalk.concurrent.api.Completable) DelegatingConnectionAcceptor(io.servicetalk.transport.api.DelegatingConnectionAcceptor) AtomicReference(java.util.concurrent.atomic.AtomicReference) ConnectionContext(io.servicetalk.transport.api.ConnectionContext) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 9 with CONTENT_LENGTH

use of io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH in project servicetalk by apple.

the class SslAndNonSslConnectionsTest method beforeClass.

@BeforeAll
static void beforeClass() throws Exception {
    final HttpHeaders httpHeaders = DefaultHttpHeadersFactory.INSTANCE.newHeaders().set(CONTENT_LENGTH, ZERO);
    // Configure HTTP server
    when(STREAMING_HTTP_SERVICE.handle(any(), any(), any())).thenAnswer((Answer<Single<StreamingHttpResponse>>) invocation -> {
        StreamingHttpResponseFactory factory = invocation.getArgument(2);
        StreamingHttpResponse resp = factory.ok();
        resp.headers().set(httpHeaders);
        return succeeded(resp);
    });
    when(STREAMING_HTTP_SERVICE.closeAsync()).thenReturn(completed());
    when(STREAMING_HTTP_SERVICE.closeAsyncGracefully()).thenReturn(completed());
    when(STREAMING_HTTP_SERVICE.requiredOffloads()).thenCallRealMethod();
    serverCtx = HttpServers.forAddress(localAddress(0)).executionStrategy(offloadNone()).listenStreamingAndAwait(STREAMING_HTTP_SERVICE);
    final String serverHostHeader = hostHeader(serverHostAndPort(serverCtx));
    requestTarget = "http://" + serverHostHeader + "/";
    // Configure HTTPS server
    when(SECURE_STREAMING_HTTP_SERVICE.handle(any(), any(), any())).thenAnswer(invocation -> {
        StreamingHttpResponseFactory factory = invocation.getArgument(2);
        StreamingHttpResponse resp = factory.ok();
        resp.headers().set(httpHeaders);
        return succeeded(resp);
    });
    when(SECURE_STREAMING_HTTP_SERVICE.closeAsync()).thenReturn(completed());
    when(SECURE_STREAMING_HTTP_SERVICE.closeAsyncGracefully()).thenReturn(completed());
    when(SECURE_STREAMING_HTTP_SERVICE.requiredOffloads()).thenCallRealMethod();
    secureServerCtx = HttpServers.forAddress(localAddress(0)).sslConfig(new ServerSslConfigBuilder(DefaultTestCerts::loadServerPem, DefaultTestCerts::loadServerKey).build()).executionStrategy(offloadNone()).listenStreamingAndAwait(SECURE_STREAMING_HTTP_SERVICE);
    final String secureServerHostHeader = hostHeader(serverHostAndPort(secureServerCtx));
    secureRequestTarget = "https://" + secureServerHostHeader + "/";
}
Also used : Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) ServerSslConfigBuilder(io.servicetalk.transport.api.ServerSslConfigBuilder) HttpHeaders(io.servicetalk.http.api.HttpHeaders) AfterAll(org.junit.jupiter.api.AfterAll) InetAddress(java.net.InetAddress) Answer(org.mockito.stubbing.Answer) ZERO(io.servicetalk.http.api.HttpHeaderValues.ZERO) BeforeAll(org.junit.jupiter.api.BeforeAll) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) AddressUtils.hostHeader(io.servicetalk.transport.netty.internal.AddressUtils.hostHeader) HttpExecutionStrategies.offloadNone(io.servicetalk.http.api.HttpExecutionStrategies.offloadNone) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Nullable(javax.annotation.Nullable) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ServerContext(io.servicetalk.transport.api.ServerContext) Mockito.clearInvocations(org.mockito.Mockito.clearInvocations) ClosedChannelException(java.nio.channels.ClosedChannelException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) Single(io.servicetalk.concurrent.api.Single) HttpResponse(io.servicetalk.http.api.HttpResponse) Mockito.times(org.mockito.Mockito.times) CertificateException(java.security.cert.CertificateException) Mockito.when(org.mockito.Mockito.when) CONTENT_LENGTH(io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH) OK(io.servicetalk.http.api.HttpResponseStatus.OK) DefaultTestCerts.serverPemHostname(io.servicetalk.test.resources.DefaultTestCerts.serverPemHostname) Mockito.verify(org.mockito.Mockito.verify) DefaultHttpHeadersFactory(io.servicetalk.http.api.DefaultHttpHeadersFactory) Test(org.junit.jupiter.api.Test) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) AfterEach(org.junit.jupiter.api.AfterEach) Mockito.never(org.mockito.Mockito.never) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) Completable.completed(io.servicetalk.concurrent.api.Completable.completed) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) Matchers.is(org.hamcrest.Matchers.is) HostAndPort(io.servicetalk.transport.api.HostAndPort) Mockito.mock(org.mockito.Mockito.mock) HttpHeaders(io.servicetalk.http.api.HttpHeaders) Single(io.servicetalk.concurrent.api.Single) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) ServerSslConfigBuilder(io.servicetalk.transport.api.ServerSslConfigBuilder) BeforeAll(org.junit.jupiter.api.BeforeAll)

Aggregations

CONTENT_LENGTH (io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH)9 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)8 Buffer (io.servicetalk.buffer.api.Buffer)6 Single (io.servicetalk.concurrent.api.Single)6 Single.succeeded (io.servicetalk.concurrent.api.Single.succeeded)6 OK (io.servicetalk.http.api.HttpResponseStatus.OK)6 ServerContext (io.servicetalk.transport.api.ServerContext)6 AddressUtils.localAddress (io.servicetalk.transport.netty.internal.AddressUtils.localAddress)6 Completable (io.servicetalk.concurrent.api.Completable)5 Completable.completed (io.servicetalk.concurrent.api.Completable.completed)5 Publisher.from (io.servicetalk.concurrent.api.Publisher.from)5 StreamingHttpRequest (io.servicetalk.http.api.StreamingHttpRequest)5 StreamingHttpResponseFactory (io.servicetalk.http.api.StreamingHttpResponseFactory)5 AddressUtils.serverHostAndPort (io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort)5 String.valueOf (java.lang.String.valueOf)5 Nullable (javax.annotation.Nullable)5 Publisher (io.servicetalk.concurrent.api.Publisher)4 ZERO (io.servicetalk.http.api.HttpHeaderValues.ZERO)4 HttpHeaders (io.servicetalk.http.api.HttpHeaders)4 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)4