Example usage for org.apache.http.client HttpClient getConnectionManager

List of usage examples for org.apache.http.client HttpClient getConnectionManager

Introduction

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

Prototype

@Deprecated
ClientConnectionManager getConnectionManager();

Source Link

Document

Obtains the connection manager used by this client.

Usage

From source file:com.basho.riak.client.util.ClientUtils.java

/**
 * Construct a new {@link HttpClient} instance given a {@link RiakConfig}.
 * /*from  w  ww .j a v a2  s .c o  m*/
 * @param config
 *            {@link RiakConfig} containing HttpClient configuration
 *            specifics.
 * @return A new {@link HttpClient}
 */
public static HttpClient newHttpClient(RiakConfig config) {

    HttpClient http = config.getHttpClient();
    ClientConnectionManager m;

    if (http == null) {
        m = new ThreadSafeClientConnManager();
        if (config.getMaxConnections() != null) {
            ((ThreadSafeClientConnManager) m).setMaxTotal(config.getMaxConnections());
            ((ThreadSafeClientConnManager) m).setDefaultMaxPerRoute(config.getMaxConnections());
        }
        http = new DefaultHttpClient(m);

        if (config.getRetryHandler() != null) {
            ((DefaultHttpClient) http).setHttpRequestRetryHandler(config.getRetryHandler());
        }
    } else {
        m = http.getConnectionManager();
    }

    HttpParams cp = http.getParams();
    if (config.getTimeout() != null) {
        cp.setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, config.getTimeout());
        cp.setIntParameter(AllClientPNames.SO_TIMEOUT, config.getTimeout());
    }

    return http;
}

From source file:net.saga.sync.gameserver.portal.CreatePlayer.java

public static Player createPlayer(HttpServletRequest req) throws UnsupportedEncodingException {
    SkeletonKeySession session = (SkeletonKeySession) req.getAttribute(SkeletonKeySession.class.getName());

    HttpClient client = new HttpClientBuilder().trustStore(session.getMetadata().getTruststore())
            .hostnameVerification(HttpClientBuilder.HostnameVerificationPolicy.ANY).build();
    try {// w  w  w . jav  a 2 s  .  c o m
        HttpPost post = new HttpPost("https://localhost:8443/gameserver-database/player");
        post.addHeader("Authorization", "Bearer " + session.getTokenString());
        post.setEntity(new StringEntity("{}"));
        try {
            HttpResponse response = client.execute(post);
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new RuntimeException("" + response.getStatusLine().getStatusCode());
            }
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            try {
                return JsonSerialization.readValue(is, Player.class);
            } finally {
                is.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.linkedin.pinot.monitor.util.HttpUtils.java

/**
 * {/*from  ww w  .j  a  v a  2  s  . c  o m*/
 text: "",
 attachments: [{
 title: "",
 description: "??",
 url: "",
 color: "warning|info|primary|error|muted|success"
 }]
 displayUser: {
 name: "??",
 avatarUrl: "??"
 }
 }
 * @param text
 * @return
 */

public static void postMonitorData(String text) {
    SSLContext sslContext = null;
    HttpClient client = new DefaultHttpClient();
    try {
        sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                    throws java.security.cert.CertificateException {

            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                    throws java.security.cert.CertificateException {

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } }, new SecureRandom());
    } catch (Exception e) {
        e.printStackTrace();
    }

    SSLSocketFactory ssf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = client.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    sr.register(new Scheme("https", 443, ssf));

    HttpPost httpPost = new HttpPost("https://hooks.pubu.im/services/1d2d2rwn8wb6sx");

    Map<String, Object> map = new HashMap<String, Object>();
    Map<String, String> sender = new HashMap<String, String>();
    sender.put("name", "Monitor");
    map.put("displayUser", sender);
    List<String> list = new ArrayList<String>();
    map.put("attachments", list);

    try {
        map.put("text", text);
        InputStreamEntity httpentity = new InputStreamEntity(
                new ByteArrayInputStream(mapper.writeValueAsBytes(map)), mapper.writeValueAsBytes(map).length);
        httpPost.setEntity(httpentity);
        httpPost.addHeader("Content-Type", "application/json");
        HttpResponse response = client.execute(httpPost);
        String result = EntityUtils.toString(response.getEntity());
        System.out.println(result);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        //
    }

}

From source file:com.easycode.common.HttpUtil.java

public static byte[] httpPost(String url, List<FormItem> blist) throws Exception {
    byte[] ret = null;
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
            Charset.forName("UTF-8"));
    if (blist != null) {
        for (FormItem f : blist) {
            reqEntity.addPart(f.getName(), f.getCtx());
        }// www  .  j  a  va  2  s  . c  om
    }
    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);

    HttpEntity resEntity = response.getEntity();

    if (resEntity != null) {
        InputStream tis = resEntity.getContent();

        java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = tis.read(bytes)) > 0) {
            out.write(bytes, 0, len);
        }
        ret = out.toByteArray();
    }
    EntityUtils.consume(resEntity);
    try {
        httpclient.getConnectionManager().shutdown();
    } catch (Exception ignore) {
    }
    return ret;
}

