Search in sources :

Example 51 with HttpCoreContext

use of org.apache.hc.core5.http.protocol.HttpCoreContext in project httpcomponents-core by apache.

the class TestHttpRequestExecutor method testExecutionEntityEnclosingRequestWithExpectContinueMultiple1xxResponses.

@Test
public void testExecutionEntityEnclosingRequestWithExpectContinueMultiple1xxResponses() throws Exception {
    final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class);
    final HttpClientConnection conn = Mockito.mock(HttpClientConnection.class);
    final HttpRequestExecutor executor = new HttpRequestExecutor();
    final HttpCoreContext context = HttpCoreContext.create();
    final ClassicHttpRequest request = new BasicClassicHttpRequest(Method.POST, "/");
    request.addHeader(HttpHeaders.EXPECT, HeaderElements.CONTINUE);
    final HttpEntity entity = Mockito.mock(HttpEntity.class);
    request.setEntity(entity);
    executor.preProcess(request, httprocessor, context);
    Mockito.verify(httprocessor).process(request, request.getEntity(), context);
    Mockito.when(conn.receiveResponseHeader()).thenReturn(new BasicClassicHttpResponse(110, "Huh?"), new BasicClassicHttpResponse(100, "Continue"), new BasicClassicHttpResponse(111, "Huh?"), new BasicClassicHttpResponse(200, "OK"));
    Mockito.when(conn.isDataAvailable(ArgumentMatchers.any(Timeout.class))).thenReturn(Boolean.TRUE);
    final HttpResponseInformationCallback callback = Mockito.mock(HttpResponseInformationCallback.class);
    final ClassicHttpResponse response = executor.execute(request, conn, callback, context);
    Mockito.verify(conn).sendRequestHeader(request);
    Mockito.verify(conn).sendRequestEntity(request);
    Mockito.verify(conn, Mockito.times(2)).flush();
    Mockito.verify(conn, Mockito.times(2)).isDataAvailable(Timeout.ofMilliseconds(3000));
    Mockito.verify(conn, Mockito.times(4)).receiveResponseHeader();
    Mockito.verify(conn).receiveResponseEntity(response);
    final ArgumentCaptor<HttpResponse> responseCaptor = ArgumentCaptor.forClass(HttpResponse.class);
    Mockito.verify(callback, Mockito.times(2)).execute(responseCaptor.capture(), ArgumentMatchers.eq(conn), ArgumentMatchers.eq(context));
    final List<HttpResponse> infos = responseCaptor.getAllValues();
    Assertions.assertNotNull(infos);
    Assertions.assertEquals(2, infos.size());
    final HttpResponse info1 = infos.get(0);
    Assertions.assertNotNull(info1);
    Assertions.assertEquals(110, info1.getCode());
    final HttpResponse info2 = infos.get(1);
    Assertions.assertNotNull(info2);
    Assertions.assertEquals(111, info2.getCode());
    executor.postProcess(response, httprocessor, context);
    Mockito.verify(httprocessor).process(response, response.getEntity(), context);
}
Also used : BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpEntity(org.apache.hc.core5.http.HttpEntity) HttpProcessor(org.apache.hc.core5.http.protocol.HttpProcessor) HttpClientConnection(org.apache.hc.core5.http.io.HttpClientConnection) Timeout(org.apache.hc.core5.util.Timeout) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) HttpResponseInformationCallback(org.apache.hc.core5.http.io.HttpResponseInformationCallback) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) Test(org.junit.jupiter.api.Test)

Example 52 with HttpCoreContext

use of org.apache.hc.core5.http.protocol.HttpCoreContext in project httpcomponents-core by apache.

the class TestHttpService method testExecutionEntityEnclosingRequestWithExpectContinue.

