use of org.apache.hc.core5.http.nio.support.BasicResponseConsumer in project httpcomponents-core by apache.
the class Http1IntegrationTest method testSlowResponseProducer.
@Test
public void testSlowResponseProducer() throws Exception {
server.register("*", () -> new AbstractClassicServerExchangeHandler(2048, Executors.newSingleThreadExecutor()) {
@Override
protected void handle(final HttpRequest request, final InputStream requestStream, final HttpResponse response, final OutputStream responseStream, final HttpContext context) throws IOException, HttpException {
if (!"/hello".equals(request.getPath())) {
response.setCode(HttpStatus.SC_NOT_FOUND);
return;
}
if (!Method.POST.name().equalsIgnoreCase(request.getMethod())) {
response.setCode(HttpStatus.SC_NOT_IMPLEMENTED);
return;
}
if (requestStream == null) {
return;
}
final Header h1 = request.getFirstHeader(HttpHeaders.CONTENT_TYPE);
final ContentType contentType = h1 != null ? ContentType.parse(h1.getValue()) : null;
final Charset charset = ContentType.getCharset(contentType, StandardCharsets.US_ASCII);
response.setCode(HttpStatus.SC_OK);
response.setHeader(h1);
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(requestStream, charset));
final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(responseStream, charset))) {
try {
String l;
int count = 0;
while ((l = reader.readLine()) != null) {
writer.write(l);
writer.write("\r\n");
count++;
if (count % 500 == 0) {
Thread.sleep(500);
}
}
writer.flush();
} catch (final InterruptedException ex) {
Thread.currentThread().interrupt();
throw new InterruptedIOException(ex.getMessage());
}
}
}
});
final InetSocketAddress serverEndpoint = server.start();
client.start(Http1Config.custom().setBufferSize(256).build());
final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
final ClientSessionEndpoint streamEndpoint = connectFuture.get();
final HttpRequest request1 = new BasicHttpRequest(Method.POST, createRequestURI(serverEndpoint, "/hello"));
final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(new BasicRequestProducer(request1, new MultiLineEntityProducer("0123456789abcd", 2000)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
final Message<HttpResponse, String> result1 = future1.get(LONG_TIMEOUT.getDuration(), LONG_TIMEOUT.getTimeUnit());
Assertions.assertNotNull(result1);
final HttpResponse response1 = result1.getHead();
Assertions.assertNotNull(response1);
Assertions.assertEquals(200, response1.getCode());
final String s1 = result1.getBody();
Assertions.assertNotNull(s1);
final StringTokenizer t1 = new StringTokenizer(s1, "\r\n");
while (t1.hasMoreTokens()) {
Assertions.assertEquals("0123456789abcd", t1.nextToken());
}
}
use of org.apache.hc.core5.http.nio.support.BasicResponseConsumer in project httpcomponents-core by apache.
the class Http1IntegrationTest method testSimpleGet.
@Test
public void testSimpleGet() throws Exception {
server.register("/hello", () -> new SingleLineResponseHandler("Hi there"));
final InetSocketAddress serverEndpoint = server.start();
client.start();
final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
final ClientSessionEndpoint streamEndpoint = connectFuture.get();
for (int i = 0; i < 5; i++) {
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();
final String entity1 = result.getBody();
Assertions.assertNotNull(response1);
Assertions.assertEquals(200, response1.getCode());
Assertions.assertEquals("Hi there", entity1);
}
}
use of org.apache.hc.core5.http.nio.support.BasicResponseConsumer in project httpcomponents-core by apache.
the class Http1IntegrationTest method testSlowRequestProducer.
@Test
public void testSlowRequestProducer() throws Exception {
server.register("*", () -> new EchoHandler(2048));
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.POST, createRequestURI(serverEndpoint, "/echo"));
final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(new BasicRequestProducer(request1, new AbstractClassicEntityProducer(4096, ContentType.TEXT_PLAIN, Executors.newSingleThreadExecutor()) {
@Override
protected void produceData(final ContentType contentType, final OutputStream outputStream) throws IOException {
final Charset charset = ContentType.getCharset(contentType, StandardCharsets.US_ASCII);
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, charset))) {
for (int i = 0; i < 500; i++) {
if (i % 100 == 0) {
writer.flush();
Thread.sleep(500);
}
writer.write("0123456789abcdef\r\n");
}
} catch (final InterruptedException ex) {
Thread.currentThread().interrupt();
throw new InterruptedIOException(ex.getMessage());
}
}
}), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
final Message<HttpResponse, String> result1 = future1.get(LONG_TIMEOUT.getDuration(), LONG_TIMEOUT.getTimeUnit());
Assertions.assertNotNull(result1);
final HttpResponse response1 = result1.getHead();
Assertions.assertNotNull(response1);
Assertions.assertEquals(200, response1.getCode());
final String s1 = result1.getBody();
Assertions.assertNotNull(s1);
final StringTokenizer t1 = new StringTokenizer(s1, "\r\n");
while (t1.hasMoreTokens()) {
Assertions.assertEquals("0123456789abcdef", t1.nextToken());
}
}
use of org.apache.hc.core5.http.nio.support.BasicResponseConsumer in project httpcomponents-core by apache.
the class Http1IntegrationTest method testSimpleHead.
@Test
public void testSimpleHead() throws Exception {
server.register("/hello", () -> new SingleLineResponseHandler("Hi there"));
final InetSocketAddress serverEndpoint = server.start();
client.start();
final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
final ClientSessionEndpoint streamEndpoint = connectFuture.get();
for (int i = 0; i < 5; i++) {
final Future<Message<HttpResponse, String>> future = streamEndpoint.execute(new BasicRequestProducer(Method.HEAD, 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(200, response1.getCode());
Assertions.assertNull(result.getBody());
}
}
use of org.apache.hc.core5.http.nio.support.BasicResponseConsumer in project httpcomponents-core by apache.
the class Http1IntegrationTest method testTruncatedChunk.
@Test
public void testTruncatedChunk() throws Exception {
final InetSocketAddress serverEndpoint = server.start(new InternalServerHttp1EventHandlerFactory(HttpProcessors.server(), (request, context) -> 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(new StringAsyncEntityProducer("useful stuff")), context);
}
}, Http1Config.DEFAULT, CharCodingConfig.DEFAULT, DefaultConnectionReuseStrategy.INSTANCE, scheme == URIScheme.HTTPS ? SSLTestContexts.createServerSSLContext() : null, null, null) {
@Override
protected ServerHttp1StreamDuplexer createServerHttp1StreamDuplexer(final ProtocolIOSession ioSession, final HttpProcessor httpProcessor, final HandlerFactory<AsyncServerExchangeHandler> exchangeHandlerFactory, final Http1Config http1Config, final CharCodingConfig connectionConfig, final ConnectionReuseStrategy connectionReuseStrategy, final NHttpMessageParser<HttpRequest> incomingMessageParser, final NHttpMessageWriter<HttpResponse> outgoingMessageWriter, final ContentLengthStrategy incomingContentStrategy, final ContentLengthStrategy outgoingContentStrategy, final Http1StreamListener streamListener) {
return new ServerHttp1StreamDuplexer(ioSession, httpProcessor, exchangeHandlerFactory, scheme.id, http1Config, connectionConfig, connectionReuseStrategy, incomingMessageParser, outgoingMessageWriter, incomingContentStrategy, outgoingContentStrategy, streamListener) {
@Override
protected ContentEncoder createContentEncoder(final long len, final WritableByteChannel channel, final SessionOutputBuffer buffer, final BasicHttpTransportMetrics metrics) throws HttpException {
if (len == ContentLengthStrategy.CHUNKED) {
return new BrokenChunkEncoder(channel, buffer, metrics);
} else {
return super.createContentEncoder(len, channel, buffer, metrics);
}
}
};
}
});
client.start();
final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
final ClientSessionEndpoint streamEndpoint = connectFuture.get();
final AsyncRequestProducer requestProducer = new BasicRequestProducer(Method.GET, createRequestURI(serverEndpoint, "/hello"));
final StringAsyncEntityConsumer entityConsumer = new StringAsyncEntityConsumer() {
@Override
public void releaseResources() {
// Do not clear internal content buffer
}
};
final BasicResponseConsumer<String> responseConsumer = new BasicResponseConsumer<>(entityConsumer);
final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(requestProducer, responseConsumer, null);
final ExecutionException exception = Assertions.assertThrows(ExecutionException.class, () -> future1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit()));
final Throwable cause = exception.getCause();
Assertions.assertTrue(cause instanceof MalformedChunkCodingException);
Assertions.assertEquals("garbage", entityConsumer.generateContent());
}
Aggregations