Search in sources :

Example 46 with BasicResponseConsumer

use of org.apache.hc.core5.http.nio.support.BasicResponseConsumer in project californium by eclipse.

the class ProxyHttpClientResource method handleRequest.

@Override
public void handleRequest(final Exchange exchange) {
    final Request incomingCoapRequest = exchange.getRequest();
    URI destination;
    try {
        InetSocketAddress exposedInterface = translator.getExposedInterface(incomingCoapRequest);
        destination = translator.getDestinationURI(incomingCoapRequest, exposedInterface);
    } catch (TranslationException ex) {
        LOGGER.debug("URI error.", ex);
        Response response = new Response(Coap2CoapTranslator.STATUS_FIELD_MALFORMED);
        response.setPayload(ex.getMessage());
        exchange.sendResponse(response);
        return;
    }
    final CacheKey cacheKey;
    final CacheResource cache = getCache();
    if (cache != null) {
        cacheKey = new CacheKey(incomingCoapRequest.getCode(), destination, incomingCoapRequest.getOptions().getAccept(), incomingCoapRequest.getPayload());
        Response response = cache.getResponse(cacheKey);
        StatsResource statsResource = getStatsResource();
        if (statsResource != null) {
            statsResource.updateStatistics(destination, response != null);
        }
        if (response != null) {
            LOGGER.info("Cache returned {}", response);
            exchange.sendResponse(response);
            return;
        }
    } else {
        cacheKey = null;
    }
    ProxyRequestProducer httpRequest = null;
    try {
        // get the mapping to http for the incoming coap request
        httpRequest = translator.getHttpRequest(destination, incomingCoapRequest);
        LOGGER.debug("Outgoing http request: {}", httpRequest.getRequestLine());
    } catch (InvalidFieldException e) {
        LOGGER.debug("Problems during the http/coap translation: {}", e.getMessage());
        exchange.sendResponse(new Response(Coap2CoapTranslator.STATUS_FIELD_MALFORMED));
        return;
    } catch (TranslationException e) {
        LOGGER.debug("Problems during the http/coap translation: {}", e.getMessage());
        exchange.sendResponse(new Response(Coap2CoapTranslator.STATUS_TRANSLATION_ERROR));
        return;
    }
    if (accept) {
        exchange.sendAccept();
    }
    asyncClient.execute(httpRequest, new BasicResponseConsumer<ContentTypedEntity>(new ContentTypedEntityConsumer()), new BasicHttpContext(), new FutureCallback<Message<HttpResponse, ContentTypedEntity>>() {

        @Override
        public void completed(Message<HttpResponse, ContentTypedEntity> result) {
            StatusLine status = new StatusLine(result.getHead());
            try {
                long timestamp = ClockUtil.nanoRealtime();
                LOGGER.debug("Incoming http response: {}", status);
                // the entity of the response, if non repeatable,
                // could be
                // consumed only one time, so do not debug it!
                // System.out.println(EntityUtils.toString(httpResponse.getEntity()));
                // translate the received http response in a coap
                // response
                Response coapResponse = translator.getCoapResponse(result, incomingCoapRequest);
                coapResponse.setNanoTimestamp(timestamp);
                if (cache != null) {
                    cache.cacheResponse(cacheKey, coapResponse);
                }
                exchange.sendResponse(coapResponse);
            } catch (InvalidFieldException e) {
                LOGGER.debug("Problems during the http/coap translation: {}", e.getMessage());
                exchange.sendResponse(new Response(Coap2CoapTranslator.STATUS_FIELD_MALFORMED));
            } catch (TranslationException e) {
                LOGGER.debug("Problems during the http/coap translation: {}", e.getMessage());
                exchange.sendResponse(new Response(Coap2CoapTranslator.STATUS_TRANSLATION_ERROR));
            } catch (Throwable e) {
                LOGGER.debug("Error during the http/coap translation: {}", e.getMessage(), e);
                exchange.sendResponse(new Response(Coap2CoapTranslator.STATUS_FIELD_MALFORMED));
            }
            LOGGER.debug("Incoming http response: {} processed!", status);
        }

        @Override
        public void failed(Exception ex) {
            LOGGER.debug("Failed to get the http response: {}", ex.getMessage(), ex);
            if (ex instanceof SocketTimeoutException) {
                exchange.sendResponse(new Response(ResponseCode.GATEWAY_TIMEOUT));
            } else {
                exchange.sendResponse(new Response(ResponseCode.BAD_GATEWAY));
            }
        }

        @Override
        public void cancelled() {
            LOGGER.debug("Request canceled");
            exchange.sendResponse(new Response(ResponseCode.SERVICE_UNAVAILABLE));
        }
    });
}
Also used : ContentTypedEntity(org.eclipse.californium.proxy2.http.ContentTypedEntity) Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) ProxyRequestProducer(org.eclipse.californium.proxy2.http.ProxyRequestProducer) BasicHttpContext(org.apache.hc.core5.http.protocol.BasicHttpContext) Request(org.eclipse.californium.core.coap.Request) HttpResponse(org.apache.hc.core5.http.HttpResponse) TranslationException(org.eclipse.californium.proxy2.TranslationException) URI(java.net.URI) InvalidFieldException(org.eclipse.californium.proxy2.InvalidFieldException) SocketTimeoutException(java.net.SocketTimeoutException) TranslationException(org.eclipse.californium.proxy2.TranslationException) Response(org.eclipse.californium.core.coap.Response) HttpResponse(org.apache.hc.core5.http.HttpResponse) ContentTypedEntityConsumer(org.eclipse.californium.proxy2.http.ContentTypedEntityConsumer) StatusLine(org.apache.hc.core5.http.message.StatusLine) SocketTimeoutException(java.net.SocketTimeoutException) InvalidFieldException(org.eclipse.californium.proxy2.InvalidFieldException)

