Search in sources :

Example 1 with ContentType

use of org.apache.tapestry5.http.ContentType in project httpcomponents-core by apache.

the class BenchmarkWorker method createResponseConsumer.

private AsyncResponseConsumer<Void> createResponseConsumer() {
    return new AsyncResponseConsumer<Void>() {

        volatile int status;

        volatile Charset charset;

        final AtomicLong contentLength = new AtomicLong();

        final AtomicReference<FutureCallback<Void>> resultCallbackRef = new AtomicReference<>();

        @Override
        public void consumeResponse(final HttpResponse response, final EntityDetails entityDetails, final HttpContext context, final FutureCallback<Void> resultCallback) throws HttpException, IOException {
            status = response.getCode();
            resultCallbackRef.set(resultCallback);
            stats.setVersion(response.getVersion());
            final Header serverHeader = response.getFirstHeader(HttpHeaders.SERVER);
            if (serverHeader != null) {
                stats.setServerName(serverHeader.getValue());
            }
            if (config.getVerbosity() >= 2) {
                System.out.println(response.getCode());
            }
            if (entityDetails != null) {
                if (config.getVerbosity() >= 6) {
                    if (entityDetails.getContentType() != null) {
                        final ContentType contentType = ContentType.parseLenient(entityDetails.getContentType());
                        charset = ContentType.getCharset(contentType, null);
                    }
                }
            } else {
                streamEnd(null);
            }
        }

        @Override
        public void informationResponse(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
        }

        @Override
        public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
            capacityChannel.update(Integer.MAX_VALUE);
        }

        @Override
        public void consume(final ByteBuffer src) throws IOException {
            final int n = src.remaining();
            contentLength.addAndGet(n);
            stats.incTotalContentLength(n);
            if (config.getVerbosity() >= 6) {
                final CharsetDecoder decoder = (charset != null ? charset : StandardCharsets.US_ASCII).newDecoder();
                System.out.print(decoder.decode(src));
            }
        }

        @Override
        public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
            if (status == HttpStatus.SC_OK) {
                stats.incSuccessCount();
            } else {
                stats.incFailureCount();
            }
            stats.setContentLength(contentLength.get());
            final FutureCallback<Void> resultCallback = resultCallbackRef.getAndSet(null);
            if (resultCallback != null) {
                resultCallback.completed(null);
            }
            if (config.getVerbosity() >= 6) {
                System.out.println();
                System.out.println();
            }
        }

        @Override
        public void failed(final Exception cause) {
            stats.incFailureCount();
            final FutureCallback<Void> resultCallback = resultCallbackRef.getAndSet(null);
            if (resultCallback != null) {
                resultCallback.failed(cause);
            }
            if (config.getVerbosity() >= 1) {
                System.out.println("HTTP response error: " + cause.getMessage());
            }
        }

        @Override
        public void releaseResources() {
        }
    };
}
Also used : CharsetDecoder(java.nio.charset.CharsetDecoder) ContentType(org.apache.hc.core5.http.ContentType) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) Charset(java.nio.charset.Charset) HttpResponse(org.apache.hc.core5.http.HttpResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) ByteBuffer(java.nio.ByteBuffer) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) AsyncResponseConsumer(org.apache.hc.core5.http.nio.AsyncResponseConsumer) AtomicLong(java.util.concurrent.atomic.AtomicLong) BasicHeader(org.apache.hc.core5.http.message.BasicHeader) Header(org.apache.hc.core5.http.Header) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) EntityDetails(org.apache.hc.core5.http.EntityDetails) List(java.util.List) FutureCallback(org.apache.hc.core5.concurrent.FutureCallback)

Example 2 with ContentType

use of org.apache.tapestry5.http.ContentType in project httpcomponents-core by apache.

the class H2IntegrationTest method testSlowResponseConsumer.

