Example usage for org.apache.http.impl.conn BasicClientConnectionManager BasicClientConnectionManager

List of usage examples for org.apache.http.impl.conn BasicClientConnectionManager BasicClientConnectionManager

Introduction

In this page you can find the example usage for org.apache.http.impl.conn BasicClientConnectionManager BasicClientConnectionManager.

Prototype

public BasicClientConnectionManager() 

Source Link

Usage

From source file:piecework.client.LoadTester.java

public LoadTester(KeyStore keystore, SecuritySettings securitySettings) {
    ClientConnectionManager cm;/*w  w  w  . ja  v  a2s  .c o  m*/
    try {
        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(keystore,
                new String(securitySettings.getKeystorePassword()));
        X509HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
        sslSocketFactory.setHostnameVerifier(hostnameVerifier);

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("https", 8443, sslSocketFactory));

        cm = new PoolingClientConnectionManager(schemeRegistry);
    } catch (Exception e) {
        cm = new BasicClientConnectionManager();
    }
    this.client = new DefaultHttpClient(cm);
}

From source file:com.klarna.checkout.BasicConnector.java

/**
 * Constructor.//w w w .ja  v  a 2 s.c o m
 *
 * @param dig Digest instance
 */
public BasicConnector(final Digest dig) {
    this(dig, new BasicClientConnectionManager());
}

From source file:com.mycompany.kerberosbyip.NewMain.java

private void doSendRequest() throws Exception {

    InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("request");
    String requestBody = new Scanner(stream, "UTF-8").useDelimiter("\\A").next();

    final DefaultHttpClient client = new DefaultHttpClient(new BasicClientConnectionManager());

    try {//from www  . j  av  a 2 s .  c o  m
        configureHttpClient(client);
        final HttpEntity entity = createEntity(requestBody);

        final HttpPost post = new HttpPost("/wsman");
        post.setHeader("Content-Type", SOAPConstants.SOAP_1_2_CONTENT_TYPE + "; charset=utf-8");
        post.setHeader("Connection", "Keep-Alive");
        post.setHeader("SOAPAction", "http://schemas.xmlsoap.org/ws/2004/09/enumeration/Enumerate");
        post.setEntity(entity);

        final HttpResponse response = client.execute(new HttpHost(ipAddress, port, "http"), post);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new Exception(String.format("Unexpected HTTP response on %s:  %s (%s)", ipAddress,
                    response.getStatusLine().getReasonPhrase(), response.getStatusLine().getStatusCode()));
        }

    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.adavr.http.Client.java

public Client() {
    httpClient = new DefaultHttpClient(new BasicClientConnectionManager());
    localContext = new BasicHttpContext();
    byteStream = new ByteArrayOutputStream();

    CookieStore cookieStore = new BasicCookieStore();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {

        @Override/*from  w  ww .  ja  va 2  s .c om*/
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {

        @Override
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            Header ceheader = entity.getContentEncoding();
            if (ceheader != null) {
                HeaderElement[] codecs = ceheader.getElements();
                for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }
    });

    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, DEFAULT_TIMEOUT);
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, DEFAULT_USER_AGENT);
    HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {

        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount >= DEFAULT_RETRY) {
                // Do not retry if over max retry count
                return false;
            }
            System.out.println(exception.getClass().getName());
            if (exception instanceof NoHttpResponseException) {
                // Retry if the server dropped connection on us
                return true;
            }
            if (exception instanceof SSLHandshakeException) {
                // Do not retry on SSL handshake exception
                return false;
            }
            HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
            boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
            if (idempotent) {
                // Retry if the request is considered idempotent
                return true;
            }
            return false;
        }
    };

    httpClient.setHttpRequestRetryHandler(myRetryHandler);
}

From source file:pl.psnc.synat.wrdz.zmkd.invocation.RestServiceCaller.java

/**
 * Gets client that can use HTTP or HTTPS protocol accepting all servers certificates.
 * //from  ww  w  .j  a v a  2  s .  c  o m
 * @return HTTP client
 */
