Search in sources :

Example 6 with BasicHttpResponse

use of org.apache.hc.core5.http.message.BasicHttpResponse in project httpcomponents-core by apache.

the class H2FullDuplexServerExample 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 H2Config h2Config = H2Config.custom().setPushEnabled(true).setMaxConcurrentStreams(100).build();
    final HttpAsyncServer server = H2ServerBootstrap.bootstrap().setIOReactorConfig(config).setH2Config(h2Config).setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_2).setStreamListener(new H2StreamListener() {

        @Override
        public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
            for (int i = 0; i < headers.size(); i++) {
                System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
            }
        }

        @Override
        public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
            for (int i = 0; i < headers.size(); i++) {
                System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
            }
        }

        @Override
        public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) {
        }

        @Override
        public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) {
        }

        @Override
        public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
        }

        @Override
        public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
        }
    }).register("/echo", () -> new AsyncServerExchangeHandler() {

        ByteBuffer buffer = ByteBuffer.allocate(2048);

        CapacityChannel inputCapacityChannel;

        DataStreamChannel outputDataChannel;

        boolean endStream;

        private void ensureCapacity(final int chunk) {
            if (buffer.remaining() < chunk) {
                final ByteBuffer oldBuffer = buffer;
                oldBuffer.flip();
                buffer = ByteBuffer.allocate(oldBuffer.remaining() + (chunk > 2048 ? chunk : 2048));
                buffer.put(oldBuffer);
            }
        }

        @Override
        public void handleRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context) throws HttpException, IOException {
            final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_OK);
            responseChannel.sendResponse(response, entityDetails, context);
        }

        @Override
        public void consume(final ByteBuffer src) throws IOException {
            if (buffer.position() == 0) {
                if (outputDataChannel != null) {
                    outputDataChannel.write(src);
                }
            }
            if (src.hasRemaining()) {
                ensureCapacity(src.remaining());
                buffer.put(src);
                if (outputDataChannel != null) {
                    outputDataChannel.requestOutput();
                }
            }
        }

        @Override
        public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
            if (buffer.hasRemaining()) {
                capacityChannel.update(buffer.remaining());
                inputCapacityChannel = null;
            } else {
                inputCapacityChannel = capacityChannel;
            }
        }

        @Override
        public void streamEnd(final List<? extends Header> trailers) throws IOException {
            endStream = true;
            if (buffer.position() == 0) {
                if (outputDataChannel != null) {
                    outputDataChannel.endStream();
                }
            } else {
                if (outputDataChannel != null) {
                    outputDataChannel.requestOutput();
                }
            }
        }

        @Override
        public int available() {
            return buffer.position();
        }

        @Override
        public void produce(final DataStreamChannel channel) throws IOException {
            outputDataChannel = channel;
            buffer.flip();
            if (buffer.hasRemaining()) {
                channel.write(buffer);
            }
            buffer.compact();
            if (buffer.position() == 0 && endStream) {
                channel.endStream();
            }
            final CapacityChannel capacityChannel = inputCapacityChannel;
            if (capacityChannel != null && buffer.hasRemaining()) {
                capacityChannel.update(buffer.remaining());
            }
        }

        @Override
        public void failed(final Exception cause) {
            if (!(cause instanceof SocketException)) {
                cause.printStackTrace(System.out);
            }
        }

        @Override
        public void releaseResources() {
        }
    }).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 : SocketException(java.net.SocketException) HttpConnection(org.apache.hc.core5.http.HttpConnection) InetSocketAddress(java.net.InetSocketAddress) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) ResponseChannel(org.apache.hc.core5.http.nio.ResponseChannel) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) H2StreamListener(org.apache.hc.core5.http2.impl.nio.H2StreamListener) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) EntityDetails(org.apache.hc.core5.http.EntityDetails) List(java.util.List) AsyncServerExchangeHandler(org.apache.hc.core5.http.nio.AsyncServerExchangeHandler) HttpRequest(org.apache.hc.core5.http.HttpRequest) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) ByteBuffer(java.nio.ByteBuffer) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) SocketException(java.net.SocketException) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) HttpAsyncServer(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) Header(org.apache.hc.core5.http.Header) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) RawFrame(org.apache.hc.core5.http2.frame.RawFrame) H2Config(org.apache.hc.core5.http2.config.H2Config)

