Java 类org.apache.http.HttpClientConnection 实例源码

项目:cyberduck    文件:LoggingHttpRequestExecutor.java   
@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 "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;
            }
        }
    }
    return super.doSendRequest(request, conn, context);
}
项目:fastcrawler    文件:SniPoolingHttpClientConnectionManager.java   
@Override
public void connect(final HttpClientConnection conn, final HttpRoute route,
                    final int connectTimeout, final HttpContext context) throws IOException {
    try {
        super.connect(conn, route, connectTimeout, context);
    } catch (SSLProtocolException e) {
        Boolean enableSniValue =
            (Boolean) context.getAttribute(SniSSLConnectionSocketFactory.ENABLE_SNI);
        boolean enableSni = enableSniValue == null || enableSniValue;
        if (enableSni && e.getMessage() != null &&
            e.getMessage().equals("handshake alert:  unrecognized_name")) {
            logger.warn("Server saw wrong SNI host, retrying without SNI");
            context.setAttribute(SniSSLConnectionSocketFactory.ENABLE_SNI, false);
            super.connect(conn, route, connectTimeout, context);
        } else {
            throw e;
        }
    }
}
项目:ibm-cos-sdk-java    文件:SdkHttpRequestExecutor.java   
@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);
    }
}
项目:remote-files-sync    文件:BasicHttpClientConnectionManager.java   
public final ConnectionRequest requestConnection(
        final HttpRoute route,
        final Object state) {
    Args.notNull(route, "Route");
    return new ConnectionRequest() {

        public boolean cancel() {
            // Nothing to abort, since requests are immediate.
            return false;
        }

        public HttpClientConnection get(final long timeout, final TimeUnit tunit) {
            return BasicHttpClientConnectionManager.this.getConnection(
                    route, state);
        }

    };
}
项目:remote-files-sync    文件:BasicHttpClientConnectionManager.java   
synchronized HttpClientConnection getConnection(final HttpRoute route, final Object state) {
    Asserts.check(!this.isShutdown.get(), "Connection manager has been shut down");
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Get connection for route " + route);
    }
    Asserts.check(!this.leased, "Connection is still allocated");
    if (!LangUtils.equals(this.route, route) || !LangUtils.equals(this.state, state)) {
        closeConnection();
    }
    this.route = route;
    this.state = state;
    checkExpiry();
    if (this.conn == null) {
        this.conn = this.connFactory.create(route, this.connConfig);
    }
    this.leased = true;
    return this.conn;
}
项目:remote-files-sync    文件:BasicHttpClientConnectionManager.java   
public void connect(
        final HttpClientConnection conn,
        final HttpRoute route,
        final int connectTimeout,
        final HttpContext context) throws IOException {
    Args.notNull(conn, "Connection");
    Args.notNull(route, "HTTP route");
    Asserts.check(conn == this.conn, "Connection not obtained from this manager");
    final HttpHost host;
    if (route.getProxyHost() != null) {
        host = route.getProxyHost();
    } else {
        host = route.getTargetHost();
    }
    final InetSocketAddress localAddress = route.getLocalAddress() != null ? new InetSocketAddress(route.getLocalAddress(), 0) : null;;
    this.connectionOperator.connect(this.conn, host, localAddress,
            connectTimeout, this.socketConfig, context);
}
项目:remote-files-sync    文件:PoolingHttpClientConnectionManager.java   
public ConnectionRequest requestConnection(
        final HttpRoute route,
        final Object state) {
    Args.notNull(route, "HTTP route");
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Connection request: " + format(route, state) + formatStats(route));
    }
    final Future<CPoolEntry> future = this.pool.lease(route, state, null);
    return new ConnectionRequest() {

        public boolean cancel() {
            return future.cancel(true);
        }

        public HttpClientConnection get(
                final long timeout,
                final TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException {
            return leaseConnection(future, timeout, tunit);
        }

    };

}
项目:remote-files-sync    文件:PoolingHttpClientConnectionManager.java   
protected HttpClientConnection leaseConnection(
        final Future<CPoolEntry> future,
        final long timeout,
        final TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException {
    final CPoolEntry entry;
    try {
        entry = future.get(timeout, tunit);
        if (entry == null || future.isCancelled()) {
            throw new InterruptedException();
        }
        Asserts.check(entry.getConnection() != null, "Pool entry with no connection");
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "Connection leased: " + format(entry) + formatStats(entry.getRoute()));
        }
        return CPoolProxy.newProxy(entry);
    } catch (final TimeoutException ex) {
        throw new ConnectionPoolTimeoutException("Timeout waiting for connection from pool");
    }
}
项目:purecloud-iot    文件:TestBasicHttpClientConnectionManager.java   
@Test
public void testLeaseReleaseNonReusable() throws Exception {
    final HttpHost target = new HttpHost("localhost", 80);
    final HttpRoute route = new HttpRoute(target);

    Mockito.when(connFactory.create(
            Mockito.eq(route), Mockito.<ConnectionConfig>any())).thenReturn(conn);

    final ConnectionRequest connRequest1 = mgr.requestConnection(route, null);
    final HttpClientConnection conn1 = connRequest1.get(0, TimeUnit.MILLISECONDS);
    Assert.assertNotNull(conn1);
    Assert.assertFalse(conn1.isOpen());

    mgr.releaseConnection(conn1, null, 100, TimeUnit.MILLISECONDS);

    Assert.assertNull(mgr.getRoute());
    Assert.assertNull(mgr.getState());

    final ConnectionRequest connRequest2 = mgr.requestConnection(route, null);
    final HttpClientConnection conn2 = connRequest2.get(0, TimeUnit.MILLISECONDS);
    Assert.assertNotNull(conn2);
    Assert.assertFalse(conn2.isOpen());

    Mockito.verify(connFactory, Mockito.times(2)).create(
            Mockito.eq(route), Mockito.<ConnectionConfig>any());
}
项目:yarpc-java    文件:HttpConnectionReuseTest.java   
private void makeRequest(HttpClientConnection conn, String body, Map<String, String> headers)
    throws IOException, HttpException {
  HttpEntityEnclosingRequest req = new HttpPost("/");
  req.setHeaders(
      new Header[] {
        new BasicHeader(HeaderMapper.SERVICE, SERVICE),
        new BasicHeader(HeaderMapper.PROCEDURE, ECHO_PROCEDURE),
        new BasicHeader(HeaderMapper.CALLER, CLIENT),
        new BasicHeader(HeaderMapper.ENCODING, RawEncoding.ENCODING),
        new BasicHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(body.length()))
      });
  headers.forEach(req::setHeader);
  req.setEntity(new ByteArrayEntity(body.getBytes(Charsets.UTF_8)));
  conn.sendRequestHeader(req);
  conn.sendRequestEntity(req);
  conn.flush();

  HttpResponse res = conn.receiveResponseHeader();
  assertEquals(HttpStatus.SC_OK, res.getStatusLine().getStatusCode());

  conn.receiveResponseEntity(res);
  String echo = EntityUtils.toString(res.getEntity(), Charsets.UTF_8);
  assertEquals(body, echo);
}
项目:purecloud-iot    文件:TestPoolingHttpClientConnectionManager.java   
@Test
public void testReleaseReusable() throws Exception {
    final HttpHost target = new HttpHost("localhost", 80);
    final HttpRoute route = new HttpRoute(target);

    final CPoolEntry entry = Mockito.spy(new CPoolEntry(LogFactory.getLog(getClass()), "id", route, conn,
            -1, TimeUnit.MILLISECONDS));
    entry.markRouteComplete();

    Mockito.when(future.isCancelled()).thenReturn(Boolean.FALSE);
    Mockito.when(future.get(1, TimeUnit.SECONDS)).thenReturn(entry);
    Mockito.when(pool.lease(route, null, null)).thenReturn(future);
    Mockito.when(conn.isOpen()).thenReturn(Boolean.TRUE);

    final ConnectionRequest connRequest1 = mgr.requestConnection(route, null);
    final HttpClientConnection conn1 = connRequest1.get(1, TimeUnit.SECONDS);
    Assert.assertNotNull(conn1);
    Assert.assertTrue(conn1.isOpen());

    mgr.releaseConnection(conn1, "some state", 0, TimeUnit.MILLISECONDS);

    Mockito.verify(pool).release(entry, true);
    Mockito.verify(entry).setState("some state");
    Mockito.verify(entry).updateExpiry(Mockito.anyLong(), Mockito.eq(TimeUnit.MILLISECONDS));
}
项目:purecloud-iot    文件:BasicHttpClientConnectionManager.java   
@Override
public final ConnectionRequest requestConnection(
        final HttpRoute route,
        final Object state) {
    Args.notNull(route, "Route");
    return new ConnectionRequest() {

        @Override
        public boolean cancel() {
            // Nothing to abort, since requests are immediate.
            return false;
        }

        @Override
        public HttpClientConnection get(final long timeout, final TimeUnit tunit) {
            return BasicHttpClientConnectionManager.this.getConnection(
                    route, state);
        }

    };
}
项目:purecloud-iot    文件:BasicHttpClientConnectionManager.java   
synchronized HttpClientConnection getConnection(final HttpRoute route, final Object state) {
    Asserts.check(!this.isShutdown.get(), "Connection manager has been shut down");
    if (this.log.isDebugEnabled()) {
        this.log.debug("Get connection for route " + route);
    }
    Asserts.check(!this.leased, "Connection is still allocated");
    if (!LangUtils.equals(this.route, route) || !LangUtils.equals(this.state, state)) {
        closeConnection();
    }
    this.route = route;
    this.state = state;
    checkExpiry();
    if (this.conn == null) {
        this.conn = this.connFactory.create(route, this.connConfig);
    }
    this.leased = true;
    return this.conn;
}
项目:purecloud-iot    文件:PoolingHttpClientConnectionManager.java   
@Override
public ConnectionRequest requestConnection(
        final HttpRoute route,
        final Object state) {
    Args.notNull(route, "HTTP route");
    if (this.log.isDebugEnabled()) {
        this.log.debug("Connection request: " + format(route, state) + formatStats(route));
    }
    final Future<CPoolEntry> future = this.pool.lease(route, state, null);
    return new ConnectionRequest() {

        @Override
        public boolean cancel() {
            return future.cancel(true);
        }

        @Override
        public HttpClientConnection get(
                final long timeout,
                final TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException {
            return leaseConnection(future, timeout, tunit);
        }

    };

}
项目:purecloud-iot    文件:TestMainClientExec.java   
@Test
public void testSocketTimeoutExistingConnection() throws Exception {
    final HttpRoute route = new HttpRoute(target);
    final HttpClientContext context = new HttpClientContext();
    final RequestConfig config = RequestConfig.custom().setSocketTimeout(3000).build();
    final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));
    context.setRequestConfig(config);
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
    Mockito.when(managedConn.isOpen()).thenReturn(true);
    Mockito.when(requestExecutor.execute(
            Mockito.same(request),
            Mockito.<HttpClientConnection>any(),
            Mockito.<HttpClientContext>any())).thenReturn(response);

    mainClientExec.execute(route, request, context, execAware);
    Mockito.verify(managedConn).setSocketTimeout(3000);
}
项目:purecloud-iot    文件:TestMainClientExec.java   
@Test(expected=RequestAbortedException.class)
public void testExecAbortedPriorToRequestExecution() throws Exception {
    final HttpRoute route = new HttpRoute(target);
    final HttpClientContext context = new HttpClientContext();
    final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));

    Mockito.when(managedConn.isOpen()).thenReturn(Boolean.FALSE);
    Mockito.when(execAware.isAborted()).thenReturn(Boolean.FALSE, Boolean.FALSE, Boolean.TRUE);
    try {
        mainClientExec.execute(route, request, context, execAware);
    } catch (final IOException ex) {
        Mockito.verify(connRequest, Mockito.times(1)).get(0, TimeUnit.MILLISECONDS);
        Mockito.verify(connManager, Mockito.times(1)).connect(managedConn, route, 0, context);
        Mockito.verify(requestExecutor, Mockito.never()).execute(
                Mockito.same(request),
                Mockito.<HttpClientConnection>any(),
                Mockito.<HttpClientContext>any());
        throw ex;
    }
}
项目:purecloud-iot    文件:TestMainClientExec.java   
@Test(expected=RuntimeException.class)
public void testExecRuntimeException() throws Exception {
    final HttpRoute route = new HttpRoute(target);
    final HttpClientContext context = new HttpClientContext();
    final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));

    Mockito.when(requestExecutor.execute(
            Mockito.<HttpRequest>any(),
            Mockito.<HttpClientConnection>any(),
            Mockito.<HttpClientContext>any())).thenThrow(new RuntimeException("Ka-boom"));

    try {
        mainClientExec.execute(route, request, context, execAware);
    } catch (final Exception ex) {
        Mockito.verify(connManager).releaseConnection(managedConn, null, 0, TimeUnit.MILLISECONDS);

        throw ex;
    }
}
项目:purecloud-iot    文件:TestMainClientExec.java   
@Test(expected=IOException.class)
public void testExecIOException() throws Exception {
    final HttpRoute route = new HttpRoute(target);
    final HttpClientContext context = new HttpClientContext();
    final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));

    Mockito.when(requestExecutor.execute(
            Mockito.<HttpRequest>any(),
            Mockito.<HttpClientConnection>any(),
            Mockito.<HttpClientContext>any())).thenThrow(new IOException("Ka-boom"));

    try {
        mainClientExec.execute(route, request, context, execAware);
    } catch (final Exception ex) {
        Mockito.verify(connManager).releaseConnection(managedConn, null, 0, TimeUnit.MILLISECONDS);

        throw ex;
    }
}
项目:purecloud-iot    文件:TestPoolingHttpClientConnectionManager.java   
@Test
public void testReleaseNonReusable() throws Exception {
    final HttpHost target = new HttpHost("localhost", 80);
    final HttpRoute route = new HttpRoute(target);

    final CPoolEntry entry = Mockito.spy(new CPoolEntry(LogFactory.getLog(getClass()), "id", route, conn,
            -1, TimeUnit.MILLISECONDS));
    entry.markRouteComplete();

    Mockito.when(future.isCancelled()).thenReturn(Boolean.FALSE);
    Mockito.when(future.get(1, TimeUnit.SECONDS)).thenReturn(entry);
    Mockito.when(pool.lease(route, null, null)).thenReturn(future);
    Mockito.when(conn.isOpen()).thenReturn(Boolean.FALSE);

    final ConnectionRequest connRequest1 = mgr.requestConnection(route, null);
    final HttpClientConnection conn1 = connRequest1.get(1, TimeUnit.SECONDS);
    Assert.assertNotNull(conn1);
    Assert.assertFalse(conn1.isOpen());

    mgr.releaseConnection(conn1, "some state", 0, TimeUnit.MILLISECONDS);

    Mockito.verify(pool).release(entry, false);
    Mockito.verify(entry, Mockito.never()).setState(Mockito.anyObject());
    Mockito.verify(entry, Mockito.never()).updateExpiry(Mockito.anyLong(), Mockito.eq(TimeUnit.MILLISECONDS));
}
项目:purecloud-iot    文件:TestConnectionHolder.java   
@Test
public void testReleaseConnectionReusable() throws Exception {
    connHolder.setState("some state");
    connHolder.setValidFor(100, TimeUnit.SECONDS);
    connHolder.markReusable();

    connHolder.releaseConnection();

    Assert.assertTrue(connHolder.isReleased());

    Mockito.verify(conn, Mockito.never()).close();
    Mockito.verify(mgr).releaseConnection(conn, "some state", 100, TimeUnit.SECONDS);

    connHolder.releaseConnection();

    Mockito.verify(mgr, Mockito.times(1)).releaseConnection(
            Mockito.<HttpClientConnection>any(),
            Mockito.anyObject(),
            Mockito.anyLong(),
            Mockito.<TimeUnit>any());
}
项目:purecloud-iot    文件:TestConnectionHolder.java   
@Test
public void testReleaseConnectionNonReusable() throws Exception {
    connHolder.setState("some state");
    connHolder.setValidFor(100, TimeUnit.SECONDS);
    connHolder.markNonReusable();

    connHolder.releaseConnection();

    Assert.assertTrue(connHolder.isReleased());

    Mockito.verify(conn, Mockito.times(1)).close();
    Mockito.verify(mgr).releaseConnection(conn, null, 0, TimeUnit.MILLISECONDS);

    connHolder.releaseConnection();

    Mockito.verify(mgr, Mockito.times(1)).releaseConnection(
            Mockito.<HttpClientConnection>any(),
            Mockito.anyObject(),
            Mockito.anyLong(),
            Mockito.<TimeUnit>any());
}
项目:purecloud-iot    文件:TestMinimalClientExec.java   
@Test
public void testSocketTimeoutExistingConnection() throws Exception {
    final HttpRoute route = new HttpRoute(target);
    final HttpClientContext context = new HttpClientContext();
    final RequestConfig config = RequestConfig.custom().setSocketTimeout(3000).build();
    final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));
    context.setRequestConfig(config);
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
    Mockito.when(managedConn.isOpen()).thenReturn(true);
    Mockito.when(requestExecutor.execute(
            Mockito.same(request),
            Mockito.<HttpClientConnection>any(),
            Mockito.<HttpClientContext>any())).thenReturn(response);

    minimalClientExec.execute(route, request, context, execAware);
    Mockito.verify(managedConn).setSocketTimeout(3000);
}
项目:purecloud-iot    文件:TestMinimalClientExec.java   
@Test(expected=RuntimeException.class)
public void testExecRuntimeException() throws Exception {
    final HttpRoute route = new HttpRoute(target);
    final HttpClientContext context = new HttpClientContext();
    final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));

    Mockito.when(requestExecutor.execute(
            Mockito.<HttpRequest>any(),
            Mockito.<HttpClientConnection>any(),
            Mockito.<HttpClientContext>any())).thenThrow(new RuntimeException("Ka-boom"));

    try {
        minimalClientExec.execute(route, request, context, execAware);
    } catch (final Exception ex) {
        Mockito.verify(connManager).releaseConnection(managedConn, null, 0, TimeUnit.MILLISECONDS);

        throw ex;
    }
}
项目:purecloud-iot    文件:TestMinimalClientExec.java   
@Test(expected=HttpException.class)
public void testExecHttpException() throws Exception {
    final HttpRoute route = new HttpRoute(target);
    final HttpClientContext context = new HttpClientContext();
    final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));

    Mockito.when(requestExecutor.execute(
            Mockito.<HttpRequest>any(),
            Mockito.<HttpClientConnection>any(),
            Mockito.<HttpClientContext>any())).thenThrow(new HttpException("Ka-boom"));

    try {
        minimalClientExec.execute(route, request, context, execAware);
    } catch (final Exception ex) {
        Mockito.verify(connManager).releaseConnection(managedConn, null, 0, TimeUnit.MILLISECONDS);

        throw ex;
    }
}
项目:purecloud-iot    文件:TestMinimalClientExec.java   
@Test(expected=IOException.class)
public void testExecIOException() throws Exception {
    final HttpRoute route = new HttpRoute(target);
    final HttpClientContext context = new HttpClientContext();
    final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));

    Mockito.when(requestExecutor.execute(
            Mockito.<HttpRequest>any(),
            Mockito.<HttpClientConnection>any(),
            Mockito.<HttpClientContext>any())).thenThrow(new IOException("Ka-boom"));

    try {
        minimalClientExec.execute(route, request, context, execAware);
    } catch (final Exception ex) {
        Mockito.verify(connManager).releaseConnection(managedConn, null, 0, TimeUnit.MILLISECONDS);

        throw ex;
    }
}
项目:purecloud-iot    文件:TestMinimalClientExec.java   
@Test
public void absoluteUriIsRewrittenToRelativeBeforeBeingPassedInRequestLine() throws Exception {
    final HttpRoute route = new HttpRoute(target);
    final HttpClientContext context = new HttpClientContext();
    final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));

    final HttpResponse response = Mockito.mock(HttpResponse.class);
    Mockito.when(requestExecutor.execute(
            Mockito.<HttpRequest>any(),
            Mockito.<HttpClientConnection>any(),
            Mockito.<HttpClientContext>any())).thenReturn(response);

    minimalClientExec.execute(route, request, context, execAware);

    final ArgumentCaptor<HttpRequest> reqCaptor = ArgumentCaptor.forClass(HttpRequest.class);
    Mockito.verify(requestExecutor).execute(reqCaptor.capture(), Mockito.<HttpClientConnection>any(), Mockito.<HttpClientContext>any());

    Assert.assertEquals("/test", reqCaptor.getValue().getRequestLine().getUri());
}
项目:lams    文件:HttpRequestExecutor.java   
/**
 * Waits for and receives a response.
 * This method will automatically ignore intermediate responses
 * with status code 1xx.
 *
 * @param request   the request for which to obtain the response
 * @param conn      the connection over which the request was sent
 * @param context   the context for receiving the response
 *
 * @return  the terminal response, not yet post-processed
 *
 * @throws IOException in case of an I/O error.
 * @throws HttpException in case of HTTP protocol violation or a processing
 *   problem.
 */
