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:Simulator.java

private int GetRoutedTravelTime(Coordinate start, Coordinate end) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*  w w w  . j  av  a  2s .c  o  m*/
        // specify the get request
        HttpGet getRequest = new HttpGet("http://dev.virtualearth.net/REST/V1/Routes/Driving" + "?wp.0="
                + start.getLat() + "," + start.getLon() + "&wp.1=" + end.getLat() + "," + end.getLon()
                + "&ra=routeSummariesOnly"
                + "&key=Ah2BJh4cdLWewXKf-u5I98pNrwtZz6JJxfCnbC-5M4GTBeHKDbQdzxtOP8yypEmU");

        HttpResponse httpResponse = httpclient.execute(getRequest);
        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {
            return GetTravelTime(entity);
        } else {
            JOptionPane.showMessageDialog(null, "Something went wrong, could not request route information",
                    "InfoBox: " + "Uh Oh.", JOptionPane.INFORMATION_MESSAGE);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
    return 0;
}

From source file:com.liferay.ide.core.remote.RemoteConnection.java

private HttpClient getHttpClient() {
    if (this.httpClient == null) {
        DefaultHttpClient newDefaultHttpClient = null;

        if (getUsername() != null || getPassword() != null) {
            try {
                final IProxyService proxyService = LiferayCore.getProxyService();

                URI uri = new URI("http://" + getHost() + ":" + getHttpPort()); //$NON-NLS-1$ //$NON-NLS-2$
                IProxyData[] proxyDataForHost = proxyService.select(uri);

                for (IProxyData data : proxyDataForHost) {
                    if (data.getHost() != null && data.getPort() > 0) {
                        SchemeRegistry schemeRegistry = new SchemeRegistry();
                        schemeRegistry.register(
                                new Scheme("http", data.getPort(), PlainSocketFactory.getSocketFactory())); //$NON-NLS-1$

                        PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
                        cm.setMaxTotal(200);
                        cm.setDefaultMaxPerRoute(20);

                        DefaultHttpClient newHttpClient = new DefaultHttpClient(cm);
                        HttpHost proxy = new HttpHost(data.getHost(), data.getPort());

                        newHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

                        newDefaultHttpClient = newHttpClient;
                        break;
                    }// ww  w.  j av a  2 s  . c om
                }

                if (newDefaultHttpClient == null) {
                    uri = new URI("SOCKS://" + getHost() + ":" + getHttpPort()); //$NON-NLS-1$ //$NON-NLS-2$
                    proxyDataForHost = proxyService.select(uri);

                    for (IProxyData data : proxyDataForHost) {
                        if (data.getHost() != null) {
                            DefaultHttpClient newHttpClient = new DefaultHttpClient();
                            newHttpClient.getParams().setParameter("socks.host", data.getHost()); //$NON-NLS-1$
                            newHttpClient.getParams().setParameter("socks.port", data.getPort()); //$NON-NLS-1$
                            newHttpClient.getConnectionManager().getSchemeRegistry().register(
                                    new Scheme("socks", data.getPort(), PlainSocketFactory.getSocketFactory())); //$NON-NLS-1$

                            newDefaultHttpClient = newHttpClient;
                            break;
                        }
                    }
                }
            } catch (URISyntaxException e) {
                LiferayCore.logError("Unable to read proxy data", e); //$NON-NLS-1$
            }

            if (newDefaultHttpClient == null) {
                newDefaultHttpClient = new DefaultHttpClient();
            }

            this.httpClient = newDefaultHttpClient;
        } else {
            this.httpClient = new DefaultHttpClient();
        }
    }

    return this.httpClient;
}

From source file:com.serena.rlc.provider.jira.client.JiraClient.java

/**
 * Execute a get request/*from  w w w.  ja  va  2  s . c  o  m*/
 *
 * @param url
 * @return Response body
 * @throws JiraClientException
 */
