Search in sources :

Example 1 with ProtocolException

use of org.apache.hc.core5.http.ProtocolException in project cxf by apache.

the class AsyncHTTPConduitFactory method setupNIOClient.

public synchronized void setupNIOClient(HTTPClientPolicy clientPolicy) {
    if (client != null) {
        return;
    }
    final IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(ioThreadCount).setSelectInterval(TimeValue.ofMilliseconds(selectInterval)).setSoLinger(TimeValue.ofMilliseconds(soLinger)).setSoTimeout(Timeout.ofMilliseconds(soTimeout)).setSoKeepAlive(soKeepalive).setTcpNoDelay(tcpNoDelay).build();
    final Registry<TlsStrategy> tlsStrategy = RegistryBuilder.<TlsStrategy>create().register("https", DefaultClientTlsStrategy.getSystemDefault()).build();
    connectionManager = new PoolingAsyncClientConnectionManager(tlsStrategy, PoolConcurrencyPolicy.STRICT, PoolReusePolicy.LIFO, TimeValue.ofMilliseconds(connectionTTL), DefaultSchemePortResolver.INSTANCE, SystemDefaultDnsResolver.INSTANCE);
    connectionManager.setDefaultMaxPerRoute(maxPerRoute);
    connectionManager.setMaxTotal(maxConnections);
    final RedirectStrategy redirectStrategy = new RedirectStrategy() {

        public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
            return false;
        }

        public URI getLocationURI(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
            return null;
        }
    };
    final HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom().setConnectionManager(connectionManager).setRedirectStrategy(redirectStrategy).setDefaultCookieStore(new BasicCookieStore() {

        private static final long serialVersionUID = 1L;

        public void addCookie(Cookie cookie) {
        }
    });
    adaptClientBuilder(httpAsyncClientBuilder);
    client = httpAsyncClientBuilder.setIOReactorConfig(config).build();
    // Start the client thread
    client.start();
    // Always start the idle checker thread to validate pending requests and
    // use the ConnectionMaxIdle to close the idle connection
    new CloseIdleConnectionThread(connectionManager, client).start();
}
Also used : TlsStrategy(org.apache.hc.core5.http.nio.ssl.TlsStrategy) DefaultClientTlsStrategy(org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy) HttpRequest(org.apache.hc.core5.http.HttpRequest) Cookie(org.apache.hc.client5.http.cookie.Cookie) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) HttpAsyncClientBuilder(org.apache.hc.client5.http.impl.async.HttpAsyncClientBuilder) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) BasicCookieStore(org.apache.hc.client5.http.cookie.BasicCookieStore) PoolingAsyncClientConnectionManager(org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager) RedirectStrategy(org.apache.hc.client5.http.protocol.RedirectStrategy)

Example 2 with ProtocolException

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

the class ReactiveRandomProcessor method processRequest.

@Override
public void processRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context, final Publisher<ByteBuffer> requestBody, final Callback<Publisher<ByteBuffer>> responseBodyCallback) throws HttpException, IOException {
    final String method = request.getMethod();
    if (!"GET".equalsIgnoreCase(method) && !"HEAD".equalsIgnoreCase(method) && !"POST".equalsIgnoreCase(method) && !"PUT".equalsIgnoreCase(method)) {
        throw new MethodNotSupportedException(method + " not supported by " + getClass().getName());
    }
    final URI uri;
    try {
        uri = request.getUri();
    } catch (final URISyntaxException ex) {
        throw new ProtocolException(ex.getMessage(), ex);
    }
    final String path = uri.getPath();
    final int slash = path.lastIndexOf('/');
    if (slash != -1) {
        final String payload = path.substring(slash + 1);
        final long n;
        if (!payload.isEmpty()) {
            try {
                n = Long.parseLong(payload);
            } catch (final NumberFormatException ex) {
                throw new ProtocolException("Invalid request path: " + path);
            }
        } else {
            // random length, but make sure at least something is sent
            n = 1 + (int) (Math.random() * 79.0);
        }
        if (new BasicHeader(HttpHeaders.EXPECT, HeaderElements.CONTINUE).equals(request.getHeader(HttpHeaders.EXPECT))) {
            responseChannel.sendInformation(new BasicHttpResponse(100), context);
        }
        final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_OK);
        final Flowable<ByteBuffer> stream = ReactiveTestUtils.produceStream(n);
        final String hash = ReactiveTestUtils.getStreamHash(n);
        response.addHeader("response-hash-code", hash);
        final BasicEntityDetails basicEntityDetails = new BasicEntityDetails(n, ContentType.APPLICATION_OCTET_STREAM);
        responseChannel.sendResponse(response, basicEntityDetails, context);
        responseBodyCallback.execute(stream);
    } else {
        throw new ProtocolException("Invalid request path: " + path);
    }
}
Also used : ProtocolException(org.apache.hc.core5.http.ProtocolException) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) ByteBuffer(java.nio.ByteBuffer) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) MethodNotSupportedException(org.apache.hc.core5.http.MethodNotSupportedException) BasicEntityDetails(org.apache.hc.core5.http.impl.BasicEntityDetails) BasicHeader(org.apache.hc.core5.http.message.BasicHeader)

