Search in sources :

Example 21 with ProtocolVersion

use of org.apache.hc.core5.http.ProtocolVersion in project httpcomponents-client by apache.

the class CachingExecBase method generateViaHeader.

String generateViaHeader(final HttpMessage msg) {
    if (msg.getVersion() == null) {
        msg.setVersion(HttpVersion.DEFAULT);
    }
    final ProtocolVersion pv = msg.getVersion();
    final String existingEntry = viaHeaders.get(msg.getVersion());
    if (existingEntry != null) {
        return existingEntry;
    }
    final VersionInfo vi = VersionInfo.loadVersionInfo("org.apache.hc.client5", getClass().getClassLoader());
    final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE;
    final String value;
    final int major = pv.getMajor();
    final int minor = pv.getMinor();
    if (URIScheme.HTTP.same(pv.getProtocol())) {
        value = String.format("%d.%d localhost (Apache-HttpClient/%s (cache))", major, minor, release);
    } else {
        value = String.format("%s/%d.%d localhost (Apache-HttpClient/%s (cache))", pv.getProtocol(), major, minor, release);
    }
    viaHeaders.put(pv, value);
    return value;
}
Also used : VersionInfo(org.apache.hc.core5.util.VersionInfo) ProtocolVersion(org.apache.hc.core5.http.ProtocolVersion)

Example 22 with ProtocolVersion

use of org.apache.hc.core5.http.ProtocolVersion in project httpcomponents-client by apache.

the class RequestExpectContinue method process.

@Override
public void process(final HttpRequest request, final EntityDetails entity, final HttpContext context) throws HttpException, IOException {
    Args.notNull(request, "HTTP request");
    if (!request.containsHeader(HttpHeaders.EXPECT)) {
        final ProtocolVersion version = request.getVersion() != null ? request.getVersion() : HttpVersion.HTTP_1_1;
        // Do not send the expect header if request body is known to be empty
        if (entity != null && entity.getContentLength() != 0 && !version.lessEquals(HttpVersion.HTTP_1_0)) {
            final HttpClientContext clientContext = HttpClientContext.adapt(context);
            final RequestConfig config = clientContext.getRequestConfig();
            if (config.isExpectContinueEnabled()) {
                request.addHeader(HttpHeaders.EXPECT, HeaderElements.CONTINUE);
            }
        }
    }
}
Also used : RequestConfig(org.apache.hc.client5.http.config.RequestConfig) ProtocolVersion(org.apache.hc.core5.http.ProtocolVersion)

Example 23 with ProtocolVersion

use of org.apache.hc.core5.http.ProtocolVersion in project opentelemetry-java-instrumentation by open-telemetry.

the class ApacheHttpClientHttpAttributesGetter method flavor.

@Override
@Nullable
public String flavor(HttpRequest request, @Nullable HttpResponse response) {
    ProtocolVersion protocolVersion = getVersion(request, response);
    if (protocolVersion == null) {
        return null;
    }
    String protocol = protocolVersion.getProtocol();
    if (!protocol.equals("HTTP")) {
        return null;
    }
    int major = protocolVersion.getMajor();
    int minor = protocolVersion.getMinor();
    if (major == 1 && minor == 0) {
        return SemanticAttributes.HttpFlavorValues.HTTP_1_0;
    }
    if (major == 1 && minor == 1) {
        return SemanticAttributes.HttpFlavorValues.HTTP_1_1;
    }
    if (major == 2 && minor == 0) {
        return SemanticAttributes.HttpFlavorValues.HTTP_2_0;
    }
    logger.log(Level.FINE, "unexpected http protocol version: {0}", protocolVersion);
    return null;
}
Also used : ProtocolVersion(org.apache.hc.core5.http.ProtocolVersion) Nullable(javax.annotation.Nullable)

Example 24 with ProtocolVersion

use of org.apache.hc.core5.http.ProtocolVersion in project httpcomponents-client by apache.

the class PoolingAsyncClientConnectionManager method lease.

