Example usage for org.apache.http.impl.client DefaultHttpClient getConnectionManager

List of usage examples for org.apache.http.impl.client DefaultHttpClient getConnectionManager

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient getConnectionManager.

Prototype

public synchronized final ClientConnectionManager getConnectionManager() 

Source Link

Usage

From source file:com.cloudbees.eclipse.core.util.Utils.java

/**
 * @param url//from  ww w.java 2 s .  c  om
 *          url to connec. Required to determine proxy settings if available. If <code>null</code> then proxy is not
 *          configured for the client returned.
 * @return
 * @throws CloudBeesException
 */
public final static DefaultHttpClient getAPIClient(String url) throws CloudBeesException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        HttpClientParams.setCookiePolicy(httpclient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);

        String version = null;
        if (CloudBeesCorePlugin.getDefault() != null) {
            version = CloudBeesCorePlugin.getDefault().getBundle().getVersion().toString();
        } else {
            version = "n/a";
        }
        HttpProtocolParams.setUserAgent(httpclient.getParams(), "CBEclipseToolkit/" + version);

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

        CloudBeesCorePlugin plugin = CloudBeesCorePlugin.getDefault();

        URL truststore;

        if (plugin == null) {
            //Outside the OSGI environment, try to open the stream from the current dir.
            truststore = new File("truststore").toURI().toURL();
        } else {
            truststore = plugin.getBundle().getResource("truststore");
        }

        InputStream instream = truststore.openStream();

        try {
            trustStore.load(instream, "123456".toCharArray());
        } finally {
            instream.close();
        }

        TrustStrategy trustAllStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(final X509Certificate[] chain, final String authType)
                    throws CertificateException {
                return true;
            }
        };

        SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, null, null, trustStore,
                null, trustAllStrategy, SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        // Override https handling to use provided truststore
        @SuppressWarnings("deprecation")
        Scheme sch = new Scheme("https", socketFactory, 443);
        httpclient.getConnectionManager().getSchemeRegistry().register(sch);

        HttpParams params = httpclient.getParams();

        //TODO Make configurable from the UI?
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        if (CloudBeesCorePlugin.getDefault() != null) { // exclude proxy support when running outside eclipse
            IProxyService ps = CloudBeesCorePlugin.getDefault().getProxyService();
            if (ps.isProxiesEnabled()) {

                IProxyData[] pr = ps.select(new URI(url));

                //NOTE! For now we use just the first proxy settings with type HTTP or HTTPS to try out the connection. If configuration has more than 1 conf then for now this likely won't work!
                if (pr != null) {
                    for (int i = 0; i < pr.length; i++) {

                        IProxyData prd = pr[i];

                        if (IProxyData.HTTP_PROXY_TYPE.equals(prd.getType())
                                || IProxyData.HTTPS_PROXY_TYPE.equals(prd.getType())) {

                            String proxyHost = prd.getHost();
                            int proxyPort = prd.getPort();
                            String proxyUser = prd.getUserId();
                            String proxyPass = prd.getPassword();

                            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
                            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

                            if (prd.isRequiresAuthentication()) {
                                List authpref = new ArrayList();
                                authpref.add(AuthPolicy.BASIC);
                                AuthScope authScope = new AuthScope(proxyHost, proxyPort);
                                httpclient.getCredentialsProvider().setCredentials(authScope,
                                        new UsernamePasswordCredentials(proxyUser, proxyPass));
                            }

                            break;

                        }

                    }
                }
            }
        }

        /*      httpclient.getHostConfiguration().setProxy(proxyHost,proxyPort);      
              //if there are proxy credentials available, set those too
              Credentials proxyCredentials = null;
              String proxyUser = beesClientConfiguration.getProxyUser();
              String proxyPassword = beesClientConfiguration.getProxyPassword();
              if(proxyUser != null || proxyPassword != null)
        proxyCredentials = new UsernamePasswordCredentials(proxyUser, proxyPassword);
              if(proxyCredentials != null)
        client.getState().setProxyCredentials(AuthScope.ANY, proxyCredentials);
                
        */

        return httpclient;

    } catch (Exception e) {
        throw new CloudBeesException("Error while initiating access to JSON APIs!", e);
    }
}

