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);
}
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();
}
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();
}
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();
}
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);
}
Aggregations