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:org.apache.solr.client.solrj.impl.BasicHttpSolrServerTest.java

@Test
public void testGetRawStream() throws SolrServerException, IOException {
    HttpClient client = HttpClientUtil.createClient(null);
    HttpSolrServer server = new HttpSolrServer(jetty.getBaseUrl().toString() + "/collection1", client, null);
    QueryRequest req = new QueryRequest();
    NamedList response = server.request(req);
    InputStream stream = (InputStream) response.get("stream");
    assertNotNull(stream);// ww  w . j av  a 2s  .  c  o m
    stream.close();
    client.getConnectionManager().shutdown();
}

From source file:com.groupon.odo.proxylib.BackupService.java

/**
 * Restore configuration from backup data
 *
 * @param streamData InputStream for configuration to restore
 * @return true if succeeded, false if operation failed
 *///  w  ww  . j  a v  a 2 s .co m
public boolean restoreBackupData(InputStream streamData) {
    // convert stream to string
    java.util.Scanner s = new java.util.Scanner(streamData).useDelimiter("\\A");
    String data = s.hasNext() ? s.next() : "";

    // parse JSON
    ObjectMapper mapper = new ObjectMapper();
    Backup backupData = null;
    try {
        backupData = mapper.readValue(data, Backup.class);
    } catch (Exception e) {
        logger.error("Could not parse input data: {}, {}", e.getClass(), e.getMessage());
        return false;
    }

    // TODO: validate json against a schema for safety

    // GROUPS
    try {
        logger.info("Number of groups: {}", backupData.getGroups().size());

        for (Group group : backupData.getGroups()) {
            // determine if group already exists.. if not then add it
            Integer groupId = PathOverrideService.getInstance().getGroupIdFromName(group.getName());
            if (groupId == null) {
                groupId = PathOverrideService.getInstance().addGroup(group.getName());
            }

            // get all methods from the group.. we are going to remove ones that don't exist in the new configuration
            List<Method> originalMethods = EditService.getInstance().getMethodsFromGroupId(groupId, null);

            for (Method originalMethod : originalMethods) {
                Boolean matchInImportGroup = false;

                int importCount = 0;
                for (Method importMethod : group.getMethods()) {
                    if (originalMethod.getClassName().equals(importMethod.getClassName())
                            && originalMethod.getMethodName().equals(importMethod.getMethodName())) {
                        matchInImportGroup = true;
                        break;
                    }
                    importCount++;
                }

                if (!matchInImportGroup) {
                    // remove it from current database since it is a delta to the current import
                    PathOverrideService.getInstance().removeOverride(originalMethod.getId());
                } else {
                    // remove from import list since it already exists
                    group.getMethods().remove(importCount);
                }
            }

            // add methods to groups
            for (Method method : group.getMethods()) {
                PathOverrideService.getInstance().createOverride(groupId, method.getMethodName(),
                        method.getClassName());
            }
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // PROFILES
    try {
        logger.info("Number of profiles: {}", backupData.getProfiles().size());

        // remove all servers
        // don't care about deltas here.. we'll just recreate them all
        // removed default servers (belong to group id=0)
        ServerRedirectService.getInstance().deleteServerGroup(0);

        for (com.groupon.odo.proxylib.models.backup.Profile profile : backupData.getProfiles()) {
            // see if a profile with this name already exists
            Integer profileId = ProfileService.getInstance().getIdFromName(profile.getName());
            com.groupon.odo.proxylib.models.Profile newProfile;
            if (profileId == null) {
                // create new profile
                newProfile = ProfileService.getInstance().add(profile.getName());
            } else {
                // get the existing profile
                newProfile = ProfileService.getInstance().findProfile(profileId);
            }

            // add new servers
            if (profile.getServers() != null) {
                for (ServerRedirect server : profile.getServers()) {
                    ServerRedirectService.getInstance().addServerRedirect(server.getRegion(),
                            server.getSrcUrl(), server.getDestUrl(), server.getHostHeader(), newProfile.getId(),
                            0);
                }
            }

            // remove all server groups
            for (ServerGroup group : ServerRedirectService.getInstance()
                    .tableServerGroups(newProfile.getId())) {
                ServerRedirectService.getInstance().deleteServerGroup(group.getId());
            }

            // add new server groups
            if (profile.getServerGroups() != null) {
                for (ServerGroup group : profile.getServerGroups()) {
                    int groupId = ServerRedirectService.getInstance().addServerGroup(group.getName(),
                            newProfile.getId());
                    for (ServerRedirect server : group.getServers()) {
                        ServerRedirectService.getInstance().addServerRedirect(server.getRegion(),
                                server.getSrcUrl(), server.getDestUrl(), server.getHostHeader(),
                                newProfile.getId(), groupId);
                    }
                }
            }

            // remove all paths
            // don't care about deltas here.. we'll just recreate them all
            for (EndpointOverride path : PathOverrideService.getInstance().getPaths(newProfile.getId(),
                    Constants.PROFILE_CLIENT_DEFAULT_ID, null)) {
                PathOverrideService.getInstance().removePath(path.getPathId());
            }

            // add new paths
            if (profile.getPaths() != null) {
                for (EndpointOverride path : profile.getPaths()) {
                    int pathId = PathOverrideService.getInstance().addPathnameToProfile(newProfile.getId(),
                            path.getPathName(), path.getPath());

                    PathOverrideService.getInstance().setContentType(pathId, path.getContentType());
                    PathOverrideService.getInstance().setRequestType(pathId, path.getRequestType());
                    PathOverrideService.getInstance().setGlobal(pathId, path.getGlobal());

                    // add groups to path
                    for (String groupName : path.getGroupNames()) {
                        int groupId = PathOverrideService.getInstance().getGroupIdFromName(groupName);
                        PathOverrideService.getInstance().AddGroupByNumber(newProfile.getId(), pathId, groupId);
                    }
                }
            }

            // set active
            ClientService.getInstance().updateActive(newProfile.getId(), Constants.PROFILE_CLIENT_DEFAULT_ID,
                    profile.getActive());
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // SCRIPTS
    try {
        // delete all scripts
        for (Script script : ScriptService.getInstance().getScripts()) {
            ScriptService.getInstance().removeScript(script.getId());
        }

        // add scripts
        for (Script script : backupData.getScripts()) {
            ScriptService.getInstance().addScript(script.getName(), script.getScript());
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // tell http/https proxies to reload plugins
    try {
        org.apache.http.conn.ssl.SSLSocketFactory sslsf = new org.apache.http.conn.ssl.SSLSocketFactory(
                new TrustStrategy() {
                    @Override
                    public boolean isTrusted(final X509Certificate[] chain, String authType)
                            throws CertificateException {
                        // ignore SSL cert issues
                        return true;
                    }
                });
        HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
        sslsf.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
        for (String connectstring : getConnectorStrings("https_proxy")) {
            HttpGet request = new HttpGet(connectstring + "/proxy/reload");

            HttpClient httpClient = new org.apache.http.impl.client.DefaultHttpClient();
            String[] parts = connectstring.split(":");
            httpClient.getConnectionManager().getSchemeRegistry()
                    .register(new org.apache.http.conn.scheme.Scheme("https",
                            Integer.parseInt(parts[parts.length - 1]), sslsf));
            HttpResponse response = httpClient.execute(request);
        }
    } catch (Exception e) {
        e.printStackTrace();
        logger.info("Exception caught during proxy reload.  Things may be in an inconsistent state.");
    }

    // restart plugin service for this process
    PluginManager.destroy();

    return true;
}

From source file:org.kairosdb.testclient.QueryTests.java

private JsonElement postQuery(JsonElement query) throws IOException, JSONException {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://" + m_host + ":" + m_port + "/api/v1/datapoints/query");
    post.setHeader("Content-Type", "application/json");

    post.setEntity(new StringEntity(query.toString()));
    HttpResponse httpResponse = client.execute(post);

    if (httpResponse.getStatusLine().getStatusCode() != 200) {
        httpResponse.getEntity().writeTo(System.out);
        return (null);
    }//from  w w  w . j  av a2s  .  c  o  m

    ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
    httpResponse.getEntity().writeTo(output);

    client.getConnectionManager().shutdown();
    return (m_parser.parse(output.toString("UTF-8")));
}

From source file:ch.ethz.inf.vs.android.g54.a4.net.RequestHandler.java

/**
 * Execute an HTTP post on a given resource on the configured server
 * //from  w  w  w. j a  v  a  2 s.c om
 * @param res
 *            The resource URL without host
 * @param data
 *            The data to post
 * @return a JSONObject / JSONArray
 * @throws ServerException
 * @throws ConnectionException
 * @throws UnrecognizedResponseException
 */
public Object post(String res, String data)
        throws ServerException, ConnectionException, UnrecognizedResponseException {
    U.logInPieces(TAG, String.format("Sending request for resource %s with data %s.", res, data));

    HttpClient client = new DefaultHttpClient();
    String responseBody = null;

    try {
        HttpPost post = new HttpPost(HOST + ":" + PORT + res);
        post.addHeader("Content-Type", "application/json");
        StringEntity se = new StringEntity(data);
        post.setEntity(se);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        responseBody = client.execute(post, responseHandler);

    } catch (ClientProtocolException e) {
        throw new ServerException("Server returned an error.", e);
    } catch (IOException e) {
        throw new ConnectionException("Could not connect to server.", e);
    } finally {
        client.getConnectionManager().shutdown();
    }
    return parseResponse(responseBody);
}

From source file:org.fedoraproject.eclipse.packager.api.UploadSourceCommand.java

/**
 * Wrap a basic HttpClient object in a Fedora SSL enabled HttpClient (which includes
 * Fedora SSL authentication cert) object.
 * /* w w  w.j a  va2 s. c om*/
 * @param base The HttpClient to wrap.
 * @return The SSL wrapped HttpClient.
 * @throws GeneralSecurityException
 * @throws IOException
 */
private HttpClient fedoraSslEnable(HttpClient base)
        throws GeneralSecurityException, FileNotFoundException, IOException {

    // Get a SSL related instance for setting up SSL connections.
    FedoraSSL fedoraSSL = FedoraSSLFactory.getInstance();
    SSLSocketFactory sf = new SSLSocketFactory(fedoraSSL.getInitializedSSLContext(), // may throw FileNotFoundE
            SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = base.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    Scheme https = new Scheme("https", 443, sf); //$NON-NLS-1$
    sr.register(https);
    return new DefaultHttpClient(ccm, base.getParams());
}

From source file:org.seasr.meandre.components.nlp.calais.OpenCalaisClient.java

@Override
public void executeCallBack(ComponentContext cc) throws Exception {
    String text = DataTypeParser.parseAsString(cc.getDataComponentFromInput(IN_TEXT))[0];

    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter("http.useragent", "SEASR " + getClass().getSimpleName());
    try {/*from   w  ww  .j a  v a2s.  c  o  m*/
        HttpPost post = new HttpPost(CALAIS_URL);
        post.setEntity(new StringEntity(text, _charset));
        for (Entry<String, String> entry : _headers.entrySet())
            post.setHeader(entry.getKey(), entry.getValue());

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = httpClient.execute(post, responseHandler);

        cc.pushDataComponentToOutput(OUT_RESPONSE, BasicDataTypesTools.stringToStrings(response));
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:org.sociotech.communitymashup.source.languagedetection.apiwrapper.DetectLanguageAPIWrapper.java

private String doPost(String url, Map<String, String> parameterMap) {
    String result = null;// w ww. j  av a2s .c  o  m

    HttpClient httpClient = new DefaultHttpClient();

    HttpPost post = new HttpPost(url);

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

    // add all post parameter
    for (String key : parameterMap.keySet()) {
        nameValuePairs.add(new BasicNameValuePair(key, parameterMap.get(key)));
    }

    ResponseHandler<String> responseHandler = new BasicResponseHandler();

    try {
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        result = httpClient.execute(post, responseHandler);
    } catch (Exception e) {
        // do nothing
    } finally {
        // client is no longer needed
        httpClient.getConnectionManager().shutdown();
    }

    return result;
}

From source file:eg.nileu.cis.nilestore.main.HttpDealer.java

/**
 * Put./*  w  w  w  . j  av  a 2  s.  c  o  m*/
 * 
 * @param filepath
 *            the filepath
 * @param url
 *            the url
 * @throws ClientProtocolException
 *             the client protocol exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static void put(String filepath, String url) throws ClientProtocolException, IOException {
    url = url + (url.endsWith("/") ? "" : "/") + "upload?t=json";
    HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost post = new HttpPost(url);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    File file = new File(filepath);
    final double filesize = file.length();

    ContentBody fbody = new FileBodyProgress(file, new ProgressListener() {

        @Override
        public void transfered(long bytes, float rate) {
            int percent = (int) ((bytes / filesize) * 100);
            String bar = ProgressUtils.progressBar("Uploading file to the gateway : ", percent, rate);
            System.err.print("\r" + bar);
            if (percent == 100) {
                System.err.println();
                System.err.println("wait the gateway is processing and saving your file");
            }
        }
    });

    entity.addPart("File", fbody);

    post.setEntity(entity);

    HttpResponse response = client.execute(post);

    if (response != null) {
        System.err.println(response.getStatusLine());
        HttpEntity ht = response.getEntity();
        String json = EntityUtils.toString(ht);
        JSONParser parser = new JSONParser();
        try {
            JSONObject obj = (JSONObject) parser.parse(json);
            System.out.println(obj.get("cap"));
        } catch (ParseException e) {
            System.err.println("Error during parsing the response: " + e.getMessage());
            System.exit(-1);
        }
    } else {
        System.err.println("Error: response = null");
    }

    client.getConnectionManager().shutdown();
}

From source file:org.jboss.as.test.integration.web.security.WebSecurityCERTTestCase.java

protected void makeCall(String alias, int expectedStatusCode) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient = wrapClient(httpclient, alias);
    try {//from w  w  w. j a v a  2s  . c o  m
        HttpGet httpget = new HttpGet(URL);

        HttpResponse response = httpclient.execute(httpget);

        StatusLine statusLine = response.getStatusLine();
        System.out.println("Response: " + statusLine);
        assertEquals(expectedStatusCode, statusLine.getStatusCode());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}