Example 7 with BasicHttpResponse

use of org.apache.hc.core5.http.message.BasicHttpResponse in project httpcomponents-core by apache.

the class Http1IntegrationTest method testExpectationFailedCloseConnection.

@Test
public void testExpectationFailedCloseConnection() throws Exception {
    server.register("*", () -> new MessageExchangeHandler<String>(new StringAsyncEntityConsumer()) {

        @Override
        protected void handle(final Message<HttpRequest, String> request, final AsyncServerRequestHandler.ResponseTrigger responseTrigger, final HttpContext context) throws IOException, HttpException {
            responseTrigger.submitResponse(new BasicResponseProducer(HttpStatus.SC_OK, "All is well"), context);
        }
    });
    final InetSocketAddress serverEndpoint = server.start(null, handler -> new BasicAsyncServerExpectationDecorator(handler) {

        @Override
        protected AsyncResponseProducer verify(final HttpRequest request, final HttpContext context) throws IOException, HttpException {
            final Header h = request.getFirstHeader("password");
            if (h != null && "secret".equals(h.getValue())) {
                return null;
            } else {
                final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_UNAUTHORIZED);
                response.addHeader(HttpHeaders.CONNECTION, HeaderElements.CLOSE);
                return new BasicResponseProducer(response, "You shall not pass");
            }
        }
    }, Http1Config.DEFAULT);
    client.start();
    final Future<IOSession> sessionFuture = client.requestSession(new HttpHost("localhost", serverEndpoint.getPort()), TIMEOUT, null);
    final IOSession ioSession = sessionFuture.get();
    final ClientSessionEndpoint streamEndpoint = new ClientSessionEndpoint(ioSession);
    final HttpRequest request1 = new BasicHttpRequest(Method.POST, createRequestURI(serverEndpoint, "/echo"));
    final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(new BasicRequestProducer(request1, new MultiBinEntityProducer(new byte[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }, 100000, ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
    final Message<HttpResponse, String> result1 = future1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
    Assertions.assertNotNull(result1);
    final HttpResponse response1 = result1.getHead();
    Assertions.assertNotNull(response1);
    Assertions.assertEquals(HttpStatus.SC_UNAUTHORIZED, response1.getCode());
    Assertions.assertNotNull("You shall not pass", result1.getBody());
    Assertions.assertFalse(streamEndpoint.isOpen());
}
Also used : BasicAsyncServerExpectationDecorator(org.apache.hc.core5.http.nio.support.BasicAsyncServerExpectationDecorator) Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) AsyncResponseProducer(org.apache.hc.core5.http.nio.AsyncResponseProducer) HttpHost(org.apache.hc.core5.http.HttpHost) ProtocolIOSession(org.apache.hc.core5.reactor.ProtocolIOSession) IOSession(org.apache.hc.core5.reactor.IOSession) HttpException(org.apache.hc.core5.http.HttpException) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) AsyncServerRequestHandler(org.apache.hc.core5.http.nio.AsyncServerRequestHandler) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) Header(org.apache.hc.core5.http.Header) BasicResponseProducer(org.apache.hc.core5.http.nio.support.BasicResponseProducer) Test(org.junit.Test)

Example 8 with BasicHttpResponse

use of org.apache.hc.core5.http.message.BasicHttpResponse in project httpcomponents-core by apache.

the class Http1IntegrationTest method testDelayedExpectationVerification.

