Search in sources :

Example 16 with ResponseChannel

use of org.apache.hc.core5.http.nio.ResponseChannel in project httpcomponents-core by apache.

the class ReactiveFullDuplexServerExample method main.

public static void main(final String[] args) throws Exception {
    int port = 8080;
    if (args.length >= 1) {
        port = Integer.parseInt(args[0]);
    }
    final IOReactorConfig config = IOReactorConfig.custom().setSoTimeout(15, TimeUnit.SECONDS).setTcpNoDelay(true).build();
    final HttpAsyncServer server = AsyncServerBootstrap.bootstrap().setIOReactorConfig(config).setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
            System.out.println(connection.getRemoteAddress() + " " + new RequestLine(request));
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
            System.out.println(connection.getRemoteAddress() + " " + new StatusLine(response));
        }

        @Override
        public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
            if (keepAlive) {
                System.out.println(connection.getRemoteAddress() + " exchange completed (connection kept alive)");
            } else {
                System.out.println(connection.getRemoteAddress() + " exchange completed (connection closed)");
            }
        }
    }).register("/echo", () -> new ReactiveServerExchangeHandler((request, entityDetails, responseChannel, context, requestBody, responseBodyFuture) -> {
        if (new BasicHeader(HttpHeaders.EXPECT, HeaderElements.CONTINUE).equals(request.getHeader(HttpHeaders.EXPECT))) {
            responseChannel.sendInformation(new BasicHttpResponse(100), context);
        }
        responseChannel.sendResponse(new BasicHttpResponse(200), new BasicEntityDetails(-1, ContentType.APPLICATION_OCTET_STREAM), context);
        // Simply using the request publisher as the response publisher will
        // cause the server to echo the request body.
        responseBodyFuture.execute(requestBody);
    })).create();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        System.out.println("HTTP server shutting down");
        server.close(CloseMode.GRACEFUL);
    }));
    server.start();
    final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(port), URIScheme.HTTP);
    final ListenerEndpoint listenerEndpoint = future.get();
    System.out.print("Listening on " + listenerEndpoint.getAddress());
    server.awaitShutdown(TimeValue.ofDays(Long.MAX_VALUE));
}
Also used : HttpRequest(org.apache.hc.core5.http.HttpRequest) ReactiveServerExchangeHandler(org.apache.hc.core5.reactive.ReactiveServerExchangeHandler) HttpConnection(org.apache.hc.core5.http.HttpConnection) InetSocketAddress(java.net.InetSocketAddress) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) StatusLine(org.apache.hc.core5.http.message.StatusLine) RequestLine(org.apache.hc.core5.http.message.RequestLine) HttpAsyncServer(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) BasicEntityDetails(org.apache.hc.core5.http.impl.BasicEntityDetails) BasicHeader(org.apache.hc.core5.http.message.BasicHeader)

Example 17 with ResponseChannel

use of org.apache.hc.core5.http.nio.ResponseChannel in project httpcomponents-core by apache.

the class ServerPushH2StreamHandler method produceOutput.

@Override
public void produceOutput() throws HttpException, IOException {
    switch(responseState) {
        case IDLE:
            responseState = MessageState.HEADERS;
            pushProducer.produceResponse(new ResponseChannel() {

                @Override
                public void sendInformation(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException {
                    commitInformation(response);
                }

                @Override
                public void sendResponse(final HttpResponse response, final EntityDetails entityDetails, final HttpContext httpContext) throws HttpException, IOException {
                    commitResponse(response, entityDetails);
                }

                @Override
                public void pushPromise(final HttpRequest promise, final AsyncPushProducer pushProducer, final HttpContext httpContext) throws HttpException, IOException {
                    commitPromise(promise, pushProducer);
                }
            }, context);
            break;
        case BODY:
            pushProducer.produce(dataChannel);
            break;
    }
}
Also used : HttpRequest(org.apache.hc.core5.http.HttpRequest) EntityDetails(org.apache.hc.core5.http.EntityDetails) AsyncPushProducer(org.apache.hc.core5.http.nio.AsyncPushProducer) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) ResponseChannel(org.apache.hc.core5.http.nio.ResponseChannel)

