use of org.apache.hc.core5.http.nio.support.BasicRequestConsumer in project httpcomponents-core by apache.
the class H2IntegrationTest method testMessageWithTrailers.
@Test
public void testMessageWithTrailers() throws Exception {
server.register("/hello", () -> new AbstractServerExchangeHandler<Message<HttpRequest, String>>() {
@Override
protected AsyncRequestConsumer<Message<HttpRequest, String>> supplyConsumer(final HttpRequest request, final EntityDetails entityDetails, final HttpContext context) throws HttpException {
return new BasicRequestConsumer<>(entityDetails != null ? new StringAsyncEntityConsumer() : null);
}
@Override
protected void handle(final Message<HttpRequest, String> requestMessage, final AsyncServerRequestHandler.ResponseTrigger responseTrigger, final HttpContext context) throws HttpException, IOException {
responseTrigger.submitResponse(new BasicResponseProducer(HttpStatus.SC_OK, new DigestingEntityProducer("MD5", new StringAsyncEntityProducer("Hello back with some trailers"))), context);
}
});
final InetSocketAddress serverEndpoint = server.start();
client.start();
final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
final ClientSessionEndpoint streamEndpoint = connectFuture.get();
final HttpRequest request1 = new BasicHttpRequest(Method.GET, createRequestURI(serverEndpoint, "/hello"));
final DigestingEntityConsumer<String> entityConsumer = new DigestingEntityConsumer<>("MD5", new StringAsyncEntityConsumer());
final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(new BasicRequestProducer(request1, null), new BasicResponseConsumer<>(entityConsumer), 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(200, response1.getCode());
Assertions.assertEquals("Hello back with some trailers", result1.getBody());
final List<Header> trailers = entityConsumer.getTrailers();
Assertions.assertNotNull(trailers);
Assertions.assertEquals(2, trailers.size());
final Map<String, String> map = new HashMap<>();
for (final Header header : trailers) {
map.put(TextUtils.toLowerCase(header.getName()), header.getValue());
}
final String digest = TextUtils.toHexString(entityConsumer.getDigest());
Assertions.assertEquals("MD5", map.get("digest-algo"));
Assertions.assertEquals(digest, map.get("digest"));
}
use of org.apache.hc.core5.http.nio.support.BasicRequestConsumer in project httpcomponents-core by apache.
the class BenchmarkToolTest method setup.
public void setup(final HttpVersionPolicy versionPolicy) throws Exception {
server = H2ServerBootstrap.bootstrap().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> requestObject, final ResponseTrigger responseTrigger, final HttpContext context) throws HttpException, IOException {
responseTrigger.submitResponse(AsyncResponseBuilder.create(HttpStatus.SC_OK).setEntity("0123456789ABCDEF").build(), context);
}
}).setVersionPolicy(versionPolicy).create();
server.start();
final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(0), URIScheme.HTTP);
final ListenerEndpoint listener = future.get();
address = (InetSocketAddress) listener.getAddress();
}
use of org.apache.hc.core5.http.nio.support.BasicRequestConsumer in project httpcomponents-core by apache.
the class Http1IntegrationTest method testMessageWithTrailers.
@Test
public void testMessageWithTrailers() throws Exception {
server.register("/hello", () -> new AbstractServerExchangeHandler<Message<HttpRequest, String>>() {
@Override
protected AsyncRequestConsumer<Message<HttpRequest, String>> supplyConsumer(final HttpRequest request, final EntityDetails entityDetails, final HttpContext context) throws HttpException {
return new BasicRequestConsumer<>(entityDetails != null ? new StringAsyncEntityConsumer() : null);
}
@Override
protected void handle(final Message<HttpRequest, String> requestMessage, final AsyncServerRequestHandler.ResponseTrigger responseTrigger, final HttpContext context) throws HttpException, IOException {
responseTrigger.submitResponse(new BasicResponseProducer(HttpStatus.SC_OK, new DigestingEntityProducer("MD5", new StringAsyncEntityProducer("Hello back with some trailers"))), context);
}
});
final InetSocketAddress serverEndpoint = server.start();
client.start();
final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
final ClientSessionEndpoint streamEndpoint = connectFuture.get();
final HttpRequest request1 = new BasicHttpRequest(Method.GET, createRequestURI(serverEndpoint, "/hello"));
final DigestingEntityConsumer<String> entityConsumer = new DigestingEntityConsumer<>("MD5", new StringAsyncEntityConsumer());
final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(new BasicRequestProducer(request1, null), new BasicResponseConsumer<>(entityConsumer), 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(200, response1.getCode());
Assertions.assertEquals("Hello back with some trailers", result1.getBody());
final List<Header> trailers = entityConsumer.getTrailers();
Assertions.assertNotNull(trailers);
Assertions.assertEquals(2, trailers.size());
final Map<String, String> map = new HashMap<>();
for (final Header header : trailers) {
map.put(TextUtils.toLowerCase(header.getName()), header.getValue());
}
final String digest = TextUtils.toHexString(entityConsumer.getDigest());
Assertions.assertEquals("MD5", map.get("digest-algo"));
Assertions.assertEquals(digest, map.get("digest"));
}
use of org.apache.hc.core5.http.nio.support.BasicRequestConsumer in project httpcomponents-core by apache.
the class AsyncServerFilterExample 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).replaceFilter(StandardFilter.EXPECT_CONTINUE.name(), new AbstractAsyncServerAuthFilter<String>(true) {
@Override
protected String parseChallengeResponse(final String authorizationValue, final HttpContext context) throws HttpException {
return authorizationValue;
}
@Override
protected boolean authenticate(final String challengeResponse, final URIAuthority authority, final String requestUri, final HttpContext context) {
return "let me pass".equals(challengeResponse);
}
@Override
protected String generateChallenge(final String challengeResponse, final URIAuthority authority, final String requestUri, final HttpContext context) {
return "who goes there?";
}
}).addFilterFirst("my-filter", (request, entityDetails, context, responseTrigger, chain) -> {
if (request.getRequestUri().equals("/back-door")) {
responseTrigger.submitResponse(new BasicHttpResponse(HttpStatus.SC_OK), AsyncEntityProducers.create("Welcome"));
return null;
}
return chain.proceed(request, entityDetails, context, new AsyncFilterChain.ResponseTrigger() {
@Override
public void sendInformation(final HttpResponse response) throws HttpException, IOException {
responseTrigger.sendInformation(response);
}
@Override
public void submitResponse(final HttpResponse response, final AsyncEntityProducer entityProducer) throws HttpException, IOException {
response.addHeader("X-Filter", "My-Filter");
responseTrigger.submitResponse(response, entityProducer);
}
@Override
public void pushPromise(final HttpRequest promise, final AsyncPushProducer responseProducer) throws HttpException, IOException {
responseTrigger.pushPromise(promise, responseProducer);
}
});
}).register("*", new AsyncServerRequestHandler<Message<HttpRequest, String>>() {
@Override
public AsyncRequestConsumer<Message<HttpRequest, String>> prepare(final HttpRequest request, final EntityDetails entityDetails, final HttpContext context) throws HttpException {
return new BasicRequestConsumer<>(entityDetails != null ? new StringAsyncEntityConsumer() : null);
}
@Override
public void handle(final Message<HttpRequest, String> requestMessage, final ResponseTrigger responseTrigger, final HttpContext context) throws HttpException, IOException {
// do something useful
responseTrigger.submitResponse(AsyncResponseBuilder.create(HttpStatus.SC_OK).setEntity("Hello").build(), context);
}
}).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.MAX_VALUE);
}
use of org.apache.hc.core5.http.nio.support.BasicRequestConsumer 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