Search in sources :

Example 1 with ZERO

use of io.servicetalk.http.api.HttpHeaderValues.ZERO in project servicetalk by apple.

the class DefaultContainerResponseWriter method sendResponse.

private void sendResponse(final long contentLength, @Nullable final Publisher<Buffer> content, final ContainerResponse containerResponse) {
    final HttpResponseStatus status = getStatus(containerResponse);
    final StreamingHttpResponse response;
    if (content != null && !isHeadRequest()) {
        final HttpExecutionStrategy executionStrategy = getResponseExecutionStrategy(request);
        // TODO(scott): use request factory methods that accept a payload body to avoid overhead of payloadBody.
        final Publisher<Buffer> payloadBody = (executionStrategy != null && executionStrategy.isSendOffloaded() ? content.subscribeOn(serviceCtx.executionContext().executor(), IoThreadFactory.IoThread::currentThreadIsIoThread) : content).beforeCancel(// Cleanup internal state if server cancels response body
        this::cancelResponse);
        response = responseFactory.newResponse(status).version(protocolVersion).payloadBody(payloadBody);
    } else {
        response = responseFactory.newResponse(status).version(protocolVersion);
    }
    final HttpHeaders headers = response.headers();
    // If we use HTTP/2 protocol all headers MUST be in lower case
    final boolean isH2 = response.version().major() == 2;
    containerResponse.getHeaders().forEach((k, vs) -> vs.forEach(v -> {
        headers.add(isH2 ? k.toLowerCase() : k, v == null ? emptyAsciiString() : asCharSequence(v));
    }));
    if (!headers.contains(CONTENT_LENGTH)) {
        if (contentLength == UNKNOWN_RESPONSE_LENGTH) {
            // We can omit Transfer-Encoding for HEAD per https://tools.ietf.org/html/rfc7231#section-4.3.2
            if (!isHeadRequest() && !HTTP_1_0.equals(protocolVersion)) {
                headers.set(TRANSFER_ENCODING, CHUNKED);
            }
        } else {
            headers.set(CONTENT_LENGTH, contentLength == 0 ? ZERO : Long.toString(contentLength));
            headers.removeIgnoreCase(TRANSFER_ENCODING, CHUNKED);
        }
    }
    responseSubscriber.onSuccess(response);
}
Also used : Buffer(io.servicetalk.buffer.api.Buffer) AtomicIntegerFieldUpdater(java.util.concurrent.atomic.AtomicIntegerFieldUpdater) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Publisher(io.servicetalk.concurrent.api.Publisher) Subscriber(io.servicetalk.concurrent.SingleSource.Subscriber) LoggerFactory(org.slf4j.LoggerFactory) HttpHeaders(io.servicetalk.http.api.HttpHeaders) Cancellable(io.servicetalk.concurrent.Cancellable) RequestProperties.getResponseExecutionStrategy(io.servicetalk.http.router.jersey.internal.RequestProperties.getResponseExecutionStrategy) ConnectableBufferOutputStream(io.servicetalk.concurrent.api.internal.ConnectableBufferOutputStream) RequestProperties.getResponseBufferPublisher(io.servicetalk.http.router.jersey.internal.RequestProperties.getResponseBufferPublisher) ContainerException(org.glassfish.jersey.server.ContainerException) ZERO(io.servicetalk.http.api.HttpHeaderValues.ZERO) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) IoThreadFactory(io.servicetalk.transport.api.IoThreadFactory) RequestProperties.getRequestCancellable(io.servicetalk.http.router.jersey.internal.RequestProperties.getRequestCancellable) Collectors.toMap(java.util.stream.Collectors.toMap) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy) HttpProtocolVersion(io.servicetalk.http.api.HttpProtocolVersion) CharSequences.emptyAsciiString(io.servicetalk.buffer.api.CharSequences.emptyAsciiString) AtomicIntegerFieldUpdater.newUpdater(java.util.concurrent.atomic.AtomicIntegerFieldUpdater.newUpdater) Status(javax.ws.rs.core.Response.Status) ContainerResponseWriter(org.glassfish.jersey.server.spi.ContainerResponseWriter) Nullable(javax.annotation.Nullable) CHUNKED(io.servicetalk.http.api.HttpHeaderValues.CHUNKED) OutputStream(java.io.OutputStream) Logger(org.slf4j.Logger) TRANSFER_ENCODING(io.servicetalk.http.api.HttpHeaderNames.TRANSFER_ENCODING) IOException(java.io.IOException) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) CONTENT_LENGTH(io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH) TimeUnit(java.util.concurrent.TimeUnit) StatusType(javax.ws.rs.core.Response.StatusType) ContainerResponse(org.glassfish.jersey.server.ContainerResponse) HEAD(javax.ws.rs.HttpMethod.HEAD) Buffer(io.servicetalk.buffer.api.Buffer) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) Function.identity(java.util.function.Function.identity) Collections.unmodifiableMap(java.util.Collections.unmodifiableMap) Arrays.stream(java.util.Arrays.stream) HttpResponseStatus(io.servicetalk.http.api.HttpResponseStatus) System.arraycopy(java.lang.System.arraycopy) HTTP_1_0(io.servicetalk.http.api.HttpProtocolVersion.HTTP_1_0) HttpHeaders(io.servicetalk.http.api.HttpHeaders) HttpResponseStatus(io.servicetalk.http.api.HttpResponseStatus) IoThreadFactory(io.servicetalk.transport.api.IoThreadFactory) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse)

Example 2 with ZERO

use of io.servicetalk.http.api.HttpHeaderValues.ZERO 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());
    serverCtx = HttpServers.forAddress(localAddress(0)).executionStrategy(offloadNever()).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());
    secureServerCtx = HttpServers.forAddress(localAddress(0)).sslConfig(new ServerSslConfigBuilder(DefaultTestCerts::loadServerPem, DefaultTestCerts::loadServerKey).build()).executionStrategy(offloadNever()).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) 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) HttpExecutionStrategies.offloadNever(io.servicetalk.http.api.HttpExecutionStrategies.offloadNever) 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)

Example 3 with ZERO

use of io.servicetalk.http.api.HttpHeaderValues.ZERO 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)

Aggregations

CONTENT_LENGTH (io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH)3 ZERO (io.servicetalk.http.api.HttpHeaderValues.ZERO)3 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)3 Completable.completed (io.servicetalk.concurrent.api.Completable.completed)2 Publisher (io.servicetalk.concurrent.api.Publisher)2 Single.succeeded (io.servicetalk.concurrent.api.Single.succeeded)2 HttpHeaders (io.servicetalk.http.api.HttpHeaders)2 HttpResponseStatus (io.servicetalk.http.api.HttpResponseStatus)2 OK (io.servicetalk.http.api.HttpResponseStatus.OK)2 StreamingHttpService (io.servicetalk.http.api.StreamingHttpService)2 HostAndPort (io.servicetalk.transport.api.HostAndPort)2 ServerContext (io.servicetalk.transport.api.ServerContext)2 AddressUtils.hostHeader (io.servicetalk.transport.netty.internal.AddressUtils.hostHeader)2 AddressUtils.localAddress (io.servicetalk.transport.netty.internal.AddressUtils.localAddress)2 AddressUtils.serverHostAndPort (io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort)2 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)2 Matchers.instanceOf (org.hamcrest.Matchers.instanceOf)2 Matchers.is (org.hamcrest.Matchers.is)2 AfterAll (org.junit.jupiter.api.AfterAll)2 Assertions.assertThrows (org.junit.jupiter.api.Assertions.assertThrows)2