protected HttpResponse doReceiveResponse(
        final HttpRequest          request,
        final HttpClientConnection conn,
        final HttpContext          context)
            throws HttpException, IOException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }
    if (conn == null) {
        throw new IllegalArgumentException("HTTP connection may not be null");
    }
    if (context == null) {
        throw new IllegalArgumentException("HTTP context may not be null");
    }

    HttpResponse response = null;
    int statuscode = 0;

    while (response == null || statuscode < HttpStatus.SC_OK) {

        response = conn.receiveResponseHeader();
        if (canResponseHaveBody(request, response)) {
            conn.receiveResponseEntity(response);
        }
        statuscode = response.getStatusLine().getStatusCode();

    } // while intermediate response

    return response;

}
项目:cyberduck    文件:UDTProxyConfigurator.java   
@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);
}
项目:cyberduck    文件:LoggingHttpRequestExecutor.java   
@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);
}
项目:cyberduck    文件:LoggingHttpRequestExecutor.java   
@Override
protected HttpResponse doReceiveResponse(final HttpRequest request, final HttpClientConnection conn, final HttpContext context) throws HttpException, IOException {
    final HttpResponse response = super.doReceiveResponse(request, conn, context);
    synchronized(listener) {
        listener.log(TranscriptListener.Type.response, response.getStatusLine().toString());
        for(Header header : response.getAllHeaders()) {
            listener.log(TranscriptListener.Type.response, header.toString());
        }
    }
    return response;
}
项目:ibm-cos-sdk-java    文件:SdkHttpRequestExecutor.java   
@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);
    }
}
项目:outcomes    文件:TestHttpCore.java   
@Test
public void test() throws ExecutionException, InterruptedException {


    HttpHost target = new HttpHost("localhost");
    BasicConnPool connpool = new BasicConnPool();
    connpool.setMaxTotal(200);
    connpool.setDefaultMaxPerRoute(10);
    connpool.setMaxPerRoute(target, 20);
    Future<BasicPoolEntry> future = connpool.lease(target, null);
    BasicPoolEntry poolEntry = future.get();
    HttpClientConnection conn = poolEntry.getConnection();

    HttpProcessor httpproc = HttpProcessorBuilder.create()
            .add(new ResponseDate())
            .add(new ResponseServer("MyServer-HTTP/1.1"))
            .add(new ResponseContent())
            .add(new ResponseConnControl())
            .build();

    HttpRequestHandler myRequestHandler = new HttpRequestHandler() {

        public void handle(
                HttpRequest request,
                HttpResponse response,
                HttpContext context) throws HttpException, IOException {
            response.setStatusCode(HttpStatus.SC_OK);
            response.setEntity(
                    new StringEntity("some important message",
                            ContentType.TEXT_PLAIN));
        }

    };

    UriHttpRequestHandlerMapper handlerMapper = new UriHttpRequestHandlerMapper();
    handlerMapper.register("/service/*", myRequestHandler);
    HttpService httpService = new HttpService(httpproc, handlerMapper);
}
项目:PhET    文件:ElementalReverseProxy.java   
public ProxyThread(
        final HttpService httpservice, 
        final HttpServerConnection inconn,
        final HttpClientConnection outconn) {
    super();
    this.httpservice = httpservice;
    this.inconn = inconn;
    this.outconn = outconn;
}
项目:remote-files-sync    文件:BasicConnFactory.java   
/**
 * @deprecated (4.3) no longer used.
 */