@Override
public Future<AsyncConnectionEndpoint> lease(final String id, final HttpRoute route, final Object state, final Timeout requestTimeout, final FutureCallback<AsyncConnectionEndpoint> callback) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("{} endpoint lease request ({}) {}", id, requestTimeout, ConnPoolSupport.formatStats(route, state, pool));
    }
    return new Future<AsyncConnectionEndpoint>() {

        final ConnectionConfig connectionConfig = resolveConnectionConfig(route);

        final BasicFuture<AsyncConnectionEndpoint> resultFuture = new BasicFuture<>(callback);

        final Future<PoolEntry<HttpRoute, ManagedAsyncClientConnection>> leaseFuture = pool.lease(route, state, requestTimeout, new FutureCallback<PoolEntry<HttpRoute, ManagedAsyncClientConnection>>() {

            @Override
            public void completed(final PoolEntry<HttpRoute, ManagedAsyncClientConnection> poolEntry) {
                if (poolEntry.hasConnection()) {
                    final TimeValue timeToLive = connectionConfig.getTimeToLive();
                    if (TimeValue.isNonNegative(timeToLive)) {
                        final Deadline deadline = Deadline.calculate(poolEntry.getCreated(), timeToLive);
                        if (deadline.isExpired()) {
                            poolEntry.discardConnection(CloseMode.GRACEFUL);
                        }
                    }
                }
                if (poolEntry.hasConnection()) {
                    final ManagedAsyncClientConnection connection = poolEntry.getConnection();
                    final TimeValue timeValue = connectionConfig.getValidateAfterInactivity();
                    if (connection.isOpen() && TimeValue.isNonNegative(timeValue)) {
                        final Deadline deadline = Deadline.calculate(poolEntry.getUpdated(), timeValue);
                        if (deadline.isExpired()) {
                            final ProtocolVersion protocolVersion = connection.getProtocolVersion();
                            if (protocolVersion != null && protocolVersion.greaterEquals(HttpVersion.HTTP_2_0)) {
                                connection.submitCommand(new PingCommand(new BasicPingHandler(result -> {
                                    if (result == null || !result) {
                                        if (LOG.isDebugEnabled()) {
                                            LOG.debug("{} connection {} is stale", id, ConnPoolSupport.getId(connection));
                                        }
                                        poolEntry.discardConnection(CloseMode.GRACEFUL);
                                    }
                                    leaseCompleted(poolEntry);
                                })), Command.Priority.IMMEDIATE);
                                return;
                            } else {
                                if (LOG.isDebugEnabled()) {
                                    LOG.debug("{} connection {} is closed", id, ConnPoolSupport.getId(connection));
                                }
                                poolEntry.discardConnection(CloseMode.IMMEDIATE);
                            }
                        }
                    }
                }
                leaseCompleted(poolEntry);
            }

            void leaseCompleted(final PoolEntry<HttpRoute, ManagedAsyncClientConnection> poolEntry) {
                final ManagedAsyncClientConnection connection = poolEntry.getConnection();
                if (connection != null) {
                    connection.activate();
                }
                if (LOG.isDebugEnabled()) {
                    LOG.debug("{} endpoint leased {}", id, ConnPoolSupport.formatStats(route, state, pool));
                }
                final AsyncConnectionEndpoint endpoint = new InternalConnectionEndpoint(poolEntry);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("{} acquired {}", id, ConnPoolSupport.getId(endpoint));
                }
                resultFuture.completed(endpoint);
            }

            @Override
            public void failed(final Exception ex) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("{} endpoint lease failed", id);
                }
                resultFuture.failed(ex);
            }

            @Override
            public void cancelled() {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("{} endpoint lease cancelled", id);
                }
                resultFuture.cancel();
            }
        });

        @Override
        public AsyncConnectionEndpoint get() throws InterruptedException, ExecutionException {
            return resultFuture.get();
        }

        @Override
        public AsyncConnectionEndpoint get(final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
            return resultFuture.get(timeout, unit);
        }

        @Override
        public boolean cancel(final boolean mayInterruptIfRunning) {
            return leaseFuture.cancel(mayInterruptIfRunning);
        }

        @Override
        public boolean isDone() {
            return resultFuture.isDone();
        }

        @Override
        public boolean isCancelled() {
            return resultFuture.isCancelled();
        }
    };
}
Also used : BasicPingHandler(org.apache.hc.core5.http2.nio.support.BasicPingHandler) Deadline(org.apache.hc.core5.util.Deadline) AsyncConnectionEndpoint(org.apache.hc.client5.http.nio.AsyncConnectionEndpoint) ProtocolVersion(org.apache.hc.core5.http.ProtocolVersion) TimeoutException(java.util.concurrent.TimeoutException) ConnectionShutdownException(org.apache.hc.client5.http.impl.ConnectionShutdownException) ExecutionException(java.util.concurrent.ExecutionException) PingCommand(org.apache.hc.core5.http2.nio.command.PingCommand) HttpRoute(org.apache.hc.client5.http.HttpRoute) PoolEntry(org.apache.hc.core5.pool.PoolEntry) BasicFuture(org.apache.hc.core5.concurrent.BasicFuture) Future(java.util.concurrent.Future) BasicFuture(org.apache.hc.core5.concurrent.BasicFuture) ComplexFuture(org.apache.hc.core5.concurrent.ComplexFuture) TimeUnit(java.util.concurrent.TimeUnit) ConnectionConfig(org.apache.hc.client5.http.config.ConnectionConfig) FutureCallback(org.apache.hc.core5.concurrent.FutureCallback) TimeValue(org.apache.hc.core5.util.TimeValue) ManagedAsyncClientConnection(org.apache.hc.client5.http.nio.ManagedAsyncClientConnection)

Example 25 with ProtocolVersion

use of org.apache.hc.core5.http.ProtocolVersion in project httpcomponents-client by apache.