Example 3 with ProtocolException

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

the class ClientH2StreamHandler method consumeHeader.

@Override
public void consumeHeader(final List<Header> headers, final boolean endStream) throws HttpException, IOException {
    if (done.get()) {
        throw new ProtocolException("Unexpected message headers");
    }
    switch(responseState) {
        case HEADERS:
            final HttpResponse response = DefaultH2ResponseConverter.INSTANCE.convert(headers);
            final int status = response.getCode();
            if (status < HttpStatus.SC_INFORMATIONAL) {
                throw new ProtocolException("Invalid response: " + new StatusLine(response));
            }
            if (status > HttpStatus.SC_CONTINUE && status < HttpStatus.SC_SUCCESS) {
                exchangeHandler.consumeInformation(response, context);
            }
            if (requestState == MessageState.ACK) {
                if (status == HttpStatus.SC_CONTINUE || status >= HttpStatus.SC_SUCCESS) {
                    requestState = MessageState.BODY;
                    exchangeHandler.produce(dataChannel);
                }
            }
            if (status < HttpStatus.SC_SUCCESS) {
                return;
            }
            final EntityDetails entityDetails = endStream ? null : new IncomingEntityDetails(response, -1);
            context.setAttribute(HttpCoreContext.HTTP_RESPONSE, response);
            httpProcessor.process(response, entityDetails, context);
            connMetrics.incrementResponseCount();
            exchangeHandler.consumeResponse(response, entityDetails, context);
            responseState = endStream ? MessageState.COMPLETE : MessageState.BODY;
            break;
        case BODY:
            responseState = MessageState.COMPLETE;
            exchangeHandler.streamEnd(headers);
            break;
        default:
            throw new ProtocolException("Unexpected message headers");
    }
}
Also used : StatusLine(org.apache.hc.core5.http.message.StatusLine) ProtocolException(org.apache.hc.core5.http.ProtocolException) EntityDetails(org.apache.hc.core5.http.EntityDetails) IncomingEntityDetails(org.apache.hc.core5.http.impl.IncomingEntityDetails) HttpResponse(org.apache.hc.core5.http.HttpResponse) IncomingEntityDetails(org.apache.hc.core5.http.impl.IncomingEntityDetails)

Example 4 with ProtocolException

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

the class H2MultiplexingRequester method execute.

