Search in sources :

Example 86 with StreamingHttpRequest

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

the class DefaultJerseyStreamingHttpRouter method handle0.

private void handle0(final HttpServiceContext serviceCtx, final StreamingHttpRequest req, final StreamingHttpResponseFactory factory, final Subscriber<? super StreamingHttpResponse> subscriber, final DelayedCancellable delayedCancellable) {
    final CharSequence baseUri = baseUriFunction.apply(serviceCtx, req);
    final CharSequence requestTarget = req.requestTarget();
    final StringBuilder requestUriBuilder = new StringBuilder(baseUri.length() + requestTarget.length()).append(baseUri);
    // Jersey expects the baseUri ends in a '/' and if not will return 404s
    assert baseUri.length() == 0 || baseUri.charAt(baseUri.length() - 1) == '/';
    if (requestTarget.length() > 0 && requestTarget.charAt(0) == '/') {
        requestUriBuilder.append(requestTarget, 1, requestTarget.length());
    } else {
        requestUriBuilder.append(requestTarget);
    }
    final URI baseURI;
    final URI requestURI;
    try {
        baseURI = URI.create(baseUri.toString());
        requestURI = URI.create(requestUriBuilder.toString());
    } catch (IllegalArgumentException cause) {
        Buffer message = serviceCtx.executionContext().bufferAllocator().fromAscii(cause.getMessage());
        StreamingHttpResponse response = factory.badRequest().payloadBody(from(message));
        response.headers().set(CONTENT_LENGTH, Integer.toString(message.readableBytes()));
        response.headers().set(CONTENT_TYPE, TEXT_PLAIN);
        subscriber.onSuccess(response);
        return;
    }
    final ContainerRequest containerRequest = new CloseSignalHandoffAbleContainerRequest(baseURI, requestURI, req.method().name(), UNAUTHENTICATED_SECURITY_CONTEXT, new MapPropertiesDelegate(), new ResourceConfig());
    req.headers().forEach(h -> containerRequest.getHeaders().add(h.getKey().toString(), h.getValue().toString()));
    final BufferPublisherInputStream entityStream = new BufferPublisherInputStream(req.payloadBody(), publisherInputStreamQueueCapacity);
    containerRequest.setEntityStream(entityStream);
    initRequestProperties(entityStream, containerRequest);
    final DefaultContainerResponseWriter responseWriter = new DefaultContainerResponseWriter(containerRequest, req.version(), serviceCtx, factory, subscriber);
    containerRequest.setWriter(responseWriter);
    containerRequest.setRequestScopedInitializer(injectionManager -> {
        injectionManager.<Ref<ConnectionContext>>getInstance(CONNECTION_CONTEXT_REF_TYPE).set(serviceCtx);
        injectionManager.<Ref<StreamingHttpRequest>>getInstance(HTTP_REQUEST_REF_TYPE).set(req);
    });
    delayedCancellable.delayedCancellable(responseWriter::dispose);
    applicationHandler.handle(containerRequest);
}
Also used : Buffer(io.servicetalk.buffer.api.Buffer) BufferPublisherInputStream(io.servicetalk.http.router.jersey.internal.BufferPublisherInputStream) URI(java.net.URI) MapPropertiesDelegate(org.glassfish.jersey.internal.MapPropertiesDelegate) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) ConnectionContext(io.servicetalk.transport.api.ConnectionContext) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse)

Example 87 with StreamingHttpRequest

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

the class TestServiceStreaming method handle.

@Override
public Single<StreamingHttpResponse> handle(final HttpServiceContext context, final StreamingHttpRequest req, final StreamingHttpResponseFactory factory) {
    LOGGER.debug("({}) Handling {}", counter, req.toString((a, b) -> b));
    final StreamingHttpResponse response;
    switch(req.path()) {
        case SVC_ECHO:
            response = newEchoResponse(req, factory);
            break;
        case SVC_COUNTER_NO_LAST_CHUNK:
            response = newTestCounterResponse(context, req, factory);
            break;
        case SVC_COUNTER:
            response = newTestCounterResponseWithLastPayloadChunk(context, req, factory);
            break;
        case SVC_LARGE_LAST:
            response = newLargeLastChunkResponse(context, req, factory);
            break;
        case SVC_TEST_PUBLISHER:
            response = newTestPublisherResponse(req, factory);
            break;
        case SVC_NO_CONTENT:
            response = newNoContentResponse(req, factory);
            break;
        case SVC_NO_CONTENT_AFTER_READ:
            return req.payloadBody().ignoreElements().concat(succeeded(newNoContentResponse(req, factory)));
        case SVC_ROT13:
            response = newRot13Response(req, factory);
            break;
        case SVC_NEVER:
            return req.payloadBody().ignoreElements().concat(never());
        case SVC_THROW_ERROR:
            response = throwErrorSynchronously();
            break;
        case SVC_SINGLE_ERROR:
            return Single.failed(DELIBERATE_EXCEPTION);
        case SVC_ERROR_BEFORE_READ:
            response = throwErrorBeforeRead(req, factory);
            break;
        case SVC_ERROR_DURING_READ:
            response = throwErrorDuringRead(req, factory);
            break;
        default:
            response = newNotFoundResponse(req, factory);
    }
    return succeeded(response);
}
Also used : StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Publisher(io.servicetalk.concurrent.api.Publisher) LoggerFactory(org.slf4j.LoggerFactory) CONTENT_TYPE(io.servicetalk.http.api.HttpHeaderNames.CONTENT_TYPE) Publisher.empty(io.servicetalk.concurrent.api.Publisher.empty) Function(java.util.function.Function) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) Publisher.from(io.servicetalk.concurrent.api.Publisher.from) DELIBERATE_EXCEPTION(io.servicetalk.concurrent.internal.DeliberateException.DELIBERATE_EXCEPTION) ConnectionContext(io.servicetalk.transport.api.ConnectionContext) Logger(org.slf4j.Logger) Single(io.servicetalk.concurrent.api.Single) Completable(io.servicetalk.concurrent.api.Completable) NO_CONTENT(io.servicetalk.http.api.HttpResponseStatus.NO_CONTENT) TRANSFER_ENCODING(io.servicetalk.http.api.HttpHeaderNames.TRANSFER_ENCODING) StatelessTrailersTransformer(io.servicetalk.http.api.StatelessTrailersTransformer) CONTENT_LENGTH(io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH) Single.never(io.servicetalk.concurrent.api.Single.never) Buffer(io.servicetalk.buffer.api.Buffer) String.valueOf(java.lang.String.valueOf) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) NOT_FOUND(io.servicetalk.http.api.HttpResponseStatus.NOT_FOUND) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse)