From source file:org.openremote.android.console.net.ORControllerServerSwitcher.java

/**
 * Detect the groupmembers of current server url
 *//*  w w  w. j a v  a  2  s. c  o  m*/
public static boolean detectGroupMembers(Context context) {
    Log.i(LOG_CATEGORY, "Detecting group members with current controller server url "
            + AppSettingsModel.getCurrentServer(context));

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 5 * 1000);
    HttpConnectionParams.setSoTimeout(params, 5 * 1000);
    HttpClient httpClient = new DefaultHttpClient(params);
    String url = AppSettingsModel.getSecuredServer(context);
    HttpGet httpGet = new HttpGet(url + "/rest/servers");

    if (httpGet == null) {
        Log.e(LOG_CATEGORY, "Create HttpRequest fail.");

        return false;
    }

    SecurityUtil.addCredentialToHttpRequest(context, httpGet);

    // TODO : fix the exception handling in this method -- it is ridiculous.

    try {
        URL uri = new URL(url);

        if ("https".equals(uri.getProtocol())) {
            Scheme sch = new Scheme(uri.getProtocol(), new SelfCertificateSSLSocketFactory(context),
                    uri.getPort());
            httpClient.getConnectionManager().getSchemeRegistry().register(sch);
        }

        HttpResponse httpResponse = httpClient.execute(httpGet);

        try {
            if (httpResponse.getStatusLine().getStatusCode() == Constants.HTTP_SUCCESS) {
                InputStream data = httpResponse.getEntity().getContent();

                try {
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    Document dom = builder.parse(data);
                    Element root = dom.getDocumentElement();

                    NodeList nodeList = root.getElementsByTagName("server");
                    int nodeNums = nodeList.getLength();
                    List<String> groupMembers = new ArrayList<String>();

                    for (int i = 0; i < nodeNums; i++) {
                        groupMembers.add(nodeList.item(i).getAttributes().getNamedItem("url").getNodeValue());
                    }

                    Log.i(LOG_CATEGORY, "Detected groupmembers. Groupmembers are " + groupMembers);

                    return saveGroupMembersToFile(context, groupMembers);
                } catch (IOException e) {
                    Log.e(LOG_CATEGORY, "The data is from ORConnection is bad", e);
                } catch (ParserConfigurationException e) {
                    Log.e(LOG_CATEGORY, "Cant build new Document builder", e);
                } catch (SAXException e) {
                    Log.e(LOG_CATEGORY, "Parse data error", e);
                }
            }

            else {
                Log.e(LOG_CATEGORY, "detectGroupMembers Parse data error");
            }
        }

        catch (IllegalStateException e) {
            Log.e(LOG_CATEGORY, "detectGroupMembers Parse data error", e);
        }

        catch (IOException e) {
            Log.e(LOG_CATEGORY, "detectGroupMembers Parse data error", e);
        }

    }

    catch (MalformedURLException e) {
        Log.e(LOG_CATEGORY, "Create URL fail:" + url);
    }

    catch (ConnectException e) {
        Log.e(LOG_CATEGORY, "Connection refused: " + AppSettingsModel.getCurrentServer(context), e);
    }

    catch (ClientProtocolException e) {
        Log.e(LOG_CATEGORY, "Can't Detect groupmembers with current controller server "
                + AppSettingsModel.getCurrentServer(context), e);
    }

    catch (SocketTimeoutException e) {
        Log.e(LOG_CATEGORY, "Can't Detect groupmembers with current controller server "
                + AppSettingsModel.getCurrentServer(context), e);
    }

    catch (IOException e) {
        Log.e(LOG_CATEGORY, "Can't Detect groupmembers with current controller server "
                + AppSettingsModel.getCurrentServer(context), e);
    }

    catch (IllegalArgumentException e) {
        Log.e(LOG_CATEGORY, "Host name can be null :" + AppSettingsModel.getCurrentServer(context), e);
    }

    return false;
}