@Test
public void testExecutionEntityEnclosingRequestWithExpectContinue() throws Exception {
    final HttpCoreContext context = HttpCoreContext.create();
    final ClassicHttpRequest request = new BasicClassicHttpRequest(Method.POST, "/");
    request.addHeader(HttpHeaders.EXPECT, HeaderElements.CONTINUE);
    final InputStream inStream = Mockito.mock(InputStream.class);
    final InputStreamEntity entity = new InputStreamEntity(inStream, -1, null);
    request.setEntity(entity);
    Mockito.when(conn.receiveRequestHeader()).thenReturn(request);
    Mockito.when(responseFactory.newHttpResponse(200)).thenReturn(response);
    Mockito.when(connReuseStrategy.keepAlive(ArgumentMatchers.eq(request), ArgumentMatchers.argThat(errorResponse -> errorResponse.getCode() == HttpStatus.SC_NOT_IMPLEMENTED), ArgumentMatchers.eq(context))).thenReturn(Boolean.TRUE);
    httpservice.handleRequest(conn, context);
    final ArgumentCaptor<ClassicHttpResponse> responseCaptor = ArgumentCaptor.forClass(ClassicHttpResponse.class);
    Mockito.verify(conn, Mockito.times(2)).sendResponseHeader(responseCaptor.capture());
    final List<ClassicHttpResponse> responses = responseCaptor.getAllValues();
    Assertions.assertNotNull(responses);
    Assertions.assertEquals(2, responses.size());
    final ClassicHttpResponse ack = responses.get(0);
    final ClassicHttpResponse response = responses.get(1);
    Assertions.assertEquals(HttpStatus.SC_CONTINUE, ack.getCode());
    Assertions.assertEquals(HttpStatus.SC_NOT_IMPLEMENTED, response.getCode());
    Assertions.assertSame(request, context.getRequest());
    Mockito.verify(httprocessor).process(request, request.getEntity(), context);
    Mockito.verify(inStream).close();
    Mockito.verify(httprocessor).process(response, response.getEntity(), context);
    Mockito.verify(conn).sendResponseHeader(response);
    Mockito.verify(conn).sendResponseEntity(response);
    Mockito.verify(conn, Mockito.times(2)).flush();
    Mockito.verify(conn, Mockito.never()).close();
    Mockito.verify(response).close();
}
Also used : HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) BeforeEach(org.junit.jupiter.api.BeforeEach) MethodNotSupportedException(org.apache.hc.core5.http.MethodNotSupportedException) ArgumentMatchers(org.mockito.ArgumentMatchers) Mock(org.mockito.Mock) UnsupportedHttpVersionException(org.apache.hc.core5.http.UnsupportedHttpVersionException) HttpResponseFactory(org.apache.hc.core5.http.HttpResponseFactory) InputStreamEntity(org.apache.hc.core5.http.io.entity.InputStreamEntity) HttpRequestMapper(org.apache.hc.core5.http.HttpRequestMapper) HttpProcessor(org.apache.hc.core5.http.protocol.HttpProcessor) MockitoAnnotations(org.mockito.MockitoAnnotations) ArgumentCaptor(org.mockito.ArgumentCaptor) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) Spy(org.mockito.Spy) HttpServerConnection(org.apache.hc.core5.http.io.HttpServerConnection) ProtocolException(org.apache.hc.core5.http.ProtocolException) ConnectionReuseStrategy(org.apache.hc.core5.http.ConnectionReuseStrategy) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) Test(org.junit.jupiter.api.Test) HttpHeaders(org.apache.hc.core5.http.HttpHeaders) Mockito(org.mockito.Mockito) List(java.util.List) HttpRequestHandler(org.apache.hc.core5.http.io.HttpRequestHandler) HeaderElements(org.apache.hc.core5.http.HeaderElements) Method(org.apache.hc.core5.http.Method) Assertions(org.junit.jupiter.api.Assertions) HttpStatus(org.apache.hc.core5.http.HttpStatus) InputStream(java.io.InputStream) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) InputStream(java.io.InputStream) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) InputStreamEntity(org.apache.hc.core5.http.io.entity.InputStreamEntity) Test(org.junit.jupiter.api.Test)

Example 53 with HttpCoreContext

use of org.apache.hc.core5.http.protocol.HttpCoreContext in project httpcomponents-core by apache.

the class TestHttpService method testNoContentResponse.