From source file:com.kku.apps.pricesearch.util.HttpConnection.java

public String doGet(String url) {

    HttpGet method = new HttpGet(url);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    method.setHeader("Connection", "Keep-Alive");
    try {// ww w .j  av  a2 s. c  o m
        String resultRes = httpClient.execute(method, new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                // Xe?[^XR?[h
                int status = response.getStatusLine().getStatusCode();
                // TODO v?C??@20120325
                // yahooAPINGXg400badequest}?u
                if (HttpStatus.SC_BAD_REQUEST == status) {
                    Log.d(TAG, "400 BAD REQUEST");
                } else if (HttpStatus.SC_OK != status) {
                    Log.d(TAG, "?MG?[??@status : " + status);

                    //throw new RuntimeException("?MG?[?");
                }
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        });
        return resultRes;
    } catch (ClientProtocolException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:org.jboss.as.test.clustering.cluster.web.ClusteredWebSimpleTestCase.java

@Test
@OperateOnDeployment(DEPLOYMENT_1)//from  w  ww.  ja  v a 2  s  .  c o  m
public void testSerialized(@ArquillianResource(SimpleServlet.class) URL baseURL) throws IOException {
    DefaultHttpClient client = HttpClientUtils.relaxedCookieHttpClient();

    // returns the URL of the deployment (http://127.0.0.1:8180/distributable)
    String url = baseURL.toString();
    log.info("URL = " + url);

    try {
        HttpResponse response = client.execute(new HttpGet(url + "simple"));
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(1, Integer.parseInt(response.getFirstHeader("value").getValue()));
        Assert.assertFalse(Boolean.valueOf(response.getFirstHeader("serialized").getValue()));
        response.getEntity().getContent().close();

        response = client.execute(new HttpGet(url + "simple"));
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(2, Integer.parseInt(response.getFirstHeader("value").getValue()));
        // This won't be true unless we have somewhere to which to replicate
        Assert.assertTrue(Boolean.valueOf(response.getFirstHeader("serialized").getValue()));
        response.getEntity().getContent().close();
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:org.gatein.sso.agent.opensso.OpenSSOAgentImpl.java

protected String getSubject(String token) throws Exception {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post;/*from  w  w  w  . j a  v a  2 s . c  o  m*/
    try {
        String uid = null;
        String url = this.serverUrl + "/identity/attributes";
        post = new HttpPost(url);

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("subjectid", token));
        nameValuePairs.add(new BasicNameValuePair("attributes_names", "uid"));
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse httpResponse = client.execute(post);
        int status = httpResponse.getStatusLine().getStatusCode();
        HttpEntity entity = httpResponse.getEntity();
        String response = entity == null ? null : EntityUtils.toString(entity);

        log.debug("Status of get subject: " + status);
        log.debug(response);

        if (response != null) {
            Properties properties = this.loadAttributes(response);
            uid = properties.getProperty("uid");
        }

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

From source file:gov.nih.nci.system.web.client.RESTfulCreateClient.java

public Response create(File fileLoc, String url) {
    try {/*from   ww  w .j av  a 2 s. com*/
        if (url == null) {
            ResponseBuilder builder = Response.status(Status.BAD_REQUEST);
            builder.type("application/xml");
            StringBuffer buffer = new StringBuffer();
            buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            buffer.append("<response>");
            buffer.append("<type>ERROR</type>");
            buffer.append("<code>INVALID_URL</code>");
            buffer.append("<message>Invalid URL: " + url + "</message>");
            buffer.append("</response>");
            builder.entity(buffer.toString());
            return builder.build();
        }

        if (fileLoc == null || !fileLoc.exists()) {
            ResponseBuilder builder = Response.status(Status.BAD_REQUEST);
            builder.type("application/xml");
            StringBuffer buffer = new StringBuffer();
            buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            buffer.append("<response>");
            buffer.append("<type>ERROR</type>");
            buffer.append("<code>INVALID_FILE</code>");
            buffer.append("<message>Invalid File given to read</message>");
            buffer.append("</response>");
            builder.entity(buffer.toString());
            return builder.build();
        }

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPut putRequest = new HttpPut(url);

        FileEntity input = new FileEntity(fileLoc);
        input.setContentType("application/xml");
        if (userName != null && password != null) {
            String base64encodedUsernameAndPassword = new String(
                    Base64.encodeBase64((userName + ":" + password).getBytes()));
            putRequest.addHeader("Authorization", "Basic " + base64encodedUsernameAndPassword);
        }

        putRequest.setEntity(input);
        HttpResponse response = httpClient.execute(putRequest);
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        StringBuffer buffer = new StringBuffer();
        buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        buffer.append("<response>");
        while ((output = br.readLine()) != null) {
            buffer.append(output);
        }

        ResponseBuilder builder = Response.status(Status.CREATED);
        builder.type("application/xml");
        buffer.append("</response>");
        builder.entity(buffer.toString());
        httpClient.getConnectionManager().shutdown();
        return builder.build();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.bibalex.gallery.storage.BAGStorage.java

public static boolean putFile(String remoteUrlStr, File localFile, String contentType, int timeout)
        throws BAGException {
    HttpPut httpput = null;/* w  w w . j ava  2  s  .  c  o m*/
    DefaultHttpClient httpclient = null;
    try {
        BasicHttpParams httpParams = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(httpParams, timeout);

        httpclient = new DefaultHttpClient(httpParams);
        URI remoteUrl = new URI(remoteUrlStr);
        String userInfo = remoteUrl.getUserInfo();
        if ((userInfo != null) && !userInfo.isEmpty()) {
            int colonIx = userInfo.indexOf(':');
            httpclient.getCredentialsProvider().setCredentials(
                    new AuthScope(remoteUrl.getHost(), remoteUrl.getPort()), new UsernamePasswordCredentials(
                            userInfo.substring(0, colonIx), userInfo.substring(colonIx + 1)));
        }

        if ((contentType == null) || contentType.isEmpty()) {
            contentType = "text/plain; charset=\"UTF-8\"";
        }

        FileEntity entity = new FileEntity(localFile, contentType);

        httpput = new HttpPut(remoteUrlStr);
        httpput.setEntity(entity);

        HttpResponse response = httpclient.execute(httpput);
        return response.getStatusLine().getStatusCode() - 200 < 100;

    } catch (IOException ex) {

        // In case of an IOException the connection will be released
        // back to the connection manager automatically
        throw new BAGException(ex);

    } catch (RuntimeException ex) {

        // In case of an unexpected exception you may want to abort
        // the HTTP request in order to shut down the underlying
        // connection and release it back to the connection manager.
        httpput.abort();
        throw ex;

    } catch (URISyntaxException e) {
        // will be still null: httpput.abort();
        throw new BAGException(e);
    } finally {

        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();

    }
}

From source file:gov.nih.nci.system.web.client.RESTfulUpdateClient.java

public Response update(File fileLoc, String url) {
    try {//from   w  ww.j a v a2 s.  c om
        if (url == null) {
            System.out.println("Invalid URL");
            ResponseBuilder builder = Response.status(Status.BAD_REQUEST);
            builder.type("application/xml");
            StringBuffer buffer = new StringBuffer();
            buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            buffer.append("<response>");
            buffer.append("<type>ERROR</type>");
            buffer.append("<code>INVALID_URL</code>");
            buffer.append("<message>Invalid URL: " + url + "</message>");
            buffer.append("</response>");
            builder.entity(buffer.toString());
            return builder.build();
        }

        if (fileLoc == null || !fileLoc.exists()) {
            System.out.println("Invalid file to create");
            ResponseBuilder builder = Response.status(Status.BAD_REQUEST);
            builder.type("application/xml");
            StringBuffer buffer = new StringBuffer();
            buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            buffer.append("<response>");
            buffer.append("<type>ERROR</type>");
            buffer.append("<code>INVALID_FILE</code>");
            buffer.append("<message>Invalid File given to read</message>");
            buffer.append("</response>");
            builder.entity(buffer.toString());
            return builder.build();
        }

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(url);

        FileEntity input = new FileEntity(fileLoc);
        input.setContentType("application/xml");
        if (userName != null && password != null) {
            String base64encodedUsernameAndPassword = new String(
                    Base64.encodeBase64((userName + ":" + password).getBytes()));
            postRequest.addHeader("Authorization", "Basic " + base64encodedUsernameAndPassword);
        }

        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        StringBuffer buffer = new StringBuffer();
        buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        buffer.append("<response>");
        while ((output = br.readLine()) != null) {
            buffer.append(output);
        }

        ResponseBuilder builder = Response.status(Status.CREATED);
        builder.type("application/xml");
        buffer.append("</response>");
        builder.entity(buffer.toString());
        httpClient.getConnectionManager().shutdown();
        return builder.build();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.marvelution.hudson.plugins.apiv2.client.connectors.HttpClient4Connector.java

/**
 * Method to create the {@link HttpClient}
 * /*from   ww w.j ava 2s  .  com*/
 * @return the {@link DefaultHttpClient}
 */
private DefaultHttpClient createClient() {
    DefaultHttpClient client = new DefaultHttpClient();
    if (server.isSecured()) {
        log.debug("The Server is secured, create the BasicHttpContext to handle preemptive authentication.");
        client.getCredentialsProvider().setCredentials(getAuthScope(),
                new UsernamePasswordCredentials(server.getUsername(), server.getPassword()));
        localContext = new BasicHttpContext();
        // Generate BASIC scheme object and stick it to the local execution context
        BasicScheme basicAuth = new BasicScheme();
        localContext.setAttribute("preemptive-auth", basicAuth);
        // Add as the first request intercepter
        client.addRequestInterceptor(new PreemptiveAuth(), 0);
    }
    if (StringUtils.isNotBlank(System.getProperty("http.proxyHost"))
            || StringUtils.isNotBlank(System.getProperty("https.proxyHost"))) {
        log.debug("A System HTTP(S) proxy is set, set the ProxySelectorRoutePlanner for the client");
        System.setProperty("java.net.useSystemProxies", "true");
        // Set the ProxySelectorRoute Planner to automatically select the system proxy host if set.
        client.setRoutePlanner(new ProxySelectorRoutePlanner(client.getConnectionManager().getSchemeRegistry(),
                ProxySelector.getDefault()));
    }
    return client;
}

From source file:test.gov.nih.nci.cacoresdk.domain.onetomany.unidirectional.selfassociation.MemberO2MUSResourceTest.java

public void testPut() throws Exception {

    try {/* www  .ja  va  2 s.c o  m*/
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String url = baseURL + "/rest/MemberO2MUS";
        HttpPut putRequest = new HttpPut(url);
        File myFile = new File("MemberO2MUS" + "XML.xml");
        if (!myFile.exists()) {
            testGet();
            myFile = new File("MemberO2MUS" + "XML.xml");
            if (!myFile.exists())
                return;
        }

        FileEntity input = new FileEntity(myFile);
        input.setContentType("application/xml");
        putRequest.setEntity(input);

        HttpResponse response = httpClient.execute(putRequest);

        if (response.getEntity() != null) {
            BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
        }

        httpClient.getConnectionManager().shutdown();
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }

}

From source file:test.gov.nih.nci.cacoresdk.domain.onetoone.unidirectional.selfassociation.MemberO2OUSResourceTest.java

public void testPut() throws Exception {

    try {//from www.j  av  a2  s.co m
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String url = baseURL + "/rest/MemberO2OUS";
        HttpPut putRequest = new HttpPut(url);
        File myFile = new File("MemberO2OUS" + "XML.xml");
        if (!myFile.exists()) {
            testGet();
            myFile = new File("MemberO2OUS" + "XML.xml");
            if (!myFile.exists())
                return;
        }

        FileEntity input = new FileEntity(myFile);
        input.setContentType("application/xml");
        putRequest.setEntity(input);

        HttpResponse response = httpClient.execute(putRequest);

        if (response.getEntity() != null) {
            BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
        }

        httpClient.getConnectionManager().shutdown();
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }

}