Example 18 with ResponseChannel

use of org.apache.hc.core5.http.nio.ResponseChannel in project httpcomponents-core by apache.

the class ServerH2StreamHandler method consumeHeader.

@Override
public void consumeHeader(final List<Header> headers, final boolean endStream) throws HttpException, IOException {
    if (done.get()) {
        throw new ProtocolException("Unexpected message headers");
    }
    switch(requestState) {
        case HEADERS:
            requestState = endStream ? MessageState.COMPLETE : MessageState.BODY;
            final HttpRequest request = DefaultH2RequestConverter.INSTANCE.convert(headers);
            final EntityDetails requestEntityDetails = endStream ? null : new IncomingEntityDetails(request, -1);
            final AsyncServerExchangeHandler handler;
            try {
                handler = exchangeHandlerFactory != null ? exchangeHandlerFactory.create(request, context) : null;
            } catch (final ProtocolException ex) {
                throw new H2StreamResetException(H2Error.PROTOCOL_ERROR, ex.getMessage());
            }
            if (handler == null) {
                throw new H2StreamResetException(H2Error.REFUSED_STREAM, "Stream refused");
            }
            exchangeHandler = handler;
            context.setProtocolVersion(HttpVersion.HTTP_2);
            context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
            try {
                httpProcessor.process(request, requestEntityDetails, context);
                connMetrics.incrementRequestCount();
                receivedRequest = request;
                exchangeHandler.handleRequest(request, requestEntityDetails, responseChannel, context);
            } catch (final HttpException ex) {
                if (!responseCommitted.get()) {
                    final AsyncResponseProducer responseProducer = new BasicResponseProducer(ServerSupport.toStatusCode(ex), ServerSupport.toErrorMessage(ex));
                    exchangeHandler = new ImmediateResponseExchangeHandler(responseProducer);
                    exchangeHandler.handleRequest(request, requestEntityDetails, responseChannel, context);
                } else {
                    throw ex;
                }
            }
            break;
        case BODY:
            responseState = MessageState.COMPLETE;
            exchangeHandler.streamEnd(headers);
            break;
        default:
            throw new ProtocolException("Unexpected message headers");
    }
}
Also used : HttpRequest(org.apache.hc.core5.http.HttpRequest) AsyncResponseProducer(org.apache.hc.core5.http.nio.AsyncResponseProducer) ProtocolException(org.apache.hc.core5.http.ProtocolException) EntityDetails(org.apache.hc.core5.http.EntityDetails) IncomingEntityDetails(org.apache.hc.core5.http.impl.IncomingEntityDetails) H2StreamResetException(org.apache.hc.core5.http2.H2StreamResetException) IncomingEntityDetails(org.apache.hc.core5.http.impl.IncomingEntityDetails) HttpException(org.apache.hc.core5.http.HttpException) ImmediateResponseExchangeHandler(org.apache.hc.core5.http.nio.support.ImmediateResponseExchangeHandler) BasicResponseProducer(org.apache.hc.core5.http.nio.support.BasicResponseProducer) AsyncServerExchangeHandler(org.apache.hc.core5.http.nio.AsyncServerExchangeHandler)

Example 19 with ResponseChannel

use of org.apache.hc.core5.http.nio.ResponseChannel in project httpcomponents-core by apache.

the class ServerHttp1StreamHandler method consumeHeader.