@Test
public void testNoContentResponse() throws Exception {
    final HttpCoreContext context = HttpCoreContext.create();
    final ClassicHttpRequest request = new BasicClassicHttpRequest(Method.GET, "/");
    Mockito.when(conn.receiveRequestHeader()).thenReturn(request);
    Mockito.when(responseFactory.newHttpResponse(200)).thenReturn(response);
    Mockito.when(handlerResolver.resolve(request, context)).thenReturn((request1, response, context1) -> response.setCode(HttpStatus.SC_NO_CONTENT));
    Mockito.when(connReuseStrategy.keepAlive(request, response, context)).thenReturn(Boolean.TRUE);
    httpservice.handleRequest(conn, context);
    Assertions.assertSame(request, context.getRequest());
    Mockito.verify(httprocessor).process(response, response.getEntity(), context);
    Mockito.verify(conn).sendResponseHeader(response);
    Mockito.verify(conn, Mockito.never()).sendResponseEntity(ArgumentMatchers.any());
    Mockito.verify(conn).flush();
    Mockito.verify(conn, Mockito.never()).close();
    Mockito.verify(response).close();
}
Also used : BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) Test(org.junit.jupiter.api.Test)

Example 54 with HttpCoreContext

use of org.apache.hc.core5.http.protocol.HttpCoreContext in project httpcomponents-core by apache.

the class TestHttpService method testResponseToHead.

@Test
public void testResponseToHead() throws Exception {
    final HttpCoreContext context = HttpCoreContext.create();
    final ClassicHttpRequest request = new BasicClassicHttpRequest(Method.HEAD, "/");
    Mockito.when(conn.receiveRequestHeader()).thenReturn(request);
    Mockito.when(responseFactory.newHttpResponse(200)).thenReturn(response);
    Mockito.when(handlerResolver.resolve(request, context)).thenReturn(requestHandler);
    Mockito.when(connReuseStrategy.keepAlive(request, response, context)).thenReturn(Boolean.TRUE);
    httpservice.handleRequest(conn, context);
    Assertions.assertSame(request, context.getRequest());
    Mockito.verify(httprocessor).process(response, response.getEntity(), context);
    Mockito.verify(requestHandler).handle(request, response, context);
    Mockito.verify(conn).sendResponseHeader(response);
    Mockito.verify(conn, Mockito.never()).sendResponseEntity(ArgumentMatchers.any());
    Mockito.verify(conn).flush();
    Mockito.verify(conn, Mockito.never()).close();
    Mockito.verify(response).close();
}
Also used : BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) Test(org.junit.jupiter.api.Test)

Example 55 with HttpCoreContext

use of org.apache.hc.core5.http.protocol.HttpCoreContext in project httpcomponents-core by apache.

the class AsyncFileServerExample method main.

/**
 * Example command line args: {@code "c:\temp" 8080}
 */