private void execute(final AsyncClientExchangeHandler exchangeHandler, final HandlerFactory<AsyncPushConsumer> pushHandlerFactory, final CancellableDependency cancellableDependency, final Timeout timeout, final HttpContext context) {
    Args.notNull(exchangeHandler, "Exchange handler");
    Args.notNull(timeout, "Timeout");
    Args.notNull(context, "Context");
    try {
        exchangeHandler.produceRequest((request, entityDetails, httpContext) -> {
            final String scheme = request.getScheme();
            final URIAuthority authority = request.getAuthority();
            if (authority == null) {
                throw new ProtocolException("Request authority not specified");
            }
            final HttpHost target = new HttpHost(scheme, authority);
            connPool.getSession(target, timeout, new FutureCallback<IOSession>() {

                @Override
                public void completed(final IOSession ioSession) {
                    ioSession.enqueue(new RequestExecutionCommand(new AsyncClientExchangeHandler() {

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

                        @Override
                        public void produceRequest(final RequestChannel channel, final HttpContext httpContext) throws HttpException, IOException {
                            channel.sendRequest(request, entityDetails, httpContext);
                        }

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

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

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

                        @Override
                        public void consumeResponse(final HttpResponse response, final EntityDetails entityDetails, final HttpContext httpContext) throws HttpException, IOException {
                            exchangeHandler.consumeResponse(response, entityDetails, httpContext);
                        }

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

                        @Override
                        public void consume(final ByteBuffer src) throws IOException {
                            exchangeHandler.consume(src);
                        }

                        @Override
                        public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
                            exchangeHandler.streamEnd(trailers);
                        }

                        @Override
                        public void cancel() {
                            exchangeHandler.cancel();
                        }

                        @Override
                        public void failed(final Exception cause) {
                            exchangeHandler.failed(cause);
                        }
                    }, pushHandlerFactory, cancellableDependency, context), Command.Priority.NORMAL);
                    if (!ioSession.isOpen()) {
                        exchangeHandler.failed(new ConnectionClosedException());
                    }
                }

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

                @Override
                public void cancelled() {
                    exchangeHandler.cancel();
                }
            });
        }, context);
    } catch (final IOException | HttpException ex) {
        exchangeHandler.failed(ex);
    }
}
Also used : ProtocolException(org.apache.hc.core5.http.ProtocolException) URIAuthority(org.apache.hc.core5.net.URIAuthority) AsyncClientExchangeHandler(org.apache.hc.core5.http.nio.AsyncClientExchangeHandler) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) ConnectionClosedException(org.apache.hc.core5.http.ConnectionClosedException) IOException(java.io.IOException) RequestExecutionCommand(org.apache.hc.core5.http.nio.command.RequestExecutionCommand) ByteBuffer(java.nio.ByteBuffer) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) HttpException(org.apache.hc.core5.http.HttpException) ProtocolException(org.apache.hc.core5.http.ProtocolException) IOException(java.io.IOException) ConnectionClosedException(org.apache.hc.core5.http.ConnectionClosedException) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) HttpHost(org.apache.hc.core5.http.HttpHost) EntityDetails(org.apache.hc.core5.http.EntityDetails) IOSession(org.apache.hc.core5.reactor.IOSession) HttpException(org.apache.hc.core5.http.HttpException) RequestChannel(org.apache.hc.core5.http.nio.RequestChannel)

Example 5 with ProtocolException

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

the class DefaultH2ResponseConverter method convert.

@Override
public List<Header> convert(final HttpResponse message) throws HttpException {
    final int code = message.getCode();
    if (code < 100 || code >= 600) {
        throw new ProtocolException("Response status %s is invalid", code);
    }
    final List<Header> headers = new ArrayList<>();
    headers.add(new BasicHeader(H2PseudoResponseHeaders.STATUS, Integer.toString(code), false));
    for (final Iterator<Header> it = message.headerIterator(); it.hasNext(); ) {
        final Header header = it.next();
        final String name = header.getName();
        final String value = header.getValue();
        if (name.startsWith(":")) {
            throw new ProtocolException("Header name '%s' is invalid", name);
        }
        if (name.equalsIgnoreCase(HttpHeaders.CONNECTION) || name.equalsIgnoreCase(HttpHeaders.KEEP_ALIVE) || name.equalsIgnoreCase(HttpHeaders.TRANSFER_ENCODING) || name.equalsIgnoreCase(HttpHeaders.UPGRADE)) {
            throw new ProtocolException("Header '%s: %s' is illegal for HTTP/2 messages", header.getName(), header.getValue());
        }
        headers.add(new BasicHeader(TextUtils.toLowerCase(name), value));
    }
    return headers;
}
Also used : ProtocolException(org.apache.hc.core5.http.ProtocolException) Header(org.apache.hc.core5.http.Header) BasicHeader(org.apache.hc.core5.http.message.BasicHeader) ArrayList(java.util.ArrayList) BasicHeader(org.apache.hc.core5.http.message.BasicHeader)

Aggregations

ProtocolException (org.apache.hc.core5.http.ProtocolException)28 HttpResponse (org.apache.hc.core5.http.HttpResponse)10 Header (org.apache.hc.core5.http.Header)9 EntityDetails (org.apache.hc.core5.http.EntityDetails)8 ProtocolVersion (org.apache.hc.core5.http.ProtocolVersion)8 URISyntaxException (java.net.URISyntaxException)6 HttpException (org.apache.hc.core5.http.HttpException)6 HttpRequest (org.apache.hc.core5.http.HttpRequest)6 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)6 IOException (java.io.IOException)5 BasicHeader (org.apache.hc.core5.http.message.BasicHeader)5 BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)5 ByteBuffer (java.nio.ByteBuffer)4 ArrayList (java.util.ArrayList)4 URIAuthority (org.apache.hc.core5.net.URIAuthority)4 InetSocketAddress (java.net.InetSocketAddress)3 URI (java.net.URI)3 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)3 ConnectionClosedException (org.apache.hc.core5.http.ConnectionClosedException)3 Message (org.apache.hc.core5.http.Message)3