org.apache.http.HttpClientConnection Java Examples

The following examples show how to use org.apache.http.HttpClientConnection. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SimpleHttpClientConnectionManager.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
@Override
public ConnectionRequest requestConnection(HttpRoute route, Object state) {
  return new ConnectionRequest() {

    @Override
    public boolean cancel() {
      // Nothing to do.
      return false;
    }

    @Override
    public HttpClientConnection get(final long timeout, final TimeUnit timeUnit) {
      return connectionFactory.create(route, connectionConfig);
    }
  };
}
 
Example #2
Source File: LoggingHttpRequestExecutor.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected HttpResponse doSendRequest(final HttpRequest request, final HttpClientConnection conn, final HttpContext context) throws IOException, HttpException {
    synchronized(listener) {
        listener.log(TranscriptListener.Type.request, request.getRequestLine().toString());
        for(Header header : request.getAllHeaders()) {
            switch(header.getName()) {
                case HttpHeaders.AUTHORIZATION:
                case HttpHeaders.PROXY_AUTHORIZATION:
                case "X-Auth-Key":
                case "X-Auth-Token":
                    listener.log(TranscriptListener.Type.request, String.format("%s: %s", header.getName(),
                            StringUtils.repeat("*", Integer.min(8, StringUtils.length(header.getValue())))));
                    break;
                default:
                    listener.log(TranscriptListener.Type.request, header.toString());
                    break;
            }
        }
    }
    final HttpResponse response = super.doSendRequest(request, conn, context);
    if(null != response) {
        // response received as part of an expect-continue handshake
        this.log(response);
    }
    return response;
}
 
Example #3
Source File: SimpleHttpClientConnectionManager.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
@Override
public void connect(
    HttpClientConnection connection,
    HttpRoute route,
    int connectTimeout,
    HttpContext context
) throws IOException {
  HttpHost host;

  if (route.getProxyHost() != null) {
    host = route.getProxyHost();
  } else {
    host = route.getTargetHost();
  }

  InetSocketAddress localAddress = route.getLocalSocketAddress();

  ManagedHttpClientConnection managed = (ManagedHttpClientConnection) connection;
  this.connectionOperator.connect(managed, host, localAddress, connectTimeout, this.socketConfig, context);
}
 
Example #4
Source File: SdkHttpRequestExecutor.java    From ibm-cos-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
protected HttpResponse doReceiveResponse(
        final HttpRequest          request,
        final HttpClientConnection conn,
        final HttpContext          context)
            throws HttpException, IOException {
    AWSRequestMetrics awsRequestMetrics = (AWSRequestMetrics) context
            .getAttribute(AWSRequestMetrics.class.getSimpleName());
    if (awsRequestMetrics == null) {
        return super.doReceiveResponse(request, conn, context);
    }
    awsRequestMetrics.startEvent(Field.HttpClientReceiveResponseTime);
    try {
        return super.doReceiveResponse(request, conn, context);
    } finally {
        awsRequestMetrics.endEvent(Field.HttpClientReceiveResponseTime);
    }
}
 
Example #5
Source File: HttpClientIT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpPost post = new HttpPost(webServer.getCallHttpUrl());
        post.addHeader("Content-Type", "application/json;charset=UTF-8");

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        httpClient.execute(post, responseHandler);
    } catch (Exception ignored) {
    } finally {
        if (null != httpClient && null != httpClient.getConnectionManager()) {
            httpClient.getConnectionManager().shutdown();
        }
    }

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();

    Class<?> connectorClass;
    
    try {
        connectorClass = Class.forName("org.apache.http.impl.conn.ManagedClientConnectionImpl");
    } catch (ClassNotFoundException e) {
        connectorClass = Class.forName("org.apache.http.impl.conn.AbstractPooledConnAdapter");
    }
    
    verifier.verifyTrace(event("HTTP_CLIENT_4_INTERNAL", AbstractHttpClient.class.getMethod("execute", HttpUriRequest.class, ResponseHandler.class)));
    final String hostname = webServer.getHostAndPort();
    verifier.verifyTrace(event("HTTP_CLIENT_4_INTERNAL", connectorClass.getMethod("open", HttpRoute.class, HttpContext.class, HttpParams.class), annotation("http.internal.display", hostname)));
    verifier.verifyTrace(event("HTTP_CLIENT_4", HttpRequestExecutor.class.getMethod("execute", HttpRequest.class, HttpClientConnection.class, HttpContext.class), null, null, hostname, annotation("http.url", "/"), annotation("http.status.code", 200), annotation("http.io", anyAnnotationValue())));
    verifier.verifyTraceCount(0);
}
 