@Test
public void testSlowResponseConsumer() throws Exception {
    server.register("/", () -> new MultiLineResponseHandler("0123456789abcd", 3));
    final InetSocketAddress serverEndpoint = server.start();
    client.start(H2Config.custom().setInitialWindowSize(16).build());
    final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
    final ClientSessionEndpoint streamEndpoint = connectFuture.get();
    final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(new BasicRequestProducer(Method.GET, createRequestURI(serverEndpoint, "/"), null), new BasicResponseConsumer<>(new AbstractClassicEntityConsumer<String>(16, Executors.newSingleThreadExecutor()) {

        @Override
        protected String consumeData(final ContentType contentType, final InputStream inputStream) throws IOException {
            final Charset charset = ContentType.getCharset(contentType, StandardCharsets.US_ASCII);
            final StringBuilder buffer = new StringBuilder();
            try {
                final byte[] tmp = new byte[16];
                int l;
                while ((l = inputStream.read(tmp)) != -1) {
                    buffer.append(charset.decode(ByteBuffer.wrap(tmp, 0, l)));
                    Thread.sleep(500);
                }
            } catch (final InterruptedException ex) {
                Thread.currentThread().interrupt();
                throw new InterruptedIOException(ex.getMessage());
            }
            return buffer.toString();
        }
    }), 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());
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) Message(org.apache.hc.core5.http.Message) ContentType(org.apache.hc.core5.http.ContentType) InetSocketAddress(java.net.InetSocketAddress) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) InputStream(java.io.InputStream) Charset(java.nio.charset.Charset) HttpResponse(org.apache.hc.core5.http.HttpResponse) AbstractClassicEntityConsumer(org.apache.hc.core5.http.nio.support.classic.AbstractClassicEntityConsumer) StringTokenizer(java.util.StringTokenizer) Test(org.junit.Test)

Example 3 with ContentType

use of org.apache.tapestry5.http.ContentType 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());
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) ContentType(org.apache.hc.core5.http.ContentType) Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) OutputStream(java.io.OutputStream) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) BufferedWriter(java.io.BufferedWriter) HttpException(org.apache.hc.core5.http.HttpException) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) Charset(java.nio.charset.Charset) AbstractClassicServerExchangeHandler(org.apache.hc.core5.http.nio.support.classic.AbstractClassicServerExchangeHandler) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) StringTokenizer(java.util.StringTokenizer) Header(org.apache.hc.core5.http.Header) BufferedReader(java.io.BufferedReader) OutputStreamWriter(java.io.OutputStreamWriter) Test(org.junit.Test)

Example 4 with ContentType

use of org.apache.tapestry5.http.ContentType 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());
    }
}
Also used : BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) InterruptedIOException(java.io.InterruptedIOException) Message(org.apache.hc.core5.http.Message) ContentType(org.apache.hc.core5.http.ContentType) InetSocketAddress(java.net.InetSocketAddress) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) OutputStream(java.io.OutputStream) Charset(java.nio.charset.Charset) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) BufferedWriter(java.io.BufferedWriter) StringTokenizer(java.util.StringTokenizer) OutputStreamWriter(java.io.OutputStreamWriter) AbstractClassicEntityProducer(org.apache.hc.core5.http.nio.support.classic.AbstractClassicEntityProducer) Test(org.junit.Test)

Example 5 with ContentType

use of org.apache.tapestry5.http.ContentType in project httpcomponents-core by apache.

the class AbstractCharAsyncEntityConsumer method streamStart.

@Override
public final void streamStart(final EntityDetails entityDetails, final FutureCallback<T> resultCallback) throws IOException, HttpException {
    Args.notNull(resultCallback, "Result callback");
    this.resultCallback = resultCallback;
    try {
        final ContentType contentType = entityDetails != null ? ContentType.parse(entityDetails.getContentType()) : null;
        setCharset(ContentType.getCharset(contentType, null));
        streamStart(contentType);
    } catch (final UnsupportedCharsetException ex) {
        throw new UnsupportedEncodingException(ex.getMessage());
    }
}
Also used : ContentType(org.apache.hc.core5.http.ContentType) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Aggregations

ContentType (org.apache.hc.core5.http.ContentType)58 Charset (java.nio.charset.Charset)18 IOException (java.io.IOException)15 ContentType (org.apache.tapestry5.http.ContentType)15 BasicRequestProducer (org.apache.hc.core5.http.nio.support.BasicRequestProducer)13 HttpException (org.apache.hc.core5.http.HttpException)12 HttpResponse (org.apache.hc.core5.http.HttpResponse)12 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)10 HttpRequest (org.apache.hc.core5.http.HttpRequest)10 BasicHttpRequest (org.apache.hc.core5.http.message.BasicHttpRequest)10 InputStream (java.io.InputStream)9 UnsupportedEncodingException (java.io.UnsupportedEncodingException)8 InetSocketAddress (java.net.InetSocketAddress)8 Header (org.apache.hc.core5.http.Header)8 Message (org.apache.hc.core5.http.Message)8 Test (org.junit.Test)8 Test (org.testng.annotations.Test)8 InterruptedIOException (java.io.InterruptedIOException)7 HttpEntity (org.apache.hc.core5.http.HttpEntity)7 StringTokenizer (java.util.StringTokenizer)6