@Deprecated
protected HttpClientConnection create(final Socket socket, final HttpParams params) throws IOException {
    final int bufsize = params.getIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024);
    final DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(bufsize);
    conn.bind(socket);
    return conn;
}
项目:purecloud-iot    文件:TestClientRequestExecution.java   
@Override
public HttpResponse execute(
        final HttpRequest request,
        final HttpClientConnection conn,
        final HttpContext context) throws IOException, HttpException {

    final HttpResponse response = super.execute(request, conn, context);
    final Object marker = context.getAttribute(MARKER);
    if (marker == null) {
        context.setAttribute(MARKER, Boolean.TRUE);
        throw new IOException(failureMsg);
    }
    return response;
}
项目:purecloud-iot    文件:TestStatefulConnManagement.java   
@Override
public void run() {
    try {
        this.context.setAttribute("user", this.uid);
        for (int r = 0; r < this.requestCount; r++) {
            final HttpGet httpget = new HttpGet("/");
            final HttpResponse response = this.httpclient.execute(
                    this.target,
                    httpget,
                    this.context);
            this.count++;

            final HttpClientConnection conn = this.context.getConnection(HttpClientConnection.class);
            final HttpContext connContext = (HttpContext) conn;
            String connuid = (String) connContext.getAttribute("user");
            if (connuid == null) {
                connContext.setAttribute("user", this.uid);
                connuid = this.uid;
            }
            this.context.setAttribute("r" + r, connuid);
            EntityUtils.consume(response.getEntity());
        }

    } catch (final Exception ex) {
        this.exception = ex;
    }
}
项目:purecloud-iot    文件:TestAbortHandling.java   
@Override
public ConnectionRequest requestConnection(
        final HttpRoute route,
        final Object state) {

    final Thread currentThread = Thread.currentThread();

    return new ConnectionRequest() {

        @Override
        public boolean cancel() {
            currentThread.interrupt();
            return true;
        }

        @Override
        public HttpClientConnection get(
                final long timeout,
                final TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException {
            connLatch.countDown(); // notify waiter that we're getting a connection

            // zero usually means sleep forever, but CountDownLatch doesn't interpret it that way.
            if(!awaitLatch.await(timeout > 0 ? timeout : Integer.MAX_VALUE, tunit)) {
                throw new ConnectionPoolTimeoutException();
            }

            return Mockito.mock(HttpClientConnection.class);
        }

    };
}
项目:remote-files-sync    文件:BasicHttpClientConnectionManager.java   
public void upgrade(
        final HttpClientConnection conn,
        final HttpRoute route,
        final HttpContext context) throws IOException {
    Args.notNull(conn, "Connection");
    Args.notNull(route, "HTTP route");
    Asserts.check(conn == this.conn, "Connection not obtained from this manager");
    this.connectionOperator.upgrade(this.conn, route.getTargetHost(), context);
}
项目:remote-files-sync    文件:PoolingHttpClientConnectionManager.java   
public void connect(
        final HttpClientConnection managedConn,
        final HttpRoute route,
        final int connectTimeout,
        final HttpContext context) throws IOException {
    Args.notNull(managedConn, "Managed Connection");
    Args.notNull(route, "HTTP route");
    final ManagedHttpClientConnection conn;
    synchronized (managedConn) {
        final CPoolEntry entry = CPoolProxy.getPoolEntry(managedConn);
        conn = entry.getConnection();
    }
    final HttpHost host;
    if (route.getProxyHost() != null) {
        host = route.getProxyHost();
    } else {
        host = route.getTargetHost();
    }
    final InetSocketAddress localAddress = route.getLocalAddress() != null ? new InetSocketAddress(route.getLocalAddress(), 0) : null;;
    SocketConfig socketConfig = this.configData.getSocketConfig(host);
    if (socketConfig == null) {
        socketConfig = this.configData.getDefaultSocketConfig();
    }
    if (socketConfig == null) {
        socketConfig = SocketConfig.DEFAULT;
    }
    this.connectionOperator.connect(
            conn, host, localAddress, connectTimeout, socketConfig, context);
}
项目:remote-files-sync    文件:PoolingHttpClientConnectionManager.java   
public void upgrade(
        final HttpClientConnection managedConn,
        final HttpRoute route,
        final HttpContext context) throws IOException {
    Args.notNull(managedConn, "Managed Connection");
    Args.notNull(route, "HTTP route");
    final ManagedHttpClientConnection conn;
    synchronized (managedConn) {
        final CPoolEntry entry = CPoolProxy.getPoolEntry(managedConn);
        conn = entry.getConnection();
    }
    this.connectionOperator.upgrade(conn, route.getTargetHost(), context);
}