void consumeHeader(final HttpRequest request, final EntityDetails requestEntityDetails) throws HttpException, IOException {
    if (done.get() || requestState != MessageState.HEADERS) {
        throw new ProtocolException("Unexpected message head");
    }
    receivedRequest = request;
    requestState = requestEntityDetails == null ? MessageState.COMPLETE : MessageState.BODY;
    AsyncServerExchangeHandler handler;
    try {
        handler = exchangeHandlerFactory.create(request, context);
    } catch (final MisdirectedRequestException ex) {
        handler = new ImmediateResponseExchangeHandler(HttpStatus.SC_MISDIRECTED_REQUEST, ex.getMessage());
    } catch (final HttpException ex) {
        handler = new ImmediateResponseExchangeHandler(HttpStatus.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
    }
    if (handler == null) {
        handler = new ImmediateResponseExchangeHandler(HttpStatus.SC_NOT_FOUND, "Cannot handle request");
    }
    exchangeHandler = handler;
    final ProtocolVersion transportVersion = request.getVersion();
    if (transportVersion != null && transportVersion.greaterEquals(HttpVersion.HTTP_2)) {
        throw new UnsupportedHttpVersionException(transportVersion);
    }
    context.setProtocolVersion(transportVersion != null ? transportVersion : HttpVersion.HTTP_1_1);
    context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
    try {
        httpProcessor.process(request, requestEntityDetails, context);
        exchangeHandler.handleRequest(request, requestEntityDetails, responseChannel, context);
    } catch (final HttpException ex) {
        if (!responseCommitted.get()) {
            final HttpResponse response = new BasicHttpResponse(ServerSupport.toStatusCode(ex));
            response.addHeader(HttpHeaders.CONNECTION, HeaderElements.CLOSE);
            final AsyncResponseProducer responseProducer = new BasicResponseProducer(response, ServerSupport.toErrorMessage(ex));
            exchangeHandler = new ImmediateResponseExchangeHandler(responseProducer);
            exchangeHandler.handleRequest(request, requestEntityDetails, responseChannel, context);
        } else {
            throw ex;
        }
    }
}
Also used : AsyncResponseProducer(org.apache.hc.core5.http.nio.AsyncResponseProducer) ProtocolException(org.apache.hc.core5.http.ProtocolException) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) HttpException(org.apache.hc.core5.http.HttpException) UnsupportedHttpVersionException(org.apache.hc.core5.http.UnsupportedHttpVersionException) ProtocolVersion(org.apache.hc.core5.http.ProtocolVersion) MisdirectedRequestException(org.apache.hc.core5.http.MisdirectedRequestException) ImmediateResponseExchangeHandler(org.apache.hc.core5.http.nio.support.ImmediateResponseExchangeHandler) BasicResponseProducer(org.apache.hc.core5.http.nio.support.BasicResponseProducer) AsyncServerExchangeHandler(org.apache.hc.core5.http.nio.AsyncServerExchangeHandler)

Aggregations

HttpResponse (org.apache.hc.core5.http.HttpResponse)15 BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)14 HttpException (org.apache.hc.core5.http.HttpException)12 EntityDetails (org.apache.hc.core5.http.EntityDetails)11 HttpRequest (org.apache.hc.core5.http.HttpRequest)11 IOException (java.io.IOException)10 AsyncServerExchangeHandler (org.apache.hc.core5.http.nio.AsyncServerExchangeHandler)10 ResponseChannel (org.apache.hc.core5.http.nio.ResponseChannel)9 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)9 ByteBuffer (java.nio.ByteBuffer)8 Header (org.apache.hc.core5.http.Header)8 ProtocolException (org.apache.hc.core5.http.ProtocolException)8 AsyncResponseProducer (org.apache.hc.core5.http.nio.AsyncResponseProducer)8 DataStreamChannel (org.apache.hc.core5.http.nio.DataStreamChannel)8 InetSocketAddress (java.net.InetSocketAddress)7 CapacityChannel (org.apache.hc.core5.http.nio.CapacityChannel)7 BasicResponseProducer (org.apache.hc.core5.http.nio.support.BasicResponseProducer)6 URISyntaxException (java.net.URISyntaxException)5 InterruptedIOException (java.io.InterruptedIOException)4 ExecutionException (java.util.concurrent.ExecutionException)4