protected String processGet(SessionData session, String jiraUrl, String url) throws JiraClientException {
    String uri = jiraUrl + url;

    logger.debug("Start executing JIRA GET request to url=\"{}\"", uri);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet getRequest = new HttpGet(uri);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(getJiraUsername(), getJiraPassword());
    getRequest.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));
    getRequest.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    getRequest.addHeader(HttpHeaders.ACCEPT, "application/json");
    String result = "";

    try {
        HttpResponse response = httpClient.execute(getRequest);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw createHttpError(response);
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        StringBuilder sb = new StringBuilder(1024);
        String output;
        while ((output = br.readLine()) != null) {
            sb.append(output);
        }
        result = sb.toString();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new JiraClientException("Server not available", e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    logger.debug("End executing JIRA GET request to url=\"{}\" and receive this result={}", uri, result);

    return result;
}

From source file:jp.mixi.android.sdk.MixiContainerImpl.java

private synchronized HttpClient getHttpClient() {
    if (mHttpClient != null) {
        return mHttpClient;
    }//from  w  ww.  jav a2  s  .  c om
    DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
    ClientConnectionManager mgr = defaultHttpClient.getConnectionManager();
    HttpParams params = defaultHttpClient.getParams();
    mHttpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()),
            params);
    mHttpClient.getParams().setParameter(HTTP_PARAM_CONNECTION_TIMEOUT, mConnectionTimeout);
    mHttpClient.getParams().setParameter(HTTP_PARAM_SOCKET_TIMEOUT, mSocketTimeout);
    return mHttpClient;
}

From source file:org.talend.librariesmanager.maven.ArtifactsDeployer.java

