use of org.apache.hc.core5.http.nio.AsyncEntityProducer in project httpcomponents-core by apache.
the class H2CompatibilityTest method executeHttpBin.
void executeHttpBin(final HttpHost target) throws Exception {
{
System.out.println("*** httpbin.org HTTP/1.1 simple request execution ***");
final List<Message<HttpRequest, AsyncEntityProducer>> requestMessages = Arrays.asList(new Message<>(new BasicHttpRequest(Method.GET, target, "/headers"), null), new Message<>(new BasicHttpRequest(Method.POST, target, "/anything"), new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN)), new Message<>(new BasicHttpRequest(Method.PUT, target, "/anything"), new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN)), new Message<>(new BasicHttpRequest(Method.GET, target, "/drip"), null), new Message<>(new BasicHttpRequest(Method.GET, target, "/bytes/20000"), null), new Message<>(new BasicHttpRequest(Method.GET, target, "/delay/2"), null), new Message<>(new BasicHttpRequest(Method.POST, target, "/delay/2"), new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN)), new Message<>(new BasicHttpRequest(Method.PUT, target, "/delay/2"), new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN)));
for (final Message<HttpRequest, AsyncEntityProducer> message : requestMessages) {
final CountDownLatch countDownLatch = new CountDownLatch(1);
final HttpRequest request = message.getHead();
final AsyncEntityProducer entityProducer = message.getBody();
client.execute(new BasicRequestProducer(request, entityProducer), new BasicResponseConsumer<>(new StringAsyncEntityConsumer(CharCodingConfig.custom().setCharset(StandardCharsets.US_ASCII).setMalformedInputAction(CodingErrorAction.IGNORE).setUnmappableInputAction(CodingErrorAction.REPLACE).build())), TIMEOUT, new FutureCallback<Message<HttpResponse, String>>() {
@Override
public void completed(final Message<HttpResponse, String> responseMessage) {
final HttpResponse response = responseMessage.getHead();
final int code = response.getCode();
if (code == HttpStatus.SC_OK) {
logResult(TestResult.OK, target, request, response, Objects.toString(response.getFirstHeader("server")));
} else {
logResult(TestResult.NOK, target, request, response, "(status " + code + ")");
}
countDownLatch.countDown();
}
@Override
public void failed(final Exception ex) {
logResult(TestResult.NOK, target, request, null, "(" + ex.getMessage() + ")");
countDownLatch.countDown();
}
@Override
public void cancelled() {
logResult(TestResult.NOK, target, request, null, "(cancelled)");
countDownLatch.countDown();
}
});
if (!countDownLatch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit())) {
logResult(TestResult.NOK, target, null, null, "(httpbin.org tests failed to complete in time)");
}
}
}
{
System.out.println("*** httpbin.org HTTP/1.1 pipelined request execution ***");
final Future<AsyncClientEndpoint> connectFuture = client.connect(target, TIMEOUT);
final AsyncClientEndpoint streamEndpoint = connectFuture.get();
final int n = 10;
final CountDownLatch countDownLatch = new CountDownLatch(n);
for (int i = 0; i < n; i++) {
final HttpRequest request;
final AsyncEntityProducer entityProducer;
if (i % 2 == 0) {
request = new BasicHttpRequest(Method.GET, target, "/headers");
entityProducer = null;
} else {
request = new BasicHttpRequest(Method.POST, target, "/anything");
entityProducer = new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN);
}
streamEndpoint.execute(new BasicRequestProducer(request, entityProducer), new BasicResponseConsumer<>(new StringAsyncEntityConsumer(CharCodingConfig.custom().setCharset(StandardCharsets.US_ASCII).setMalformedInputAction(CodingErrorAction.IGNORE).setUnmappableInputAction(CodingErrorAction.REPLACE).build())), new FutureCallback<Message<HttpResponse, String>>() {
@Override
public void completed(final Message<HttpResponse, String> responseMessage) {
final HttpResponse response = responseMessage.getHead();
final int code = response.getCode();
if (code == HttpStatus.SC_OK) {
logResult(TestResult.OK, target, request, response, "pipelined / " + response.getFirstHeader("server"));
} else {
logResult(TestResult.NOK, target, request, response, "(status " + code + ")");
}
countDownLatch.countDown();
}
@Override
public void failed(final Exception ex) {
logResult(TestResult.NOK, target, request, null, "(" + ex.getMessage() + ")");
countDownLatch.countDown();
}
@Override
public void cancelled() {
logResult(TestResult.NOK, target, request, null, "(cancelled)");
countDownLatch.countDown();
}
});
}
if (!countDownLatch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit())) {
logResult(TestResult.NOK, target, null, null, "(httpbin.org tests failed to complete in time)");
}
}
}
use of org.apache.hc.core5.http.nio.AsyncEntityProducer 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.AsyncEntityProducer in project httpcomponents-core by apache.
the class TestFileAsyncEntityProducer method testTextContent.
@Test
public void testTextContent() throws Exception {
final AsyncEntityProducer producer = new FileEntityProducer(tempFile, ContentType.TEXT_PLAIN);
Assertions.assertEquals(6, producer.getContentLength());
Assertions.assertEquals(ContentType.TEXT_PLAIN.toString(), producer.getContentType());
Assertions.assertNull(producer.getContentEncoding());
final WritableByteChannelMock byteChannel = new WritableByteChannelMock(1024);
final DataStreamChannel streamChannel = new BasicDataStreamChannel(byteChannel);
producer.produce(streamChannel);
producer.produce(streamChannel);
Assertions.assertFalse(byteChannel.isOpen());
Assertions.assertEquals("abcdef", byteChannel.dump(StandardCharsets.US_ASCII));
}
use of org.apache.hc.core5.http.nio.AsyncEntityProducer in project httpcomponents-core by apache.
the class TestPathAsyncEntityProducer method testTextContentRepeatable.
@Test
public void testTextContentRepeatable() throws Exception {
final Path tempPath = tempFile.toPath();
final AsyncEntityProducer producer = new PathEntityProducer(tempPath, ContentType.TEXT_PLAIN, StandardOpenOption.READ);
Assertions.assertEquals(6, producer.getContentLength());
Assertions.assertEquals(ContentType.TEXT_PLAIN.toString(), producer.getContentType());
Assertions.assertNull(producer.getContentEncoding());
for (int i = 0; i < 3; i++) {
final WritableByteChannelMock byteChannel = new WritableByteChannelMock(1024);
final DataStreamChannel streamChannel = new BasicDataStreamChannel(byteChannel);
producer.produce(streamChannel);
producer.produce(streamChannel);
Assertions.assertFalse(byteChannel.isOpen());
Assertions.assertEquals("abcdef", byteChannel.dump(StandardCharsets.US_ASCII));
producer.releaseResources();
}
}
use of org.apache.hc.core5.http.nio.AsyncEntityProducer in project httpcomponents-core by apache.
the class TestStringAsyncEntityProducer method testTextContentRepeatable.
@Test
public void testTextContentRepeatable() throws Exception {
final AsyncEntityProducer producer = new StringAsyncEntityProducer("abc", ContentType.TEXT_PLAIN);
Assertions.assertEquals(-1, producer.getContentLength());
Assertions.assertEquals(ContentType.TEXT_PLAIN.toString(), producer.getContentType());
Assertions.assertNull(producer.getContentEncoding());
for (int i = 0; i < 3; i++) {
final WritableByteChannelMock byteChannel = new WritableByteChannelMock(1024);
final DataStreamChannel streamChannel = new BasicDataStreamChannel(byteChannel);
producer.produce(streamChannel);
Assertions.assertFalse(byteChannel.isOpen());
Assertions.assertEquals("abc", byteChannel.dump(StandardCharsets.US_ASCII));
producer.releaseResources();
}
}
Aggregations