Search in sources :

Example 1 with BasicEntityDetails

use of org.apache.hc.core5.http.impl.BasicEntityDetails in project httpcomponents-core by apache.

the class ReactiveEchoProcessor method processRequest.

@Override
public void processRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context, final Publisher<ByteBuffer> requestBody, final Callback<Publisher<ByteBuffer>> responseBodyFuture) throws HttpException, IOException {
    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);
    responseBodyFuture.execute(requestBody);
}
Also used : BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) BasicEntityDetails(org.apache.hc.core5.http.impl.BasicEntityDetails) BasicHeader(org.apache.hc.core5.http.message.BasicHeader)

Example 2 with BasicEntityDetails

use of org.apache.hc.core5.http.impl.BasicEntityDetails in project httpcomponents-core by apache.

the class ReactiveRandomProcessor method processRequest.

@Override
public void processRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context, final Publisher<ByteBuffer> requestBody, final Callback<Publisher<ByteBuffer>> responseBodyCallback) throws HttpException, IOException {
    final String method = request.getMethod();
    if (!"GET".equalsIgnoreCase(method) && !"HEAD".equalsIgnoreCase(method) && !"POST".equalsIgnoreCase(method) && !"PUT".equalsIgnoreCase(method)) {
        throw new MethodNotSupportedException(method + " not supported by " + getClass().getName());
    }
    final URI uri;
    try {
        uri = request.getUri();
    } catch (final URISyntaxException ex) {
        throw new ProtocolException(ex.getMessage(), ex);
    }
    final String path = uri.getPath();
    final int slash = path.lastIndexOf('/');
    if (slash != -1) {
        final String payload = path.substring(slash + 1);
        final long n;
        if (!payload.isEmpty()) {
            try {
                n = Long.parseLong(payload);
            } catch (final NumberFormatException ex) {
                throw new ProtocolException("Invalid request path: " + path);
            }
        } else {
            // random length, but make sure at least something is sent
            n = 1 + (int) (Math.random() * 79.0);
        }
        if (new BasicHeader(HttpHeaders.EXPECT, HeaderElements.CONTINUE).equals(request.getHeader(HttpHeaders.EXPECT))) {
            responseChannel.sendInformation(new BasicHttpResponse(100), context);
        }
        final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_OK);
        final Flowable<ByteBuffer> stream = ReactiveTestUtils.produceStream(n);
        final String hash = ReactiveTestUtils.getStreamHash(n);
        response.addHeader("response-hash-code", hash);
        final BasicEntityDetails basicEntityDetails = new BasicEntityDetails(n, ContentType.APPLICATION_OCTET_STREAM);
        responseChannel.sendResponse(response, basicEntityDetails, context);
        responseBodyCallback.execute(stream);
    } else {
        throw new ProtocolException("Invalid request path: " + path);
    }
}
Also used : ProtocolException(org.apache.hc.core5.http.ProtocolException) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) ByteBuffer(java.nio.ByteBuffer) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) MethodNotSupportedException(org.apache.hc.core5.http.MethodNotSupportedException) BasicEntityDetails(org.apache.hc.core5.http.impl.BasicEntityDetails) BasicHeader(org.apache.hc.core5.http.message.BasicHeader)

Example 3 with BasicEntityDetails

use of org.apache.hc.core5.http.impl.BasicEntityDetails in project httpcomponents-core by apache.

the class TestAbstractBinAsyncEntityConsumer method testConsumeData.

@Test
public void testConsumeData() throws Exception {
    final AsyncEntityConsumer<byte[]> consumer = new ByteArrayAsyncEntityConsumer();
    final AtomicLong count = new AtomicLong(0);
    consumer.streamStart(new BasicEntityDetails(-1, ContentType.APPLICATION_OCTET_STREAM), new FutureCallback<byte[]>() {

        @Override
        public void completed(final byte[] result) {
            count.incrementAndGet();
        }

        @Override
        public void failed(final Exception ex) {
            count.incrementAndGet();
        }

        @Override
        public void cancelled() {
            count.incrementAndGet();
        }
    });
    consumer.consume(ByteBuffer.wrap(new byte[] { '1', '2', '3' }));
    consumer.consume(ByteBuffer.wrap(new byte[] { '4', '5' }));
    consumer.consume(ByteBuffer.wrap(new byte[] {}));
    Assertions.assertNull(consumer.getContent());
    consumer.streamEnd(null);
    Assertions.assertArrayEquals(new byte[] { '1', '2', '3', '4', '5' }, consumer.getContent());
    Assertions.assertEquals(1L, count.longValue());
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) BasicEntityDetails(org.apache.hc.core5.http.impl.BasicEntityDetails) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) Test(org.junit.jupiter.api.Test)

Example 4 with BasicEntityDetails

use of org.apache.hc.core5.http.impl.BasicEntityDetails in project httpcomponents-core by apache.

the class TestAbstractCharAsyncEntityConsumer method testConsumeData.

@Test
public void testConsumeData() throws Exception {
    final AsyncEntityConsumer<String> consumer = new StringBuilderAsyncEntityConsumer();
    final AtomicLong count = new AtomicLong(0);
    consumer.streamStart(new BasicEntityDetails(-1, ContentType.TEXT_PLAIN), new FutureCallback<String>() {

        @Override
        public void completed(final String result) {
            count.incrementAndGet();
        }

        @Override
        public void failed(final Exception ex) {
            count.incrementAndGet();
        }

        @Override
        public void cancelled() {
            count.incrementAndGet();
        }
    });
    consumer.consume(ByteBuffer.wrap(new byte[] { '1', '2', '3' }));
    consumer.consume(ByteBuffer.wrap(new byte[] { '4', '5' }));
    consumer.consume(ByteBuffer.wrap(new byte[] {}));
    Assertions.assertNull(consumer.getContent());
    consumer.streamEnd(null);
    Assertions.assertEquals("12345", consumer.getContent());
    Assertions.assertEquals(1L, count.longValue());
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) BasicEntityDetails(org.apache.hc.core5.http.impl.BasicEntityDetails) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) Test(org.junit.jupiter.api.Test)

Example 5 with BasicEntityDetails

use of org.apache.hc.core5.http.impl.BasicEntityDetails 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)

Aggregations

BasicEntityDetails (org.apache.hc.core5.http.impl.BasicEntityDetails)6 BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)4 IOException (java.io.IOException)3 AtomicLong (java.util.concurrent.atomic.AtomicLong)3 HttpException (org.apache.hc.core5.http.HttpException)3 HttpResponse (org.apache.hc.core5.http.HttpResponse)3 BasicHeader (org.apache.hc.core5.http.message.BasicHeader)3 ByteBuffer (java.nio.ByteBuffer)2 HttpRequest (org.apache.hc.core5.http.HttpRequest)2 StatusLine (org.apache.hc.core5.http.message.StatusLine)2 IOReactorConfig (org.apache.hc.core5.reactor.IOReactorConfig)2 Test (org.junit.jupiter.api.Test)2 InetSocketAddress (java.net.InetSocketAddress)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 AsyncExecCallback (org.apache.hc.client5.http.async.AsyncExecCallback)1 AsyncExecChain (org.apache.hc.client5.http.async.AsyncExecChain)1 AsyncExecChainHandler (org.apache.hc.client5.http.async.AsyncExecChainHandler)1 SimpleHttpRequest (org.apache.hc.client5.http.async.methods.SimpleHttpRequest)1 SimpleHttpResponse (org.apache.hc.client5.http.async.methods.SimpleHttpResponse)1