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.bitrepository.protocol.http.HttpFileExchange.java

/**
 * Method for putting data on the HTTP-server of a given url.
 * //from   www . j a va 2  s.co  m
 * TODO perhaps make it synchronized around the URL, to prevent data from 
 * trying to uploaded several times to the same location simultaneously. 
 * 
 * @param in The data to put into the url.
 * @param url The place to put the data.
 * @throws IOException If a problem with the connection occurs during the 
 * transaction. Also if the response code is 300 or above, which indicates
 * that the transaction has not been successful.
 */
private void performUpload(InputStream in, URL url) throws IOException {
    HttpClient httpClient = null;
    try {
        httpClient = getHttpClient();
        HttpPut httpPut = new HttpPut(url.toExternalForm());
        InputStreamEntity reqEntity = new InputStreamEntity(in, -1);
        reqEntity.setChunked(true);
        httpPut.setEntity(reqEntity);
        HttpResponse response = httpClient.execute(httpPut);

        // HTTP code >= 300 means error!
        if (response.getStatusLine().getStatusCode() >= HTTP_ERROR_CODE_BARRIER) {
            throw new IOException("Could not upload file to URL '" + url.toExternalForm()
                    + "'. got status code '" + response.getStatusLine() + "'");
        }
        log.debug("Uploaded datastream to url '" + url.toString() + "' and " + "received the response line '"
                + response.getStatusLine() + "'.");
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
}

From source file:org.jenkinsci.plugins.bitbucketNotifier.BitbucketNotifier.java

/**
 * Notifies the configured Bitbucket server by POSTing the build results
 * to the Bitbucket build API./*from  w  w w .  ja  v a 2s .c  o m*/
 *
 * @param logger      the logger to use
 * @param build         the build to notify Bitbucket of
 * @param commitSha1   the SHA1 of the built commit
 * @param listener      the build listener for logging
 * @param state         the state of the build as defined by the Bitbucket API.
 */
private NotificationResult notifyBitbucket(final PrintStream logger, final AbstractBuild<?, ?> build,
        final String commitSha1, final BuildListener listener, final BitbucketBuildState state)
        throws Exception {
    HttpEntity bitbucketBuildNotificationEntity = newBitbucketBuildNotificationEntity(build, state, listener);
    HttpPost req = createRequest(bitbucketBuildNotificationEntity, commitSha1);
    HttpClient client = getHttpClient(logger, build);
    try {
        HttpResponse res = client.execute(req);
        if (res.getStatusLine().getStatusCode() != 200 && res.getStatusLine().getStatusCode() != 201) {
            return NotificationResult.newFailure(EntityUtils.toString(res.getEntity()));
        } else {
            return NotificationResult.newSuccess();
        }
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:eu.liveGov.libraries.livegovtoolkit.Utils.RestClient.java

private void executeRequest(HttpUriRequest request, String url, int soTime, int connTime) throws Exception {
    HttpClient client = new DefaultHttpClient();

    // ----- Set timeout --------------
    // HttpParams httpParameters = new BasicHttpParams();
    ////  w  ww. ja  va  2  s  .c  o  m
    // // Set the timeout in milliseconds until a connection is established.
    // // The default value is zero, that means the timeout is not used.
    // int timeoutConnection = 1000;
    // HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // // Set the default socket timeout (SO_TIMEOUT)
    // // in milliseconds which is the timeout for waiting for data.
    // int timeoutSocket = 1000;
    // HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    client.getParams().setParameter("http.socket.timeout", soTime);
    client.getParams().setParameter("http.connection.timeout", connTime);

    // ----------------------------------

    try {
        httpResponse = client.execute(request);
    } catch (Exception e) {
        client.getConnectionManager().shutdown();
        e.printStackTrace();
        throw e;
    }
}

From source file:com.foundationdb.server.service.security.SecurityServiceIT.java

@Test
public void restAddDropUser() throws Exception {
    SecurityService securityService = securityService();
    assertNull(securityService.getUser("user3"));
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(getRestURL("/security/users", null, "akiban:topsecret"));
    post.setEntity(new StringEntity(ADD_USER, ContentType.APPLICATION_JSON));
    HttpResponse response = client.execute(post);
    int code = response.getStatusLine().getStatusCode();
    String content = EntityUtils.toString(response.getEntity());
    assertEquals(HttpStatus.SC_OK, code);
    assertNotNull(securityService.getUser("user3"));

    // Check returned id
    JsonNode idNode = readTree(content).get("id");
    assertNotNull("Has id field", idNode);
    assertEquals("id is integer", true, idNode.isInt());

    HttpDelete delete = new HttpDelete(getRestURL("/security/users/user3", null, "akiban:topsecret"));
    response = client.execute(delete);/*  w  w w. jav a 2 s . co  m*/
    code = response.getStatusLine().getStatusCode();
    EntityUtils.consume(response.getEntity());
    client.getConnectionManager().shutdown();
    assertEquals(HttpStatus.SC_OK, code);
    assertNull(securityService.getUser("user3"));
}

From source file:com.couchbase.capi.TestCouchbase.java

public void testPoolBucketDetails() throws Exception {
    HttpClient client = getClient();

    // first access the bucket with the correct bucket_uuid
    HttpUriRequest request = new HttpGet(String.format(
            "http://localhost:%d/pools/default/buckets/default?bucket_uuid=00000000000000000000000000000000",
            port));/*from w w  w. j a  va 2  s  .  co m*/
    HttpResponse response = client.execute(request);
    validateSuccessfulBucketResponse(response);

    // now access the bucket with the wrong bucket_uuid
    request = new HttpGet(String.format(
            "http://localhost:%d/pools/default/buckets/default?bucket_uuid=00000000000000000000000000000001",
            port));
    response = client.execute(request);
    validateMissingBucketResponse(response);

    // now access a non-existant bucket
    request = new HttpGet(String.format("http://localhost:%d/pools/default/buckets/does_not_exist", port));
    response = client.execute(request);
    validateMissingBucketResponse(response);

    client.getConnectionManager().shutdown();
}

From source file:ch.entwine.weblounge.test.harness.rest.PagesEndpointTest.java

/**
 * Locks the page./*www .  j a  va  2 s .  com*/
 * 
 * @param serverUrl
 *          the server url
 * @param id
 *          the page identifier
 * @throws Exception
 *           if updating failed
 */
private void testUnlockPage(String serverUrl, String id) throws Exception {
    String requestUrl = UrlUtils.concat(serverUrl, "system/weblounge/pages/", id);

    // Unlock the page
    HttpDelete unlockRequest = new HttpDelete(UrlUtils.concat(requestUrl, "lock"));
    HttpClient httpClient = new DefaultHttpClient();
    logger.info("Unlocking the page at {}", requestUrl);
    try {
        HttpResponse response = TestUtils.request(httpClient, unlockRequest, null);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    // Make sure the update was successful
    HttpGet getUpdatedPageRequest = new HttpGet(requestUrl);
    httpClient = new DefaultHttpClient();
    String[][] params = null;
    params = new String[][] { { "version", Long.toString(Resource.WORK) } };
    logger.info("Requesting locked page at {}", requestUrl);
    try {
        HttpResponse response = TestUtils.request(httpClient, getUpdatedPageRequest, params);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Document pageXml = TestUtils.parseXMLResponse(response);
        assertNull(XPathHelper.valueOf(pageXml, "/page/head/locked"));
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

}

From source file:com.github.restdriver.serverdriver.RestServerDriver.java

private static Response doHttpRequest(ServerDriverHttpUriRequest request) {

    HttpClient httpClient = new DefaultHttpClient(RestServerDriver.ccm, RestServerDriver.httpParams);

    HttpParams httpParams = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, (int) request.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(httpParams, (int) request.getSocketTimeout());
    HttpClientParams.setRedirecting(httpParams, false);

    if (request.getProxyHost() != null) {
        httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, request.getProxyHost());
    }/* w  ww.ja v a 2  s.c o m*/

    HttpUriRequest httpUriRequest = request.getHttpUriRequest();

    if (!httpUriRequest.containsHeader(USER_AGENT)) {
        httpUriRequest.addHeader(USER_AGENT, DEFAULT_USER_AGENT);
    }

    HttpResponse response;

    try {
        long startTime = System.currentTimeMillis();
        response = httpClient.execute(httpUriRequest);
        long endTime = System.currentTimeMillis();

        return new DefaultResponse(response, (endTime - startTime));

    } catch (ClientProtocolException cpe) {
        throw new RuntimeClientProtocolException(cpe);

    } catch (UnknownHostException uhe) {
        throw new RuntimeUnknownHostException(uhe);

    } catch (HttpHostConnectException hhce) {
        throw new RuntimeHttpHostConnectException(hhce);

    } catch (IOException e) {
        throw new RuntimeException("Error executing request", e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

}

From source file:ch.entwine.weblounge.test.harness.content.PageContentTest.java

/**
 * Tests that the work version of a page is returned if it exists when the
 * corresponding cookie is passed in.//from www . jav a 2  s .  c om
 * 
 * @param serverUrl
 *          the base server url
 * @throws Exception
 *           if the test fails
 */
private void testPageAsEditor(String serverUrl) throws Exception {
    logger.info("Preparing test of regular page content");

    // Prepare the request
    logger.info("Testing regular page output as an editor");

    String requestUrl = UrlUtils.concat(serverUrl, requestPath);

    logger.info("Sending request to the work version of {}", requestUrl);
    HttpGet request = new HttpGet(requestUrl);

    // Send and the request and examine the response
    logger.debug("Sending request to {}", request.getURI());
    HttpClient httpClient = new DefaultHttpClient();
    try {

        request.setHeader("Cookie", EditingState.STATE_COOKIE + "=true");

        HttpResponse response = TestUtils.request(httpClient, request, null);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());

        // Get the document contents
        Document xml = TestUtils.parseXMLResponse(response);

        // Look for included pagelet's properties
        String property = XPathHelper.valueOf(xml, "/html/body/div[@id='main']//span[@id='property']");
        assertNotNull("Content of pagelet property 'headline' not found", property);
        assertEquals("Element property does not match", "false", property);

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

}

From source file:ch.entwine.weblounge.test.harness.content.HTMLActionTest.java

/**
 * Tests whether the action returns its url correctly.
 * //w  ww. java 2  s .  c  o  m
 * @param serverUrl
 *          the server url
 */
private void testActionURL(String serverUrl) {
    // Prepare the request
    logger.info("Testing action url");

    HttpOptions request = new HttpOptions(UrlUtils.concat(serverUrl, defaultActionPath));

    // Send the request and make sure it ends up on the expected page
    logger.info("Sending request to {}", request.getURI());
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpResponse response = TestUtils.request(httpClient, request, null);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());

        // Make sure there is a Location header in the response
        Header locationHeader = response.getFirstHeader("Location");
        assertNotNull("Action did not return 'Location' header", locationHeader);
        String location = locationHeader.getValue();

        // Check that the action's url starts with the correct environment
        assertEquals("Action reports invalid url", defaultActionPath + "/", location);

    } catch (Throwable e) {
        fail("Request to " + request.getURI() + " failed" + e.getMessage());
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:org.wso2.carbon.appfactory.apiManager.integration.APIManagerIntegrationService.java

public boolean removeApplication(String applicationId, String samlToken) throws AppFactoryException {

    HttpClient httpClient = new DefaultHttpClient();
    try {/* w  w w.  j av a 2 s  . c om*/
        loginToStore(httpClient, samlToken);
        URL apiManagerUrl = getApiManagerURL();

        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair(ACTION, "removeApplication"));
        parameters.add(new BasicNameValuePair("application", applicationId));
        parameters.add(new BasicNameValuePair("tier", getDefaultTier()));

        HttpPost postMethod = createHttpPostRequest(apiManagerUrl, parameters, DELETE_APPLICATION_ENDPOINT);
        HttpResponse response = executeHttpMethod(httpClient, postMethod);

        if (response != null) {

        }
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return true;
}