@Test
public void testDelayedExpectationVerification() throws Exception {
    server.register("*", () -> new AsyncServerExchangeHandler() {

        private final Random random = new Random(System.currentTimeMillis());

        private final AsyncEntityProducer entityProducer = AsyncEntityProducers.create("All is well");

        @Override
        public void handleRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context) throws HttpException, IOException {
            Executors.newSingleThreadExecutor().execute(() -> {
                try {
                    if (entityDetails != null) {
                        final Header h = request.getFirstHeader(HttpHeaders.EXPECT);
                        if (h != null && HeaderElements.CONTINUE.equalsIgnoreCase(h.getValue())) {
                            Thread.sleep(random.nextInt(1000));
                            responseChannel.sendInformation(new BasicHttpResponse(HttpStatus.SC_CONTINUE), context);
                        }
                        final HttpResponse response = new BasicHttpResponse(200);
                        synchronized (entityProducer) {
                            responseChannel.sendResponse(response, entityProducer, context);
                        }
                    }
                } catch (final Exception ignore) {
                // ignore
                }
            });
        }

        @Override
        public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
            capacityChannel.update(Integer.MAX_VALUE);
        }

        @Override
        public void consume(final ByteBuffer src) throws IOException {
        }

        @Override
        public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
        }

        @Override
        public int available() {
            synchronized (entityProducer) {
                return entityProducer.available();
            }
        }

        @Override
        public void produce(final DataStreamChannel channel) throws IOException {
            synchronized (entityProducer) {
                entityProducer.produce(channel);
            }
        }

        @Override
        public void failed(final Exception cause) {
        }

        @Override
        public void releaseResources() {
        }
    });
    final InetSocketAddress serverEndpoint = server.start();
    client.start(Http1Config.custom().setWaitForContinueTimeout(Timeout.ofMilliseconds(100)).build());
    final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
    final ClientSessionEndpoint streamEndpoint = connectFuture.get();
    final Queue<Future<Message<HttpResponse, String>>> queue = new LinkedList<>();
    for (int i = 0; i < 5; i++) {
        queue.add(streamEndpoint.execute(new BasicRequestProducer(Method.POST, createRequestURI(serverEndpoint, "/"), AsyncEntityProducers.create("Some important message")), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null));
    }
    while (!queue.isEmpty()) {
        final Future<Message<HttpResponse, String>> future = queue.remove();
        final Message<HttpResponse, String> result = future.get(LONG_TIMEOUT.getDuration(), LONG_TIMEOUT.getTimeUnit());
        Assertions.assertNotNull(result);
        final HttpResponse response = result.getHead();
        Assertions.assertNotNull(response);
        Assertions.assertEquals(200, response.getCode());
        Assertions.assertNotNull("All is well", result.getBody());
    }
}
Also used : Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) ResponseChannel(org.apache.hc.core5.http.nio.ResponseChannel) Random(java.util.Random) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) EntityDetails(org.apache.hc.core5.http.EntityDetails) BasicResponseConsumer(org.apache.hc.core5.http.nio.support.BasicResponseConsumer) HttpException(org.apache.hc.core5.http.HttpException) AsyncServerExchangeHandler(org.apache.hc.core5.http.nio.AsyncServerExchangeHandler) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) CancellationException(java.util.concurrent.CancellationException) MalformedChunkCodingException(org.apache.hc.core5.http.MalformedChunkCodingException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) URISyntaxException(java.net.URISyntaxException) HttpException(org.apache.hc.core5.http.HttpException) ProtocolException(org.apache.hc.core5.http.ProtocolException) LinkedList(java.util.LinkedList) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) AsyncEntityProducer(org.apache.hc.core5.http.nio.AsyncEntityProducer) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) Header(org.apache.hc.core5.http.Header) Future(java.util.concurrent.Future) Test(org.junit.Test)

Example 9 with BasicHttpResponse

use of org.apache.hc.core5.http.message.BasicHttpResponse in project httpcomponents-core by apache.

the class Http1IntegrationTest method testResponseNoContent.