From source file:org.cloudifysource.azure.CliAzureDeploymentTest.java

private static boolean isUrlAvailable(URL url) throws URISyntaxException {
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url.toURI());
    httpGet.addHeader("Cache-Control", "no-cache");
    try {/*from  w  ww. j ava2  s. c  o m*/
        HttpResponse response = client.execute(httpGet);
        System.out.print("HTTP GET " + url + "Response:");
        response.getEntity().writeTo(System.out);
        System.out.print("");
        if (response.getStatusLine().getStatusCode() == 404) {
            return false;
        }
        return true;
    } catch (Exception e) {
        log("Failed connecting to " + url, e);
        return false;
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.jsquant.listener.JsquantContextListener.java

public void contextDestroyed(ServletContextEvent sce) {
    ServletContext context = sce.getServletContext();
    context.removeAttribute(ATTR_FILE_CACHE);

    HttpClient httpClient = getHttpClient(context);
    if (httpClient != null) {
        httpClient.getConnectionManager().shutdown();
    }/*w ww .j a  v a  2 s  .c  o m*/
    context.removeAttribute(ATTR_HTTP_CLIENT);
}

From source file:ca.sqlpower.enterprise.ClientSideSessionUtils.java

public static ProjectLocation createNewServerSession(SPServerInfo serviceInfo, String name,
        CookieStore cookieStore, UserPrompterFactory userPrompterFactory)
        throws URISyntaxException, ClientProtocolException, IOException, JSONException {

    HttpClient httpClient = ClientSideSessionUtils.createHttpClient(serviceInfo, cookieStore);
    try {// w ww. j  a v  a 2 s .c o m
        HttpUriRequest request = new HttpGet(
                getServerURI(serviceInfo, "/" + REST_TAG + "/jcr/projects/new", "name=" + name));
        JSONMessage message = httpClient.execute(request, new JSONResponseHandler());
        JSONObject response = new JSONObject(message.getBody());
        return new ProjectLocation(response.getString("uuid"), response.getString("name"), serviceInfo);
    } catch (AccessDeniedException e) {
        userPrompterFactory
                .createUserPrompter("You do not have sufficient privileges to create a new workspace.",
                        UserPromptType.MESSAGE, UserPromptOptions.OK, UserPromptResponse.OK, "OK", "OK")
                .promptUser("");
        return null;
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:org.apache.solr.client.solrj.impl.HttpClientUtilTest.java

@SuppressWarnings("deprecation")
private X509HostnameVerifier getHostnameVerifier(HttpClient client) {
    return ((SSLSocketFactory) client.getConnectionManager().getSchemeRegistry().get("https")
            .getSchemeSocketFactory()).getHostnameVerifier();
}

From source file:biz.webgate.tools.urlfetcher.URLFetcher.java

public static PageAnalyse analyseURL(String url, int maxPictureHeight) throws FetcherException {
    PageAnalyse analyse = new PageAnalyse(url);
    HttpClient httpClient = null;
    try {//w w w .  j ava2s . com
        httpClient = new DefaultHttpClient();
        ((DefaultHttpClient) httpClient).setRedirectStrategy(new DefaultRedirectStrategy());
        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader("Content-Type", "text/html; charset=utf-8");
        HttpResponse response = httpClient.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode == STATUS_OK) {
            HttpEntity entity = response.getEntity();
            parseContent(maxPictureHeight, analyse, entity.getContent());

        } else {
            throw new FetcherException("Response from WebSite is :" + statusCode);
        }
    } catch (IllegalStateException e) {
        throw new FetcherException(e);
    } catch (FetcherException e) {
        throw e;
    } catch (Exception e) {
        throw new FetcherException(e);
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
    return analyse;
}