Search in sources :

Example 11 with AsyncEntityProducer

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

the class TerminalAsyncServerFilter method handle.

@Override
public AsyncDataConsumer handle(final HttpRequest request, final EntityDetails entityDetails, final HttpContext context, final AsyncFilterChain.ResponseTrigger responseTrigger, final AsyncFilterChain chain) throws HttpException, IOException {
    final AsyncServerExchangeHandler exchangeHandler = handlerFactory.create(request, context);
    if (exchangeHandler != null) {
        exchangeHandler.handleRequest(request, entityDetails, new ResponseChannel() {

            @Override
            public void sendInformation(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException {
                responseTrigger.sendInformation(response);
            }

            @Override
            public void sendResponse(final HttpResponse response, final EntityDetails entityDetails, final HttpContext httpContext) throws HttpException, IOException {
                responseTrigger.submitResponse(response, entityDetails != null ? new AsyncEntityProducer() {

                    @Override
                    public void failed(final Exception cause) {
                        exchangeHandler.failed(cause);
                    }

                    @Override
                    public boolean isRepeatable() {
                        return false;
                    }

                    @Override
                    public long getContentLength() {
                        return entityDetails.getContentLength();
                    }

                    @Override
                    public String getContentType() {
                        return entityDetails.getContentType();
                    }

                    @Override
                    public String getContentEncoding() {
                        return entityDetails.getContentEncoding();
                    }

                    @Override
                    public boolean isChunked() {
                        return entityDetails.isChunked();
                    }

                    @Override
                    public Set<String> getTrailerNames() {
                        return entityDetails.getTrailerNames();
                    }

                    @Override
                    public int available() {
                        return exchangeHandler.available();
                    }

                    @Override
                    public void produce(final DataStreamChannel channel) throws IOException {
                        exchangeHandler.produce(channel);
                    }

                    @Override
                    public void releaseResources() {
                        exchangeHandler.releaseResources();
                    }
                } : null);
            }

            @Override
            public void pushPromise(final HttpRequest promise, final AsyncPushProducer pushProducer, final HttpContext httpContext) throws HttpException, IOException {
                responseTrigger.pushPromise(promise, pushProducer);
            }
        }, context);
        return exchangeHandler;
    }
    responseTrigger.submitResponse(new BasicHttpResponse(HttpStatus.SC_NOT_FOUND), AsyncEntityProducers.create("Not found"));
    return null;
}
Also used : HttpRequest(org.apache.hc.core5.http.HttpRequest) Set(java.util.Set) AsyncPushProducer(org.apache.hc.core5.http.nio.AsyncPushProducer) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) IOException(java.io.IOException) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) ResponseChannel(org.apache.hc.core5.http.nio.ResponseChannel) AsyncEntityProducer(org.apache.hc.core5.http.nio.AsyncEntityProducer) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) EntityDetails(org.apache.hc.core5.http.EntityDetails) HttpException(org.apache.hc.core5.http.HttpException) AsyncServerExchangeHandler(org.apache.hc.core5.http.nio.AsyncServerExchangeHandler)

Example 12 with AsyncEntityProducer

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

the class AsyncRequestBuilder method build.

@Override
public AsyncRequestProducer build() {
    String path = getPath();
    if (TextUtils.isEmpty(path)) {
        path = "/";
    }
    AsyncEntityProducer entityProducerCopy = entityProducer;
    final String method = getMethod();
    final List<NameValuePair> parameters = getParameters();
    if (parameters != null && !parameters.isEmpty()) {
        final Charset charset = getCharset();
        if (entityProducerCopy == null && (Method.POST.isSame(method) || Method.PUT.isSame(method))) {
            final String content = WWWFormCodec.format(parameters, charset != null ? charset : ContentType.APPLICATION_FORM_URLENCODED.getCharset());
            entityProducerCopy = new StringAsyncEntityProducer(content, ContentType.APPLICATION_FORM_URLENCODED);
        } else {
            try {
                final URI uri = new URIBuilder(path).setCharset(charset).addParameters(parameters).build();
                path = uri.toASCIIString();
            } catch (final URISyntaxException ex) {
            // should never happen
            }
        }
    }
    if (entityProducerCopy != null && Method.TRACE.isSame(method)) {
        throw new IllegalStateException(Method.TRACE + " requests may not include an entity");
    }
    final BasicHttpRequest request = new BasicHttpRequest(method, getScheme(), getAuthority(), path);
    request.setVersion(getVersion());
    request.setHeaders(getHeaders());
    request.setAbsoluteRequestUri(isAbsoluteRequestUri());
    return new BasicRequestProducer(request, entityProducerCopy);
}
Also used : NameValuePair(org.apache.hc.core5.http.NameValuePair) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) BasicAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.BasicAsyncEntityProducer) AsyncEntityProducer(org.apache.hc.core5.http.nio.AsyncEntityProducer) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) Charset(java.nio.charset.Charset) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) URIBuilder(org.apache.hc.core5.net.URIBuilder)