public static void main(final String[] args) throws Exception {
    if (args.length < 1) {
        System.err.println("Please specify document root directory");
        System.exit(1);
    }
    // Document root directory
    final File docRoot = new File(args[0]);
    int port = 8080;
    if (args.length >= 2) {
        port = Integer.parseInt(args[1]);
    }
    final IOReactorConfig config = IOReactorConfig.custom().setSoTimeout(15, TimeUnit.SECONDS).setTcpNoDelay(true).build();
    final HttpAsyncServer server = AsyncServerBootstrap.bootstrap().setIOReactorConfig(config).register("*", new AsyncServerRequestHandler<Message<HttpRequest, Void>>() {

        @Override
        public AsyncRequestConsumer<Message<HttpRequest, Void>> prepare(final HttpRequest request, final EntityDetails entityDetails, final HttpContext context) throws HttpException {
            return new BasicRequestConsumer<>(entityDetails != null ? new DiscardingEntityConsumer<>() : null);
        }

        @Override
        public void handle(final Message<HttpRequest, Void> message, final ResponseTrigger responseTrigger, final HttpContext context) throws HttpException, IOException {
            final HttpRequest request = message.getHead();
            final URI requestUri;
            try {
                requestUri = request.getUri();
            } catch (final URISyntaxException ex) {
                throw new ProtocolException(ex.getMessage(), ex);
            }
            final String path = requestUri.getPath();
            final File file = new File(docRoot, path);
            if (!file.exists()) {
                final String msg = "File " + file.getPath() + " not found";
                println(msg);
                responseTrigger.submitResponse(AsyncResponseBuilder.create(HttpStatus.SC_NOT_FOUND).setEntity("<html><body><h1>" + msg + "</h1></body></html>", ContentType.TEXT_HTML).build(), context);
            } else if (!file.canRead() || file.isDirectory()) {
                final String msg = "Cannot read file " + file.getPath();
                println(msg);
                responseTrigger.submitResponse(AsyncResponseBuilder.create(HttpStatus.SC_FORBIDDEN).setEntity("<html><body><h1>" + msg + "</h1></body></html>", ContentType.TEXT_HTML).build(), context);
            } else {
                final ContentType contentType;
                final String filename = TextUtils.toLowerCase(file.getName());
                if (filename.endsWith(".txt")) {
                    contentType = ContentType.TEXT_PLAIN;
                } else if (filename.endsWith(".html") || filename.endsWith(".htm")) {
                    contentType = ContentType.TEXT_HTML;
                } else if (filename.endsWith(".xml")) {
                    contentType = ContentType.TEXT_XML;
                } else {
                    contentType = ContentType.DEFAULT_BINARY;
                }
                final HttpCoreContext coreContext = HttpCoreContext.adapt(context);
                final EndpointDetails endpoint = coreContext.getEndpointDetails();
                println(endpoint + " | serving file " + file.getPath());
                responseTrigger.submitResponse(AsyncResponseBuilder.create(HttpStatus.SC_OK).setEntity(AsyncEntityProducers.create(file, contentType)).build(), context);
            }
        }
    }).create();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        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();
    println("Listening on " + listenerEndpoint.getAddress());
    server.awaitShutdown(TimeValue.MAX_VALUE);
}
Also used : HttpRequest(org.apache.hc.core5.http.HttpRequest) ProtocolException(org.apache.hc.core5.http.ProtocolException) Message(org.apache.hc.core5.http.Message) ContentType(org.apache.hc.core5.http.ContentType) BasicRequestConsumer(org.apache.hc.core5.http.nio.support.BasicRequestConsumer) InetSocketAddress(java.net.InetSocketAddress) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) URISyntaxException(java.net.URISyntaxException) EndpointDetails(org.apache.hc.core5.http.EndpointDetails) URI(java.net.URI) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) AsyncServerRequestHandler(org.apache.hc.core5.http.nio.AsyncServerRequestHandler) DiscardingEntityConsumer(org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer) HttpAsyncServer(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) EntityDetails(org.apache.hc.core5.http.EntityDetails) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) File(java.io.File)

Aggregations

HttpCoreContext (org.apache.hc.core5.http.protocol.HttpCoreContext)56 BasicClassicHttpRequest (org.apache.hc.core5.http.message.BasicClassicHttpRequest)46 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)39 ClassicHttpRequest (org.apache.hc.core5.http.ClassicHttpRequest)33 BasicClassicHttpResponse (org.apache.hc.core5.http.message.BasicClassicHttpResponse)29 HttpHost (org.apache.hc.core5.http.HttpHost)26 Test (org.junit.jupiter.api.Test)25 Test (org.junit.Test)21 HttpEntity (org.apache.hc.core5.http.HttpEntity)16 StringEntity (org.apache.hc.core5.http.io.entity.StringEntity)13 HttpClientConnection (org.apache.hc.core5.http.io.HttpClientConnection)12 ByteArrayEntity (org.apache.hc.core5.http.io.entity.ByteArrayEntity)12 HttpProcessor (org.apache.hc.core5.http.protocol.HttpProcessor)12 AbstractHttpEntity (org.apache.hc.core5.http.io.entity.AbstractHttpEntity)9 Random (java.util.Random)8 Header (org.apache.hc.core5.http.Header)8 ArrayList (java.util.ArrayList)6 HttpRequest (org.apache.hc.core5.http.HttpRequest)6 ProtocolException (org.apache.hc.core5.http.ProtocolException)6 ContentType (org.apache.hc.core5.http.ContentType)5