private HttpClient getHttpClient() {
    Scheme httpScheme = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
    Scheme httpsScheme = null;
    try {
        httpsScheme = new Scheme("https", 443,
                new SSLSocketFactory(new TrustAllStrategy(), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER));
    } catch (KeyManagementException e) {
        throw new WrdzRuntimeException(e);
    } catch (UnrecoverableKeyException e) {
        throw new WrdzRuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new WrdzRuntimeException(e);
    } catch (KeyStoreException e) {
        throw new WrdzRuntimeException(e);
    }

    ClientConnectionManager connectionManager = new BasicClientConnectionManager();
    connectionManager.getSchemeRegistry().register(httpScheme);
    connectionManager.getSchemeRegistry().register(httpsScheme);

    return new DefaultHttpClient(connectionManager);
}

From source file:org.glassfish.jersey.apache.connector.HelloWorldTest.java

/**
 * JERSEY-2157 reproducer.//  w  w  w.  j  a va 2 s .c  om
 * <p>
 * The test ensures that entities of the error responses which cause
 * WebApplicationException being thrown by a JAX-RS client are buffered
 * and that the underlying input connections are automatically released
 * in such case.
 */
@Test
public void testConnectionClosingOnExceptionsForErrorResponses() {
    final BasicClientConnectionManager cm = new BasicClientConnectionManager();
    final AtomicInteger connectionCounter = new AtomicInteger(0);

    final ClientConfig config = new ClientConfig().property(ApacheClientProperties.CONNECTION_MANAGER,
            new ClientConnectionManager() {
                @Override
                public SchemeRegistry getSchemeRegistry() {
                    return cm.getSchemeRegistry();
                }

                @Override
                public ClientConnectionRequest requestConnection(final HttpRoute route, final Object state) {
                    connectionCounter.incrementAndGet();

                    final ClientConnectionRequest wrappedRequest = cm.requestConnection(route, state);

                    /**
                     * To explain the following long piece of code:
                     *
                     * All the code does is to just create a wrapper implementations
                     * for the AHC connection management interfaces.
                     *
                     * The only really important piece of code is the
                     * {@link org.apache.http.conn.ManagedClientConnection#releaseConnection()} implementation,
                     * where the connectionCounter is decremented when a managed connection instance
                     * is released by AHC runtime. In our test, this is expected to happen
                     * as soon as the exception is created for an error response
                     * (as the error response entity gets buffered in
                     * {@link org.glassfish.jersey.client.JerseyInvocation#convertToException(javax.ws.rs.core.Response)}).
                     */
                    return new ClientConnectionRequest() {
                        @Override
                        public ManagedClientConnection getConnection(long timeout, TimeUnit tunit)
                                throws InterruptedException, ConnectionPoolTimeoutException {

                            final ManagedClientConnection wrappedConnection = wrappedRequest
                                    .getConnection(timeout, tunit);

                            return new ManagedClientConnection() {
                                @Override
                                public boolean isSecure() {
                                    return wrappedConnection.isSecure();
                                }

                                @Override
                                public HttpRoute getRoute() {
                                    return wrappedConnection.getRoute();
                                }

                                @Override
                                public SSLSession getSSLSession() {
                                    return wrappedConnection.getSSLSession();
                                }

                                @Override
                                public void open(HttpRoute route, HttpContext context, HttpParams params)
                                        throws IOException {
                                    wrappedConnection.open(route, context, params);
                                }

                                @Override
                                public void tunnelTarget(boolean secure, HttpParams params) throws IOException {
                                    wrappedConnection.tunnelTarget(secure, params);
                                }

                                @Override
                                public void tunnelProxy(HttpHost next, boolean secure, HttpParams params)
                                        throws IOException {
                                    wrappedConnection.tunnelProxy(next, secure, params);
                                }

                                @Override
                                public void layerProtocol(HttpContext context, HttpParams params)
                                        throws IOException {
                                    wrappedConnection.layerProtocol(context, params);
                                }

                                @Override
                                public void markReusable() {
                                    wrappedConnection.markReusable();
                                }

                                @Override
                                public void unmarkReusable() {
                                    wrappedConnection.unmarkReusable();
                                }

                                @Override
                                public boolean isMarkedReusable() {
                                    return wrappedConnection.isMarkedReusable();
                                }

                                @Override
                                public void setState(Object state) {
                                    wrappedConnection.setState(state);
                                }

                                @Override
                                public Object getState() {
                                    return wrappedConnection.getState();
                                }

                                @Override
                                public void setIdleDuration(long duration, TimeUnit unit) {
                                    wrappedConnection.setIdleDuration(duration, unit);
                                }

                                @Override
                                public boolean isResponseAvailable(int timeout) throws IOException {
                                    return wrappedConnection.isResponseAvailable(timeout);
                                }

                                @Override
                                public void sendRequestHeader(HttpRequest request)
                                        throws HttpException, IOException {
                                    wrappedConnection.sendRequestHeader(request);
                                }

                                @Override
                                public void sendRequestEntity(HttpEntityEnclosingRequest request)
                                        throws HttpException, IOException {
                                    wrappedConnection.sendRequestEntity(request);
                                }

                                @Override
                                public HttpResponse receiveResponseHeader() throws HttpException, IOException {
                                    return wrappedConnection.receiveResponseHeader();
                                }

                                @Override
                                public void receiveResponseEntity(HttpResponse response)
                                        throws HttpException, IOException {
                                    wrappedConnection.receiveResponseEntity(response);
                                }

                                @Override
                                public void flush() throws IOException {
                                    wrappedConnection.flush();
                                }

                                @Override
                                public void close() throws IOException {
                                    wrappedConnection.close();
                                }

                                @Override
                                public boolean isOpen() {
                                    return wrappedConnection.isOpen();
                                }

                                @Override
                                public boolean isStale() {
                                    return wrappedConnection.isStale();
                                }

                                @Override
                                public void setSocketTimeout(int timeout) {
                                    wrappedConnection.setSocketTimeout(timeout);
                                }

                                @Override
                                public int getSocketTimeout() {
                                    return wrappedConnection.getSocketTimeout();
                                }

                                @Override
                                public void shutdown() throws IOException {
                                    wrappedConnection.shutdown();
                                }

                                @Override
                                public HttpConnectionMetrics getMetrics() {
                                    return wrappedConnection.getMetrics();
                                }

                                @Override
                                public InetAddress getLocalAddress() {
                                    return wrappedConnection.getLocalAddress();
                                }

                                @Override
                                public int getLocalPort() {
                                    return wrappedConnection.getLocalPort();
                                }

                                @Override
                                public InetAddress getRemoteAddress() {
                                    return wrappedConnection.getRemoteAddress();
                                }

                                @Override
                                public int getRemotePort() {
                                    return wrappedConnection.getRemotePort();
                                }

                                @Override
                                public void releaseConnection() throws IOException {
                                    connectionCounter.decrementAndGet();
                                    wrappedConnection.releaseConnection();
                                }

                                @Override
                                public void abortConnection() throws IOException {
                                    wrappedConnection.abortConnection();
                                }

                                @Override
                                public String getId() {
                                    return wrappedConnection.getId();
                                }

                                @Override
                                public void bind(Socket socket) throws IOException {
                                    wrappedConnection.bind(socket);
                                }

                                @Override
                                public Socket getSocket() {
                                    return wrappedConnection.getSocket();
                                }
                            };
                        }

                        @Override
                        public void abortRequest() {
                            wrappedRequest.abortRequest();
                        }
                    };
                }

                @Override
                public void releaseConnection(ManagedClientConnection conn, long keepalive, TimeUnit tunit) {
                    cm.releaseConnection(conn, keepalive, tunit);
                }

                @Override
                public void closeExpiredConnections() {
                    cm.closeExpiredConnections();
                }

                @Override
                public void closeIdleConnections(long idletime, TimeUnit tunit) {
                    cm.closeIdleConnections(idletime, tunit);
                }

                @Override
                public void shutdown() {
                    cm.shutdown();
                }
            });
    config.connectorProvider(new ApacheConnectorProvider());

    final Client client = ClientBuilder.newClient(config);
    final WebTarget rootTarget = client.target(getBaseUri()).path(ROOT_PATH);

    // Test that connection is getting closed properly for error responses.
    try {
        final String response = rootTarget.path("error").request().get(String.class);
        fail("Exception expected. Received: " + response);
    } catch (InternalServerErrorException isee) {
        // do nothing - connection should be closed properly by now
    }

    // Fail if the previous connection has not been closed automatically.
    assertEquals(0, connectionCounter.get());

    try {
        final String response = rootTarget.path("error2").request().get(String.class);
        fail("Exception expected. Received: " + response);
    } catch (InternalServerErrorException isee) {
        assertEquals("Received unexpected data.", "Error2.", isee.getResponse().readEntity(String.class));
        // Test buffering:
        // second read would fail if entity was not buffered
        assertEquals("Unexpected data in the entity buffer.", "Error2.",
                isee.getResponse().readEntity(String.class));
    }

    assertEquals(0, connectionCounter.get());
}