Example 13 with AsyncEntityProducer

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

the class AsyncServerExpectationFilter method handle.

@Override
public final AsyncDataConsumer handle(final HttpRequest request, final EntityDetails entityDetails, final HttpContext context, final AsyncFilterChain.ResponseTrigger responseTrigger, final AsyncFilterChain chain) throws HttpException, IOException {
    if (entityDetails != null) {
        final Header h = request.getFirstHeader(HttpHeaders.EXPECT);
        if (h != null && HeaderElements.CONTINUE.equalsIgnoreCase(h.getValue())) {
            final boolean verified = verify(request, context);
            if (verified) {
                responseTrigger.sendInformation(new BasicHttpResponse(HttpStatus.SC_CONTINUE));
            } else {
                final HttpResponse expectationFailed = new BasicHttpResponse(HttpStatus.SC_EXPECTATION_FAILED);
                final AsyncEntityProducer responseContentProducer = generateResponseContent(expectationFailed);
                responseTrigger.submitResponse(expectationFailed, responseContentProducer);
                return null;
            }
        }
    }
    return chain.proceed(request, entityDetails, context, responseTrigger);
}
Also used : BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) AsyncEntityProducer(org.apache.hc.core5.http.nio.AsyncEntityProducer) Header(org.apache.hc.core5.http.Header) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse)

Example 14 with AsyncEntityProducer

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

the class AsyncServerFilterChainExchangeHandlerFactory method create.

@Override
public AsyncServerExchangeHandler create(final HttpRequest request, final HttpContext context) throws HttpException {
    return new AsyncServerExchangeHandler() {

        private final AtomicReference<AsyncDataConsumer> dataConsumerRef = new AtomicReference<>();

        private final AtomicReference<AsyncResponseProducer> responseProducerRef = new AtomicReference<>();

        @Override
        public void handleRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context) throws HttpException, IOException {
            dataConsumerRef.set(filterChain.handle(request, entityDetails, context, new AsyncFilterChain.ResponseTrigger() {

                @Override
                public void sendInformation(final HttpResponse response) throws HttpException, IOException {
                    responseChannel.sendInformation(response, context);
                }

                @Override
                public void submitResponse(final HttpResponse response, final AsyncEntityProducer entityProducer) throws HttpException, IOException {
                    final AsyncResponseProducer responseProducer = new BasicResponseProducer(response, entityProducer);
                    responseProducerRef.set(responseProducer);
                    responseProducer.sendResponse(responseChannel, context);
                }

                @Override
                public void pushPromise(final HttpRequest promise, final AsyncPushProducer responseProducer) throws HttpException, IOException {
                    responseChannel.pushPromise(promise, responseProducer, context);
                }
            }));
        }

        @Override
        public void failed(final Exception cause) {
            if (exceptionCallback != null) {
                exceptionCallback.execute(cause);
            }
            final AsyncResponseProducer handler = responseProducerRef.get();
            if (handler != null) {
                handler.failed(cause);
            }
        }

        @Override
        public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
            final AsyncDataConsumer dataConsumer = dataConsumerRef.get();
            if (dataConsumer != null) {
                dataConsumer.updateCapacity(capacityChannel);
            } else {
                capacityChannel.update(Integer.MAX_VALUE);
            }
        }

        @Override
        public void consume(final ByteBuffer src) throws IOException {
            final AsyncDataConsumer dataConsumer = dataConsumerRef.get();
            if (dataConsumer != null) {
                dataConsumer.consume(src);
            }
        }

        @Override
        public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
            final AsyncDataConsumer dataConsumer = dataConsumerRef.get();
            if (dataConsumer != null) {
                dataConsumer.streamEnd(trailers);
            }
        }

        @Override
        public int available() {
            final AsyncResponseProducer responseProducer = responseProducerRef.get();
            Asserts.notNull(responseProducer, "Response producer");
            return responseProducer.available();
        }

        @Override
        public void produce(final DataStreamChannel channel) throws IOException {
            final AsyncResponseProducer responseProducer = responseProducerRef.get();
            Asserts.notNull(responseProducer, "Response producer");
            responseProducer.produce(channel);
        }

        @Override
        public void releaseResources() {
            final AsyncDataConsumer dataConsumer = dataConsumerRef.getAndSet(null);
            if (dataConsumer != null) {
                dataConsumer.releaseResources();
            }
            final AsyncResponseProducer responseProducer = responseProducerRef.getAndSet(null);
            if (responseProducer != null) {
                responseProducer.releaseResources();
            }
        }
    };
}
Also used : HttpRequest(org.apache.hc.core5.http.HttpRequest) AsyncPushProducer(org.apache.hc.core5.http.nio.AsyncPushProducer) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) ByteBuffer(java.nio.ByteBuffer) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) ResponseChannel(org.apache.hc.core5.http.nio.ResponseChannel) AsyncResponseProducer(org.apache.hc.core5.http.nio.AsyncResponseProducer) AsyncEntityProducer(org.apache.hc.core5.http.nio.AsyncEntityProducer) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) Header(org.apache.hc.core5.http.Header) EntityDetails(org.apache.hc.core5.http.EntityDetails) AsyncDataConsumer(org.apache.hc.core5.http.nio.AsyncDataConsumer) List(java.util.List) AsyncServerExchangeHandler(org.apache.hc.core5.http.nio.AsyncServerExchangeHandler)