the class PoolingAsyncClientConnectionManager method connect.

@Override
public Future<AsyncConnectionEndpoint> connect(final AsyncConnectionEndpoint endpoint, final ConnectionInitiator connectionInitiator, final Timeout timeout, final Object attachment, final HttpContext context, final FutureCallback<AsyncConnectionEndpoint> callback) {
    Args.notNull(endpoint, "Endpoint");
    Args.notNull(connectionInitiator, "Connection initiator");
    final InternalConnectionEndpoint internalEndpoint = cast(endpoint);
    final ComplexFuture<AsyncConnectionEndpoint> resultFuture = new ComplexFuture<>(callback);
    if (internalEndpoint.isConnected()) {
        resultFuture.completed(endpoint);
        return resultFuture;
    }
    final PoolEntry<HttpRoute, ManagedAsyncClientConnection> poolEntry = internalEndpoint.getPoolEntry();
    final HttpRoute route = poolEntry.getRoute();
    final HttpHost host;
    if (route.getProxyHost() != null) {
        host = route.getProxyHost();
    } else {
        host = route.getTargetHost();
    }
    final InetSocketAddress localAddress = route.getLocalSocketAddress();
    final ConnectionConfig connectionConfig = resolveConnectionConfig(route);
    final TlsConfig tlsConfig = resolveTlsConfig(host, attachment);
    final Timeout connectTimeout = timeout != null ? timeout : connectionConfig.getConnectTimeout();
    if (LOG.isDebugEnabled()) {
        LOG.debug("{} connecting endpoint to {} ({})", ConnPoolSupport.getId(endpoint), host, connectTimeout);
    }
    final Future<ManagedAsyncClientConnection> connectFuture = connectionOperator.connect(connectionInitiator, host, localAddress, connectTimeout, route.isTunnelled() ? TlsConfig.copy(tlsConfig).setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_1).build() : tlsConfig, context, new FutureCallback<ManagedAsyncClientConnection>() {

        @Override
        public void completed(final ManagedAsyncClientConnection connection) {
            try {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("{} connected {}", ConnPoolSupport.getId(endpoint), ConnPoolSupport.getId(connection));
                }
                final ProtocolVersion protocolVersion = connection.getProtocolVersion();
                context.setProtocolVersion(protocolVersion);
                final Timeout socketTimeout = connectionConfig.getSocketTimeout();
                if (socketTimeout != null) {
                    connection.setSocketTimeout(socketTimeout);
                }
                poolEntry.assignConnection(connection);
                resultFuture.completed(internalEndpoint);
            } catch (final RuntimeException ex) {
                resultFuture.failed(ex);
            }
        }

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

        @Override
        public void cancelled() {
            resultFuture.cancel();
        }
    });
    resultFuture.setDependency(connectFuture);
    return resultFuture;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) Timeout(org.apache.hc.core5.util.Timeout) AsyncConnectionEndpoint(org.apache.hc.client5.http.nio.AsyncConnectionEndpoint) ProtocolVersion(org.apache.hc.core5.http.ProtocolVersion) TimeoutException(java.util.concurrent.TimeoutException) ConnectionShutdownException(org.apache.hc.client5.http.impl.ConnectionShutdownException) ExecutionException(java.util.concurrent.ExecutionException) HttpRoute(org.apache.hc.client5.http.HttpRoute) HttpHost(org.apache.hc.core5.http.HttpHost) TlsConfig(org.apache.hc.client5.http.config.TlsConfig) ComplexFuture(org.apache.hc.core5.concurrent.ComplexFuture) ConnectionConfig(org.apache.hc.client5.http.config.ConnectionConfig) ManagedAsyncClientConnection(org.apache.hc.client5.http.nio.ManagedAsyncClientConnection)

Aggregations

ProtocolVersion (org.apache.hc.core5.http.ProtocolVersion)55 Test (org.junit.jupiter.api.Test)12 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)10 BasicClassicHttpRequest (org.apache.hc.core5.http.message.BasicClassicHttpRequest)9 ProtocolException (org.apache.hc.core5.http.ProtocolException)8 UnsupportedHttpVersionException (org.apache.hc.core5.http.UnsupportedHttpVersionException)8 BasicClassicHttpResponse (org.apache.hc.core5.http.message.BasicClassicHttpResponse)8 ClassicHttpRequest (org.apache.hc.core5.http.ClassicHttpRequest)7 Header (org.apache.hc.core5.http.Header)6 HttpException (org.apache.hc.core5.http.HttpException)6 HttpHost (org.apache.hc.core5.http.HttpHost)5 HttpResponse (org.apache.hc.core5.http.HttpResponse)4 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 AtomicReference (java.util.concurrent.atomic.AtomicReference)3 HeaderElement (org.apache.hc.core5.http.HeaderElement)3 ParseException (org.apache.hc.core5.http.ParseException)3 StringEntity (org.apache.hc.core5.http.io.entity.StringEntity)3 BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)3