From source file:org.bigmouth.nvwa.network.http.HttpClientHelper.java

public static HttpClient https(int port) {
    try {//from  w  w  w .  j  a  v  a 2s  .c  o  m
        SSLContext ctx = getInstance();
        ClientConnectionManager ccm = new BasicClientConnectionManager();
        return getHttpClient(ctx, ccm, port, DEFAULT_TIME_OUT);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.bigmouth.nvwa.network.http.HttpClientHelper.java

public static HttpClient https(File keystore, char[] pwd, int port) {
    try {/* w  w w. j  a  v  a 2 s .  co m*/
        ClientConnectionManager ccm = new BasicClientConnectionManager();
        return getHttpClient(keystore, pwd, ccm, port, DEFAULT_TIME_OUT);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.rhq.maven.plugins.UploadMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (skipUpload) {
        getLog().info("Skipped execution");
        return;/*  w  w  w .j ava 2s.  co m*/
    }
    File agentPluginArchive = getAgentPluginArchiveFile(buildDirectory, finalName);
    if (!agentPluginArchive.exists() && agentPluginArchive.isFile()) {
        throw new MojoExecutionException("Agent plugin archive does not exist: " + agentPluginArchive);
    }

    // Prepare HttpClient
    ClientConnectionManager httpConnectionManager = new BasicClientConnectionManager();
    DefaultHttpClient httpClient = new DefaultHttpClient(httpConnectionManager);
    HttpParams httpParams = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, socketConnectionTimeout);
    HttpConnectionParams.setSoTimeout(httpParams, socketReadTimeout);
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, port),
            new UsernamePasswordCredentials(username, password));

    HttpPost uploadContentRequest = null;
    HttpPut moveContentToPluginsDirRequest = null;
    HttpPost pluginScanRequest = null;
    HttpPost pluginDeployRequest = null;
    HttpGet pluginDeployCheckCompleteRequest = null;
    try {

        // Upload plugin content
        URI uploadContentUri = buildUploadContentUri();
        uploadContentRequest = new HttpPost(uploadContentUri);
        uploadContentRequest.setEntity(new FileEntity(agentPluginArchive, APPLICATION_OCTET_STREAM));
        uploadContentRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
        HttpResponse uploadContentResponse = httpClient.execute(uploadContentRequest);

        if (uploadContentResponse.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
            handleProblem(uploadContentResponse.getStatusLine().toString());
            return;
        }

        getLog().info("Uploaded " + agentPluginArchive);
        // Read the content handle value in JSON response
        JSONObject uploadContentResponseJsonObject = new JSONObject(
                EntityUtils.toString(uploadContentResponse.getEntity()));
        String contentHandle = (String) uploadContentResponseJsonObject.get("value");
        uploadContentRequest.abort();

        if (!startScan && !updatePluginsOnAllAgents) {

            // Request uploaded content to be moved to the plugins directory but do not trigger a plugin scan
            URI moveContentToPluginsDirUri = buildMoveContentToPluginsDirUri(contentHandle);
            moveContentToPluginsDirRequest = new HttpPut(moveContentToPluginsDirUri);
            moveContentToPluginsDirRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
            HttpResponse moveContentToPluginsDirResponse = httpClient.execute(moveContentToPluginsDirRequest);

            if (moveContentToPluginsDirResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                handleProblem(moveContentToPluginsDirResponse.getStatusLine().toString());
                return;
            }

            moveContentToPluginsDirRequest.abort();
            getLog().info("Moved uploaded content to plugins directory");
            return;
        }

        // Request uploaded content to be moved to the plugins directory and trigger a plugin scan
        URI pluginScanUri = buildPluginScanUri(contentHandle);
        pluginScanRequest = new HttpPost(pluginScanUri);
        pluginScanRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
        getLog().info("Moving uploaded content to plugins directory and requesting a plugin scan");
        HttpResponse pluginScanResponse = httpClient.execute(pluginScanRequest);

        if (pluginScanResponse.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED //
                && pluginScanResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            handleProblem(pluginScanResponse.getStatusLine().toString());
            return;
        }

        pluginScanRequest.abort();
        getLog().info("Plugin scan complete");

        if (updatePluginsOnAllAgents) {

            URI pluginDeployUri = buildPluginDeployUri();
            pluginDeployRequest = new HttpPost(pluginDeployUri);
            pluginDeployRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
            getLog().info("Requesting agents to update their plugins");
            HttpResponse pluginDeployResponse = httpClient.execute(pluginDeployRequest);

            if (pluginDeployResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                handleProblem(pluginDeployResponse.getStatusLine().toString());
                return;
            }

            getLog().info("Plugins update requests sent");
            // Read the agent plugins update handle value in JSON response
            JSONObject pluginDeployResponseJsonObject = new JSONObject(
                    EntityUtils.toString(pluginDeployResponse.getEntity()));
            String pluginsUpdateHandle = (String) pluginDeployResponseJsonObject.get("value");
            pluginDeployRequest.abort();

            if (waitForPluginsUpdateOnAllAgents) {

                getLog().info("Waiting for plugins update requests to complete");

                long start = System.currentTimeMillis();
                for (;;) {

                    URI pluginDeployCheckCompleteUri = buildPluginDeployCheckCompleteUri(pluginsUpdateHandle);
                    pluginDeployCheckCompleteRequest = new HttpGet(pluginDeployCheckCompleteUri);
                    pluginDeployCheckCompleteRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
                    HttpResponse pluginDeployCheckCompleteResponse = httpClient
                            .execute(pluginDeployCheckCompleteRequest);

                    if (pluginDeployCheckCompleteResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                        handleProblem(pluginDeployCheckCompleteResponse.getStatusLine().toString());
                        return;
                    }

                    // Read the agent plugins update handle value in JSON response
                    JSONObject pluginDeployCheckCompleteResponseJsonObject = new JSONObject(
                            EntityUtils.toString(pluginDeployCheckCompleteResponse.getEntity()));
                    Boolean pluginDeployCheckCompleteHandle = (Boolean) pluginDeployCheckCompleteResponseJsonObject
                            .get("value");
                    pluginDeployCheckCompleteRequest.abort();

                    if (pluginDeployCheckCompleteHandle == TRUE) {
                        getLog().info("All agents updated their plugins");
                        return;
                    }

                    if (SECONDS.toMillis(
                            maxWaitForPluginsUpdateOnAllAgents) < (System.currentTimeMillis() - start)) {
                        handleProblem("Not all agents updated their plugins but wait limit has been reached ("
                                + maxWaitForPluginsUpdateOnAllAgents + " ms)");
                        return;
                    }

                    Thread.sleep(SECONDS.toMillis(5));
                    getLog().info("Checking plugins update requests status again");
                }
            }
        }
    } catch (IOException e) {
        handleException(e);
    } catch (JSONException e) {
        handleException(e);
    } catch (URISyntaxException e) {
        handleException(e);
    } catch (InterruptedException e) {
        handleException(e);
    } finally {
        abortQuietly(uploadContentRequest);
        abortQuietly(moveContentToPluginsDirRequest);
        abortQuietly(pluginScanRequest);
        abortQuietly(pluginDeployRequest);
        abortQuietly(pluginDeployCheckCompleteRequest);
        httpConnectionManager.shutdown();
    }
}