Example 15 with AsyncEntityProducer

use of org.apache.hc.core5.http.nio.AsyncEntityProducer in project mercury by yellow013.

the class AsyncClientMessageTrailers method main.

public static final void main(final String[] args) throws Exception {
    final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(Timeout.ofSeconds(5)).build();
    final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setIOReactorConfig(ioReactorConfig).addExecInterceptorAfter(ChainElement.PROTOCOL.name(), "custom", new AsyncExecChainHandler() {

        @Override
        public void execute(final HttpRequest request, final AsyncEntityProducer entityProducer, final AsyncExecChain.Scope scope, final AsyncExecChain chain, final AsyncExecCallback asyncExecCallback) throws HttpException, IOException {
            // Send MD5 hash in a trailer by decorating the original entity producer
            chain.proceed(request, entityProducer != null ? new DigestingEntityProducer("MD5", entityProducer) : null, scope, asyncExecCallback);
        }
    }).build();
    client.start();
    final SimpleHttpRequest request = SimpleRequestBuilder.post("http://httpbin.org/post").setBody("some stuff", ContentType.TEXT_PLAIN).build();
    System.out.println("Executing request " + request);
    final Future<SimpleHttpResponse> future = client.execute(SimpleRequestProducer.create(request), SimpleResponseConsumer.create(), new FutureCallback<SimpleHttpResponse>() {

        @Override
        public void completed(final SimpleHttpResponse response) {
            System.out.println(request + "->" + new StatusLine(response));
            System.out.println(response.getBody());
        }

        @Override
        public void failed(final Exception ex) {
            System.out.println(request + "->" + ex);
        }

        @Override
        public void cancelled() {
            System.out.println(request + " cancelled");
        }
    });
    future.get();
    System.out.println("Shutting down");
    client.close(CloseMode.GRACEFUL);
}
Also used : HttpRequest(org.apache.hc.core5.http.HttpRequest) SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) AsyncExecCallback(org.apache.hc.client5.http.async.AsyncExecCallback) DigestingEntityProducer(org.apache.hc.core5.http.nio.entity.DigestingEntityProducer) AsyncExecChain(org.apache.hc.client5.http.async.AsyncExecChain) SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) AsyncExecChainHandler(org.apache.hc.client5.http.async.AsyncExecChainHandler) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) StatusLine(org.apache.hc.core5.http.message.StatusLine) AsyncEntityProducer(org.apache.hc.core5.http.nio.AsyncEntityProducer) CloseableHttpAsyncClient(org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient)

Aggregations

AsyncEntityProducer (org.apache.hc.core5.http.nio.AsyncEntityProducer)27 DataStreamChannel (org.apache.hc.core5.http.nio.DataStreamChannel)18 Test (org.junit.jupiter.api.Test)16 WritableByteChannelMock (org.apache.hc.core5.http.WritableByteChannelMock)14 BasicDataStreamChannel (org.apache.hc.core5.http.nio.BasicDataStreamChannel)14 IOException (java.io.IOException)8 HttpException (org.apache.hc.core5.http.HttpException)8 HttpResponse (org.apache.hc.core5.http.HttpResponse)8 HttpRequest (org.apache.hc.core5.http.HttpRequest)7 Header (org.apache.hc.core5.http.Header)6 BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)6 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)6 EntityDetails (org.apache.hc.core5.http.EntityDetails)5 ByteBuffer (java.nio.ByteBuffer)4 Path (java.nio.file.Path)4 BasicHttpRequest (org.apache.hc.core5.http.message.BasicHttpRequest)4 List (java.util.List)3 AsyncDataConsumer (org.apache.hc.core5.http.nio.AsyncDataConsumer)3 AsyncServerExchangeHandler (org.apache.hc.core5.http.nio.AsyncServerExchangeHandler)3 CapacityChannel (org.apache.hc.core5.http.nio.CapacityChannel)3