Example #6
Source File: ConnectionReuseTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void headerRequest(HttpHost target, HttpRoute route, HttpClientConnection conn, PoolingHttpClientConnectionManager cm)
    throws IOException, HttpException {
  HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);

  req.addHeader("Host", target.getHostName());
  if (!conn.isOpen()) {
    // establish connection based on its route info
    cm.connect(conn, route, 1000, context);
    // and mark it as route complete
    cm.routeComplete(conn, route, context);
  }
  conn.sendRequestHeader(req);
  conn.flush();
  conn.receiveResponseHeader();
}
 
Example #7
Source File: SimpleHttpClientConnectionManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public void releaseConnection(
    HttpClientConnection connection,
    Object newState,
    long validDuration,
    TimeUnit timeUnit
) {
  try {
    connection.close();
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #8
Source File: InstrumentedHttpRequestExecutor.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse execute(HttpRequest request, HttpClientConnection conn, HttpContext context) throws IOException, HttpException {
  Timer.Context timerContext = null;
  if (solrMetricsContext != null) {
    timerContext = timer(request).time();
  }
  try {
    return super.execute(request, conn, context);
  } finally {
    if (timerContext != null) {
      timerContext.stop();
    }
  }
}
 
Example #9
Source File: SimpleHttpFetcher.java    From ache with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse execute(HttpRequest request, HttpClientConnection conn, HttpContext context)
        throws IOException, HttpException {
    HttpInetConnection connection = (HttpInetConnection) conn;
    context.setAttribute(HOST_ADDRESS, connection.getRemoteAddress().getHostAddress());
    return super.execute(request, conn, context);
}
 
Example #10
Source File: SdkHttpRequestExecutor.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
protected HttpResponse doSendRequest(
        final HttpRequest request,
        final HttpClientConnection conn,
        final HttpContext context)
            throws IOException, HttpException {
    AWSRequestMetrics awsRequestMetrics = (AWSRequestMetrics) context
            .getAttribute(AWSRequestMetrics.class.getSimpleName());

    if (awsRequestMetrics == null) {
        return super.doSendRequest(request, conn, context);
    }
    if (conn instanceof ManagedHttpClientConnection) {
        ManagedHttpClientConnection managedConn = (ManagedHttpClientConnection)conn;
        Socket sock = managedConn.getSocket();
        if (sock instanceof SdkMetricsSocket) {
            SdkMetricsSocket sdkMetricsSocket = (SdkMetricsSocket)sock;
            sdkMetricsSocket.setMetrics(awsRequestMetrics);
        } else if (sock instanceof SdkSSLMetricsSocket) {
            SdkSSLMetricsSocket sdkSSLMetricsSocket = (SdkSSLMetricsSocket)sock;
            sdkSSLMetricsSocket.setMetrics(awsRequestMetrics);
        }
    }
    awsRequestMetrics.startEvent(Field.HttpClientSendRequestTime);
    try {
        return super.doSendRequest(request, conn, context);
    } finally {
        awsRequestMetrics.endEvent(Field.HttpClientSendRequestTime);
    }
}
 
Example #11
Source File: MockConnectionManager.java    From esigate with Apache License 2.0 5 votes vote down vote up
@Override
public void releaseConnection(HttpClientConnection conn, Object newState, long validDuration, TimeUnit timeUnit) {
    try {
        conn.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #12
Source File: LoggingHttpRequestExecutor.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
public HttpResponse execute(final HttpRequest request, final HttpClientConnection conn, final HttpContext context)
        throws IOException, HttpException {
    if(!request.containsHeader(HttpHeaders.USER_AGENT)) {
        request.addHeader(new BasicHeader(HttpHeaders.USER_AGENT, useragentProvider.get()));
    }
    return super.execute(request, conn, context);
}
 
Example #13
Source File: UDTProxyConfigurator.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
public HttpResponse execute(final HttpRequest request, final HttpClientConnection conn, final HttpContext context) throws IOException, HttpException {
    for(Header h : headers) {
        request.addHeader(new BasicHeader(h.getName(), h.getValue()));
    }
    return super.execute(request, conn, context);
}
 
Example #14
Source File: MicrometerHttpRequestExecutor.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse execute(HttpRequest request, HttpClientConnection conn, HttpContext context) throws IOException, HttpException {
    Timer.Sample timerSample = Timer.start(registry);

    Tag method = Tag.of("method", request.getRequestLine().getMethod());
    Tag uri = Tag.of("uri", uriMapper.apply(request));
    Tag status = STATUS_UNKNOWN;

    Tags routeTags = exportTagsForRoute ? HttpContextUtils.generateTagsForRoute(context) : Tags.empty();

    try {
        HttpResponse response = super.execute(request, conn, context);
        status = response != null ? Tag.of("status", Integer.toString(response.getStatusLine().getStatusCode())) : STATUS_CLIENT_ERROR;
        return response;
    } catch (IOException | HttpException | RuntimeException e) {
        status = STATUS_IO_ERROR;
        throw e;
    } finally {
        Iterable<Tag> tags = Tags.of(extraTags)
                .and(routeTags)
                .and(uri, method, status);

        timerSample.stop(Timer.builder(METER_NAME)
                .description("Duration of Apache HttpClient request execution")
                .tags(tags)
                .register(registry));
    }
}
 
Example #15
Source File: CloaeableHttpClientIT.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
@Test
public void test() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpGet httpget = new HttpGet(webServer.getCallHttpUrl());
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    instream.read();
                } catch (IOException ex) {
                    throw ex;
                } finally {
                    instream.close();
                }
            }
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
    
    verifier.verifyTrace(event("HTTP_CLIENT_4_INTERNAL", CloseableHttpClient.class.getMethod("execute", HttpUriRequest.class)));
    final String display = webServer.getHostAndPort();
    verifier.verifyTrace(event("HTTP_CLIENT_4_INTERNAL", PoolingHttpClientConnectionManager.class.getMethod("connect", HttpClientConnection.class, HttpRoute.class, int.class, HttpContext.class),
            annotation("http.internal.display", display)));

    final String destinationId = webServer.getHostAndPort();
    verifier.verifyTrace(event("HTTP_CLIENT_4",
            HttpRequestExecutor.class.getMethod("execute", HttpRequest.class, HttpClientConnection.class, HttpContext.class), null, null, destinationId,
            annotation("http.url", "/"),
            annotation("http.status.code", 200),
            annotation("http.io", anyAnnotationValue())));

    verifier.verifyTraceCount(0);
}
 
Example #16
Source File: MockConnectionManager.java    From esigate with Apache License 2.0 4 votes vote down vote up
@Override
public void routeComplete(HttpClientConnection conn, HttpRoute route, HttpContext context) {
    // Nothing to do
}
 
Example #17
Source File: DelegatingHttpClientConnectionManager.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
@Override
public void routeComplete(HttpClientConnection conn, HttpRoute route, HttpContext context) throws IOException {
  this.fallbackConnManager.routeComplete(conn, route, context);
}
 
Example #18
Source File: DelegatingHttpClientConnectionManager.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
@Override
public void upgrade(HttpClientConnection conn, HttpRoute route, HttpContext context) throws IOException {
  this.fallbackConnManager.upgrade(conn, route, context);
}
 
Example #19
Source File: DelegatingHttpClientConnectionManager.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
@Override
public void connect(HttpClientConnection conn, HttpRoute route, int connectTimeout, HttpContext context)
    throws IOException {
  this.fallbackConnManager.connect(conn, route, connectTimeout, context);
}
 
Example #20
Source File: DelegatingHttpClientConnectionManager.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
@Override
public void releaseConnection(HttpClientConnection conn, Object newState, long validDuration, TimeUnit timeUnit) {
  this.fallbackConnManager.releaseConnection(conn, newState, validDuration, timeUnit);
}
 
Example #21
Source File: MockConnectionManager.java    From esigate with Apache License 2.0 4 votes vote down vote up
@Override
public void connect(HttpClientConnection conn, HttpRoute route, int connectTimeout, HttpContext context) {
    if (this.responseHandler instanceof IResponseHandler2) {
        ((IResponseHandler2) this.responseHandler).connect(conn, route, connectTimeout, context);
    }
}
 
Example #22
Source File: SimpleHttpClientConnectionManager.java    From lavaplayer with Apache License 2.0 4 votes vote down vote up
@Override
public void routeComplete(HttpClientConnection conn, HttpRoute route, HttpContext context) {
  // Nothing to do.
}
 
Example #23
Source File: SimpleHttpClientConnectionManager.java    From lavaplayer with Apache License 2.0 4 votes vote down vote up
@Override
public void upgrade(HttpClientConnection connection, HttpRoute route, HttpContext context) throws IOException {
  ManagedHttpClientConnection managed = (ManagedHttpClientConnection) connection;
  this.connectionOperator.upgrade(managed, route.getTargetHost(), context);
}
 
Example #24
Source File: MockConnectionManager.java    From esigate with Apache License 2.0 4 votes vote down vote up
@Override
public void upgrade(HttpClientConnection conn, HttpRoute route, HttpContext context) {
    // Nothing to do
}
 
Example #25
Source File: RestClientTest.java    From hugegraph-common with Apache License 2.0 4 votes vote down vote up
@Test
public void testCleanExecutor() throws Exception {
    // Modify IDLE_TIME 100ms to speed test
    int newIdleTime = 100;
    int newCheckPeriod = newIdleTime + 20;

    RestClient client = new RestClientImpl("/test", 1000, newIdleTime,
                                           10, 5, 200);

    PoolingHttpClientConnectionManager pool;
    pool = Whitebox.getInternalState(client, "pool");
    pool = Mockito.spy(pool);
    Whitebox.setInternalState(client, "pool", pool);
    HttpRoute route = new HttpRoute(HttpHost.create(
                                    "http://127.0.0.1:8080"));
    // Create a connection manually, it will be put into leased list
    HttpClientConnection conn = pool.requestConnection(route, null)
                                    .get(1L, TimeUnit.SECONDS);
    PoolStats stats = pool.getTotalStats();
    int usingConns = stats.getLeased() + stats.getPending();
    Assert.assertGte(1, usingConns);

    // Sleep more than two check periods for busy connection
    Thread.sleep(newCheckPeriod);
    Mockito.verify(pool, Mockito.never()).closeExpiredConnections();
    stats = pool.getTotalStats();
    usingConns = stats.getLeased() + stats.getPending();
    Assert.assertGte(1, usingConns);

    // The connection will be put into available list
    pool.releaseConnection(conn, null, 0, TimeUnit.SECONDS);

    stats = pool.getTotalStats();
    usingConns = stats.getLeased() + stats.getPending();
    Assert.assertEquals(0, usingConns);
    /*
     * Sleep more than two check periods for free connection,
     * ensure connection has been closed
     */
    Thread.sleep(newCheckPeriod);
    Mockito.verify(pool, Mockito.atLeastOnce())
           .closeExpiredConnections();
    Mockito.verify(pool, Mockito.atLeastOnce())
           .closeIdleConnections(newIdleTime, TimeUnit.MILLISECONDS);
}
 
Example #26
Source File: ConnectionReuseTest.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public HttpClientConnection getConn(ConnectionRequest mConn)
    throws InterruptedException, ConnectionPoolTimeoutException, ExecutionException {
  HttpClientConnection conn = mConn.get(30, TimeUnit.SECONDS);

  return conn;
}
 
Example #27
Source File: ClientConnectionRequestFactoryTest.java    From ibm-cos-sdk-java with Apache License 2.0 4 votes vote down vote up
@Override
public HttpClientConnection get(long timeout, TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException {
    return null;
}
 
Example #28
Source File: ClientConnectionManagerFactoryTest.java    From ibm-cos-sdk-java with Apache License 2.0 4 votes vote down vote up
@Override
public void releaseConnection(HttpClientConnection conn,
                              Object newState,
                              long validDuration,
                              TimeUnit timeUnit) {
}
 
Example #29
Source File: IdleConnectionReaperTest.java    From ibm-cos-sdk-java with Apache License 2.0 4 votes vote down vote up
@Override
public void routeComplete(HttpClientConnection conn, HttpRoute route, HttpContext context) throws IOException {}
 
Example #30
Source File: IdleConnectionReaperTest.java    From ibm-cos-sdk-java with Apache License 2.0 4 votes vote down vote up
@Override
public void upgrade(HttpClientConnection conn, HttpRoute route, HttpContext context) throws IOException {}