@Test
public void testResponseNoContent() throws Exception {
    server.register("/hello", () -> new SingleLineResponseHandler("Hi there") {

        @Override
        protected void handle(final Message<HttpRequest, String> request, final AsyncServerRequestHandler.ResponseTrigger responseTrigger, final HttpContext context) throws IOException, HttpException {
            final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_NO_CONTENT);
            responseTrigger.submitResponse(new BasicResponseProducer(response), context);
        }
    });
    final InetSocketAddress serverEndpoint = server.start();
    client.start();
    final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
    final ClientSessionEndpoint streamEndpoint = connectFuture.get();
    final Future<Message<HttpResponse, String>> future = streamEndpoint.execute(new BasicRequestProducer(Method.GET, createRequestURI(serverEndpoint, "/hello")), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
    final Message<HttpResponse, String> result = future.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
    Assertions.assertNotNull(result);
    final HttpResponse response1 = result.getHead();
    Assertions.assertNotNull(response1);
    Assertions.assertEquals(204, response1.getCode());
    Assertions.assertNull(result.getBody());
}
Also used : BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) AsyncServerRequestHandler(org.apache.hc.core5.http.nio.AsyncServerRequestHandler) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) HttpException(org.apache.hc.core5.http.HttpException) BasicResponseProducer(org.apache.hc.core5.http.nio.support.BasicResponseProducer) Test(org.junit.Test)

Example 10 with BasicHttpResponse

use of org.apache.hc.core5.http.message.BasicHttpResponse in project httpcomponents-core by apache.

the class HttpResponseWrapperTest method testSetResponseStatus.

@Test
void testSetResponseStatus() {
    final HttpResponse response1 = new BasicHttpResponse(200, "OK");
    final HttpResponseWrapper httpResponseWrapper1 = new HttpResponseWrapper(response1);
    Assertions.assertNotNull(httpResponseWrapper1.getCode());
    Assertions.assertEquals(200, httpResponseWrapper1.getCode());
    final HttpResponse response2 = new BasicHttpResponse(HttpStatus.SC_BAD_REQUEST, "Bad Request");
    final HttpResponseWrapper httpResponseWrapper2 = new HttpResponseWrapper(response2);
    Assertions.assertEquals(HttpStatus.SC_BAD_REQUEST, httpResponseWrapper2.getCode());
    final HttpResponse response3 = new BasicHttpResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "whatever");
    final HttpResponseWrapper httpResponseWrapper3 = new HttpResponseWrapper(response3);
    Assertions.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, httpResponseWrapper3.getCode());
    Assertions.assertEquals("whatever", httpResponseWrapper3.getReasonPhrase());
    final HttpResponse response4 = new BasicHttpResponse(HttpStatus.SC_OK, "OK");
    final HttpResponseWrapper httpResponseWrapper4 = new HttpResponseWrapper(response4);
    Assertions.assertThrows(IllegalArgumentException.class, () -> httpResponseWrapper4.setCode(-23));
}
Also used : HttpResponse(org.apache.hc.core5.http.HttpResponse) Test(org.junit.jupiter.api.Test)

Aggregations

BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)60 HttpResponse (org.apache.hc.core5.http.HttpResponse)57 Test (org.junit.jupiter.api.Test)40 HttpRequest (org.apache.hc.core5.http.HttpRequest)15 Header (org.apache.hc.core5.http.Header)14 HttpException (org.apache.hc.core5.http.HttpException)11 IOException (java.io.IOException)10 BasicHttpRequest (org.apache.hc.core5.http.message.BasicHttpRequest)9 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)9 InetSocketAddress (java.net.InetSocketAddress)8 EntityDetails (org.apache.hc.core5.http.EntityDetails)8 ByteBuffer (java.nio.ByteBuffer)7 BasicHeader (org.apache.hc.core5.http.message.BasicHeader)7 Test (org.junit.Test)7 ProtocolException (org.apache.hc.core5.http.ProtocolException)6 AsyncEntityProducer (org.apache.hc.core5.http.nio.AsyncEntityProducer)6 AsyncServerExchangeHandler (org.apache.hc.core5.http.nio.AsyncServerExchangeHandler)6 Message (org.apache.hc.core5.http.Message)5 CapacityChannel (org.apache.hc.core5.http.nio.CapacityChannel)5 DataStreamChannel (org.apache.hc.core5.http.nio.DataStreamChannel)5