private void installToRemote(HttpEntity entity, URL targetURL) throws Exception {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {/*from  www  .jav  a 2 s  .c om*/
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(targetURL.getHost(), targetURL.getPort()),
                new UsernamePasswordCredentials(nexusServer.getUserName(), nexusServer.getPassword()));

        HttpPut httpPut = new HttpPut(targetURL.toString());
        httpPut.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPut);
        StatusLine statusLine = response.getStatusLine();
        int responseCode = statusLine.getStatusCode();
        EntityUtils.consume(entity);
        if (responseCode > 399) {
            if (responseCode == 500) {
                // ignor this error , if .pom already exist on server and deploy again will get this error
            } else if (responseCode == 401) {
                throw new BusinessException("Authrity failed");
            } else {
                throw new BusinessException(
                        "Deploy failed: " + responseCode + ' ' + statusLine.getReasonPhrase());
            }
        }
    } catch (Exception e) {
        throw new Exception(targetURL.toString(), e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:ch.tatool.core.module.creator.FileDownloadWorker.java

/** Loads the module file from the data server using the provided code. */
public void loadFile(String url, int timeout) {
    // give it a timeout to ensure the user does not wait forever in case of connectivity problems
    HttpParams params = new BasicHttpParams();
    if (timeout > 0) {
        HttpConnectionParams.setConnectionTimeout(params, timeout);
        HttpConnectionParams.setSoTimeout(params, timeout);
    }//from  w ww  .  java  2  s . com

    // remove whitespaces since they are not allowed
    url = url.replaceAll("\\s+", "").trim();

    // create a http client
    DefaultHttpClient httpclient = new DefaultHttpClient(params);
    HttpGet httpGet = new HttpGet(url);

    errorTitle = null;
    errorText = null;
    file = null;
    try {
        HttpResponse response = httpclient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            errorTitle = messages.getString("General.errorMessage.windowTitle.error");
            errorText = messages.getString("DataExportError.online.http");
            errorText += "\n" + response.getStatusLine().getReasonPhrase() + " ("
                    + response.getStatusLine().getStatusCode() + ")";
        } else {
            // copy the response into a temporary file
            HttpEntity entity = response.getEntity();
            byte[] data = EntityUtils.toByteArray(entity);
            File tmpFile = File.createTempFile("tatool_module", "tmp");
            FileUtils.writeByteArrayToFile(tmpFile, data);
            tmpFile.deleteOnExit();
            this.file = tmpFile;
        }
    } catch (IOException ioe) {
        errorTitle = messages.getString("General.errorMessage.windowTitle.error");
        errorText = messages.getString("DataExportError.online.http");
    } finally {
        // make sure we close the connection manager
        httpclient.getConnectionManager().shutdown();
    }
}

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

public void testPost() throws Exception {

    try {//from   ww w. j  av a2s . com
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String url = baseURL + "/rest/MemberO2MUS";
        WebClient client = WebClient.create(url);
        HttpPost postRequest = new HttpPost(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");
        System.out.println("input: " + myFile);
        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        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 testPost() throws Exception {

    try {//from   w w  w . j  a  v  a 2s .c o m
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String url = baseURL + "/rest/MemberO2OUS";
        WebClient client = WebClient.create(url);
        HttpPost postRequest = new HttpPost(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");
        System.out.println("input: " + myFile);
        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        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:org.jboss.as.test.clustering.cluster.ejb.stateful.StatefulFailoverTestCase.java

/**
 * Validates that a @Stateful(passivationCapable=false) bean does not replicate
 *//* w w w .  j a  v  a2s  . c  o m*/
@Test
public void noFailover(@ArquillianResource() @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
        @ArquillianResource() @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2) throws Exception {

    DefaultHttpClient client = org.jboss.as.test.http.util.HttpClientUtils.relaxedCookieHttpClient();

    URI uri1 = StatefulServlet.createURI(baseURL1, MODULE_NAME,
            PassivationIncapableIncrementorBean.class.getSimpleName());
    URI uri2 = StatefulServlet.createURI(baseURL2, MODULE_NAME,
            PassivationIncapableIncrementorBean.class.getSimpleName());

    try {
        assertEquals(1, queryCount(client, uri1));
        assertEquals(2, queryCount(client, uri1));

        assertEquals(0, queryCount(client, uri2));

        undeploy(DEPLOYMENT_2);

        assertEquals(1, queryCount(client, uri1));
        assertEquals(2, queryCount(client, uri1));

        deploy(DEPLOYMENT_2);

        assertEquals(3, queryCount(client, uri1));
        assertEquals(4, queryCount(client, uri1));

        assertEquals(0, queryCount(client, uri2));

        undeploy(DEPLOYMENT_1);

        assertEquals(1, queryCount(client, uri2));
        assertEquals(2, queryCount(client, uri2));

        deploy(DEPLOYMENT_1);

        assertEquals(0, queryCount(client, uri1));
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.example.week04.GcmIntentService.java

private void getArticleInBackground(final String keyword) {
    new AsyncTask<Void, Void, Void>() {
        private String resultMessage = "";

        @Override//w ww.  jav  a2s . co m
        protected Void doInBackground(Void... params) {
            String serverURL = new Settings().getServerURL();
            String URL = serverURL + "getArticle/" + keyword;
            DefaultHttpClient client = new DefaultHttpClient();
            String result;
            try {
                // Make connection to server.
                Log.i("Connection", "Make connection to server");
                HttpParams connectionParams = client.getParams();
                HttpConnectionParams.setConnectionTimeout(connectionParams, 5000);
                HttpConnectionParams.setSoTimeout(connectionParams, 5000);
                HttpGet httpGet = new HttpGet(URL);

                // Get response and parse entity.
                Log.i("Connection", "Get response and parse entity.");
                HttpResponse responsePost = client.execute(httpGet);
                HttpEntity resEntity = responsePost.getEntity();

                // Parse result to string.
                Log.i("Connection", "Parse result to string.");
                result = EntityUtils.toString(resEntity);
                result = result.replaceAll("'|&lt;|&quot;|&gt;", "''");
            } catch (Exception e) {
                e.printStackTrace();
                Log.i("Connection", "Some error in server!");
                result = "";
            }

            client.getConnectionManager().shutdown(); // Disconnect.

            if (!result.isEmpty()) {
                try {
                    JSONArray articleArray = new JSONArray(result);
                    int arrayLength = articleArray.length();
                    int updatedRow = 0;

                    DBHelper mHelper = new DBHelper(getApplicationContext());
                    SQLiteDatabase db = mHelper.getWritableDatabase();
                    for (int i = 0; i < arrayLength; i++) {
                        JSONObject articleObject = articleArray.getJSONObject(i);
                        String title = articleObject.getString("Title");
                        String link = articleObject.getString("Link");
                        String date = articleObject.getString("Date");
                        String news = articleObject.getString("News");
                        String content = articleObject.getString("Head");
                        String query = "INSERT INTO ARTICLES(KEYWORD, TITLE, NEWS, DATE, CONTENT, LINK) VALUES('"
                                + keyword + "', '" + title + "', '" + news + "', '" + date + "', '" + content
                                + "', '" + link + "');";
                        try {
                            updatedRow++;
                            db.execSQL(query);
                        } catch (SQLException e) {
                            updatedRow--;
                            Log.i("SQL inserting", "SQL exception in " + i + "th row : duplicated?");
                        }

                    }

                    String thisTime = getThisTime();
                    String query = "UPDATE KEYWORDS SET LASTUPDATE = '" + thisTime + "' WHERE KEYWORD = '"
                            + keyword + "';";
                    db.execSQL(query);

                    mHelper.close();

                    if (updatedRow > 0) {
                        resultMessage = "Article loading complete!";
                        sendNotification(
                                "'" + keyword + "'    " + updatedRow + " !");
                    } else {
                        resultMessage = "Loading complete - No fresh news.";
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    resultMessage = "Error in article loading - problem in JSONArray?";
                }
            } else {
                resultMessage = "Error in receiving articles!";
            }
            Log.i("JSON parsing", resultMessage);
            return null;
        }
    }.execute(null, null, null);
}