Example 47 with BasicResponseConsumer

use of org.apache.hc.core5.http.nio.support.BasicResponseConsumer in project httpcomponents-core by apache.

the class Http1ServerAndRequesterTest method testSequentialRequestsSameEndpoint.

@Test
public void testSequentialRequestsSameEndpoint() throws Exception {
    server.start();
    final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(0), scheme);
    final ListenerEndpoint listener = future.get();
    final InetSocketAddress address = (InetSocketAddress) listener.getAddress();
    requester.start();
    final HttpHost target = new HttpHost(scheme.id, "localhost", address.getPort());
    final Future<AsyncClientEndpoint> endpointFuture = requester.connect(target, Timeout.ofSeconds(5));
    final AsyncClientEndpoint endpoint = endpointFuture.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
    try {
        final Future<Message<HttpResponse, String>> resultFuture1 = endpoint.execute(new BasicRequestProducer(Method.POST, target, "/stuff", new StringAsyncEntityProducer("some stuff", ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
        final Message<HttpResponse, String> message1 = resultFuture1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
        assertThat(message1, CoreMatchers.notNullValue());
        final HttpResponse response1 = message1.getHead();
        assertThat(response1.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
        final String body1 = message1.getBody();
        assertThat(body1, CoreMatchers.equalTo("some stuff"));
        final Future<Message<HttpResponse, String>> resultFuture2 = endpoint.execute(new BasicRequestProducer(Method.POST, target, "/other-stuff", new StringAsyncEntityProducer("some other stuff", ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
        final Message<HttpResponse, String> message2 = resultFuture2.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
        assertThat(message2, CoreMatchers.notNullValue());
        final HttpResponse response2 = message2.getHead();
        assertThat(response2.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
        final String body2 = message2.getBody();
        assertThat(body2, CoreMatchers.equalTo("some other stuff"));
        final Future<Message<HttpResponse, String>> resultFuture3 = endpoint.execute(new BasicRequestProducer(Method.POST, target, "/more-stuff", new StringAsyncEntityProducer("some more stuff", ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
        final Message<HttpResponse, String> message3 = resultFuture3.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
        assertThat(message3, CoreMatchers.notNullValue());
        final HttpResponse response3 = message3.getHead();
        assertThat(response3.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
        final String body3 = message3.getBody();
        assertThat(body3, CoreMatchers.equalTo("some more stuff"));
    } finally {
        endpoint.releaseAndReuse();
    }
}
Also used : StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) Message(org.apache.hc.core5.http.Message) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) InetSocketAddress(java.net.InetSocketAddress) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) HttpResponse(org.apache.hc.core5.http.HttpResponse) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) HttpHost(org.apache.hc.core5.http.HttpHost) Test(org.junit.Test)

Example 48 with BasicResponseConsumer

use of org.apache.hc.core5.http.nio.support.BasicResponseConsumer in project httpcomponents-core by apache.

the class Http1ServerAndRequesterTest method testSequentialRequests.

@Test
public void testSequentialRequests() throws Exception {
    server.start();
    final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(0), scheme);
    final ListenerEndpoint listener = future.get();
    final InetSocketAddress address = (InetSocketAddress) listener.getAddress();
    requester.start();
    final HttpHost target = new HttpHost(scheme.id, "localhost", address.getPort());
    final Future<Message<HttpResponse, String>> resultFuture1 = requester.execute(new BasicRequestProducer(Method.POST, target, "/stuff", new StringAsyncEntityProducer("some stuff", ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), TIMEOUT, null);
    final Message<HttpResponse, String> message1 = resultFuture1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
    assertThat(message1, CoreMatchers.notNullValue());
    final HttpResponse response1 = message1.getHead();
    assertThat(response1.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
    final String body1 = message1.getBody();
    assertThat(body1, CoreMatchers.equalTo("some stuff"));
    final Future<Message<HttpResponse, String>> resultFuture2 = requester.execute(new BasicRequestProducer(Method.POST, target, "/other-stuff", new StringAsyncEntityProducer("some other stuff", ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), TIMEOUT, null);
    final Message<HttpResponse, String> message2 = resultFuture2.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
    assertThat(message2, CoreMatchers.notNullValue());
    final HttpResponse response2 = message2.getHead();
    assertThat(response2.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
    final String body2 = message2.getBody();
    assertThat(body2, CoreMatchers.equalTo("some other stuff"));
    final Future<Message<HttpResponse, String>> resultFuture3 = requester.execute(new BasicRequestProducer(Method.POST, target, "/more-stuff", new StringAsyncEntityProducer("some more stuff", ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), TIMEOUT, null);
    final Message<HttpResponse, String> message3 = resultFuture3.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
    assertThat(message3, CoreMatchers.notNullValue());
    final HttpResponse response3 = message3.getHead();
    assertThat(response3.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
    final String body3 = message3.getBody();
    assertThat(body3, CoreMatchers.equalTo("some more stuff"));
}
Also used : StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) HttpResponse(org.apache.hc.core5.http.HttpResponse) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) HttpHost(org.apache.hc.core5.http.HttpHost) Test(org.junit.Test)

Example 49 with BasicResponseConsumer

use of org.apache.hc.core5.http.nio.support.BasicResponseConsumer in project httpcomponents-core by apache.

the class Http1ServerAndRequesterTest method testSequentialRequestsNonPersistentConnection.

@Test
public void testSequentialRequestsNonPersistentConnection() throws Exception {
    server.start();
    final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(0), scheme);
    final ListenerEndpoint listener = future.get();
    final InetSocketAddress address = (InetSocketAddress) listener.getAddress();
    requester.start();
    final HttpHost target = new HttpHost(scheme.id, "localhost", address.getPort());
    final Future<Message<HttpResponse, String>> resultFuture1 = requester.execute(new BasicRequestProducer(Method.POST, target, "/no-keep-alive/stuff", new StringAsyncEntityProducer("some stuff", ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), TIMEOUT, null);
    final Message<HttpResponse, String> message1 = resultFuture1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
    assertThat(message1, CoreMatchers.notNullValue());
    final HttpResponse response1 = message1.getHead();
    assertThat(response1.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
    final String body1 = message1.getBody();
    assertThat(body1, CoreMatchers.equalTo("some stuff"));
    final Future<Message<HttpResponse, String>> resultFuture2 = requester.execute(new BasicRequestProducer(Method.POST, target, "/no-keep-alive/other-stuff", new StringAsyncEntityProducer("some other stuff", ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), TIMEOUT, null);
    final Message<HttpResponse, String> message2 = resultFuture2.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
    assertThat(message2, CoreMatchers.notNullValue());
    final HttpResponse response2 = message2.getHead();
    assertThat(response2.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
    final String body2 = message2.getBody();
    assertThat(body2, CoreMatchers.equalTo("some other stuff"));
    final Future<Message<HttpResponse, String>> resultFuture3 = requester.execute(new BasicRequestProducer(Method.POST, target, "/no-keep-alive/more-stuff", new StringAsyncEntityProducer("some more stuff", ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), TIMEOUT, null);
    final Message<HttpResponse, String> message3 = resultFuture3.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
    assertThat(message3, CoreMatchers.notNullValue());
    final HttpResponse response3 = message3.getHead();
    assertThat(response3.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
    final String body3 = message3.getBody();
    assertThat(body3, CoreMatchers.equalTo("some more stuff"));
}
Also used : StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) HttpResponse(org.apache.hc.core5.http.HttpResponse) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) HttpHost(org.apache.hc.core5.http.HttpHost) Test(org.junit.Test)

Example 50 with BasicResponseConsumer

use of org.apache.hc.core5.http.nio.support.BasicResponseConsumer in project httpcomponents-core by apache.

the class Http1ServerAndRequesterTest method testNonPersistentHeads.

@Test
public void testNonPersistentHeads() throws Exception {
    server.start();
    final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(0), scheme);
    final ListenerEndpoint listener = future.get();
    final InetSocketAddress address = (InetSocketAddress) listener.getAddress();
    requester.start();
    final HttpHost target = new HttpHost(scheme.id, "localhost", address.getPort());
    final Queue<Future<Message<HttpResponse, String>>> queue = new LinkedList<>();
    for (int i = 0; i < 20; i++) {
        final HttpRequest head = new BasicHttpRequest(Method.HEAD, target, "/no-keep-alive/stuff?p=" + i);
        queue.add(requester.execute(new BasicRequestProducer(head, null), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), TIMEOUT, null));
    }
    while (!queue.isEmpty()) {
        final Future<Message<HttpResponse, String>> resultFuture = queue.remove();
        final Message<HttpResponse, String> message = resultFuture.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
        assertThat(message, CoreMatchers.notNullValue());
        final HttpResponse response = message.getHead();
        assertThat(response.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
        assertThat(message.getBody(), CoreMatchers.nullValue());
    }
}
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) Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpResponse(org.apache.hc.core5.http.HttpResponse) LinkedList(java.util.LinkedList) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) HttpHost(org.apache.hc.core5.http.HttpHost) Future(java.util.concurrent.Future) BasicResponseConsumer(org.apache.hc.core5.http.nio.support.BasicResponseConsumer) Test(org.junit.Test)

Aggregations

StringAsyncEntityConsumer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer)94 Message (org.apache.hc.core5.http.Message)93 HttpResponse (org.apache.hc.core5.http.HttpResponse)92 BasicRequestProducer (org.apache.hc.core5.http.nio.support.BasicRequestProducer)86 InetSocketAddress (java.net.InetSocketAddress)84 Test (org.junit.Test)73 HttpRequest (org.apache.hc.core5.http.HttpRequest)41 BasicHttpRequest (org.apache.hc.core5.http.message.BasicHttpRequest)40 HttpHost (org.apache.hc.core5.http.HttpHost)38 BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)36 StringAsyncEntityProducer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer)30 IOException (java.io.IOException)27 ListenerEndpoint (org.apache.hc.core5.reactor.ListenerEndpoint)26 HttpException (org.apache.hc.core5.http.HttpException)25 BasicResponseConsumer (org.apache.hc.core5.http.nio.support.BasicResponseConsumer)23 InterruptedIOException (java.io.InterruptedIOException)22 Header (org.apache.hc.core5.http.Header)20 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)20 Future (java.util.concurrent.Future)18 ExecutionException (java.util.concurrent.ExecutionException)17