Example 88 with StreamingHttpRequest

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

the class TestServiceStreaming method newEchoResponse.

private static StreamingHttpResponse newEchoResponse(final StreamingHttpRequest req, final StreamingHttpResponseFactory factory) {
    final StreamingHttpResponse response = factory.ok().version(req.version()).transformMessageBody(pub -> pub.ignoreElements().merge(req.messageBody())).transform(new StatelessTrailersTransformer<>());
    final CharSequence contentLength = req.headers().get(CONTENT_LENGTH);
    if (contentLength != null) {
        response.addHeader(CONTENT_LENGTH, contentLength);
    }
    final CharSequence contentType = req.headers().get(CONTENT_TYPE);
    if (contentType != null) {
        response.addHeader(CONTENT_TYPE, contentType);
    }
    final CharSequence transferEncoding = req.headers().get(TRANSFER_ENCODING);
    if (transferEncoding != null) {
        response.addHeader(TRANSFER_ENCODING, transferEncoding);
    }
    return response;
}
Also used : StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Publisher(io.servicetalk.concurrent.api.Publisher) LoggerFactory(org.slf4j.LoggerFactory) CONTENT_TYPE(io.servicetalk.http.api.HttpHeaderNames.CONTENT_TYPE) Publisher.empty(io.servicetalk.concurrent.api.Publisher.empty) Function(java.util.function.Function) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) Publisher.from(io.servicetalk.concurrent.api.Publisher.from) DELIBERATE_EXCEPTION(io.servicetalk.concurrent.internal.DeliberateException.DELIBERATE_EXCEPTION) ConnectionContext(io.servicetalk.transport.api.ConnectionContext) Logger(org.slf4j.Logger) Single(io.servicetalk.concurrent.api.Single) Completable(io.servicetalk.concurrent.api.Completable) NO_CONTENT(io.servicetalk.http.api.HttpResponseStatus.NO_CONTENT) TRANSFER_ENCODING(io.servicetalk.http.api.HttpHeaderNames.TRANSFER_ENCODING) StatelessTrailersTransformer(io.servicetalk.http.api.StatelessTrailersTransformer) CONTENT_LENGTH(io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH) Single.never(io.servicetalk.concurrent.api.Single.never) Buffer(io.servicetalk.buffer.api.Buffer) String.valueOf(java.lang.String.valueOf) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) NOT_FOUND(io.servicetalk.http.api.HttpResponseStatus.NOT_FOUND) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse)

Example 89 with StreamingHttpRequest

use of io.servicetalk.http.api.StreamingHttpRequest 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 90 with StreamingHttpRequest

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

the class ContentLengthTest method shouldCalculateRequestContentLengthFromSingleItemPublisher.

@Test
void shouldCalculateRequestContentLengthFromSingleItemPublisher() throws Exception {
    StreamingHttpRequest request = newAggregatedRequest().toStreamingRequest().payloadBody(from("Hello"), appSerializerUtf8FixLen());
    setRequestContentLengthAndVerify(request, contentEqualTo("9"));
}
Also used : StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) Test(org.junit.jupiter.api.Test)

Aggregations

StreamingHttpRequest (io.servicetalk.http.api.StreamingHttpRequest)169 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)84 Test (org.junit.jupiter.api.Test)82 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)66 MethodSource (org.junit.jupiter.params.provider.MethodSource)47 Single (io.servicetalk.concurrent.api.Single)35 Buffer (io.servicetalk.buffer.api.Buffer)33 StreamingHttpClient (io.servicetalk.http.api.StreamingHttpClient)32 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)25 HttpServiceContext (io.servicetalk.http.api.HttpServiceContext)23 StreamingHttpResponseFactory (io.servicetalk.http.api.StreamingHttpResponseFactory)23 Nullable (javax.annotation.Nullable)22 InetSocketAddress (java.net.InetSocketAddress)21 OK (io.servicetalk.http.api.HttpResponseStatus.OK)20 StreamingHttpServiceFilter (io.servicetalk.http.api.StreamingHttpServiceFilter)19 CountDownLatch (java.util.concurrent.CountDownLatch)19 Single.succeeded (io.servicetalk.concurrent.api.Single.succeeded)18 HttpHeaders (io.servicetalk.http.api.HttpHeaders)17 ServerContext (io.servicetalk.transport.api.ServerContext)17 AddressUtils.localAddress (io.servicetalk.transport.netty.internal.AddressUtils.localAddress)17