Example usage for org.apache.http.client.utils HttpClientUtils closeQuietly

List of usage examples for org.apache.http.client.utils HttpClientUtils closeQuietly

Introduction

In this page you can find the example usage for org.apache.http.client.utils HttpClientUtils closeQuietly.

Prototype

public static void closeQuietly(final HttpClient httpClient) 

Source Link

Document

Unconditionally close a httpClient.

Usage

From source file:com.jivesoftware.os.routing.bird.http.client.ApacheHttpClient441BackedHttpClient.java

private HttpResponse execute(HttpRequestBase requestBase) throws IOException, OAuthMessageSignerException,
        OAuthExpectationFailedException, OAuthCommunicationException {

    applyHeadersCommonToAllRequests(requestBase);

    byte[] responseBody;
    StatusLine statusLine = null;/* w w w  . j av a  2s . c  o  m*/
    if (LOG.isInfoEnabled()) {
        LOG.startTimer(TIMER_NAME);
    }

    activeCount.incrementAndGet();
    CloseableHttpResponse response = null;
    try {
        response = client.execute(requestBase);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        InputStream responseBodyAsStream = response.getEntity().getContent();
        if (responseBodyAsStream != null) {
            IOUtils.copy(responseBodyAsStream, outputStream);
        }

        responseBody = outputStream.toByteArray();
        statusLine = response.getStatusLine();
        return new HttpResponse(statusLine.getStatusCode(), statusLine.getReasonPhrase(), responseBody);

    } finally {
        if (response != null) {
            HttpClientUtils.closeQuietly(response);
        }
        requestBase.reset();
        activeCount.decrementAndGet();
        if (LOG.isInfoEnabled()) {
            long elapsedTime = LOG.stopTimer(TIMER_NAME);
            StringBuilder httpInfo = new StringBuilder();
            if (statusLine != null) {
                httpInfo.append("Outbound ").append(statusLine.getProtocolVersion()).append(" Status ")
                        .append(statusLine.getStatusCode());
            } else {
                httpInfo.append("Exception sending request");
            }
            httpInfo.append(" in ").append(elapsedTime).append(" ms ").append(requestBase.getMethod())
                    .append(" ").append(client).append(requestBase.getURI());
            LOG.debug(httpInfo.toString());
        }
    }
}

From source file:org.jboss.additional.testsuite.jdkall.present.clustering.cluster.ejb.xpc.StatefulWithXPCFailoverTestCase.java

private static String executeUrlWithAnswer(HttpClient client, URI url, String message) throws IOException {
    HttpResponse response = client.execute(new HttpGet(url));
    try {//from   www  .  j a  va 2 s  . c o  m
        assertEquals(200, response.getStatusLine().getStatusCode());
        Header header = response.getFirstHeader("answer");
        Assert.assertNotNull(message, header);
        return header.getValue();
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

From source file:org.jboss.additional.testsuite.jdkall.present.clustering.cluster.ejb.xpc.StatefulWithXPCFailoverTestCase.java

private static void assertExecuteUrl(HttpClient client, URI url) throws IOException {
    HttpResponse response = client.execute(new HttpGet(url));
    try {/* ww w.j a v  a  2s.co m*/
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

From source file:sachin.spider.WebSpider.java

private void handleRedirectedLink(WebURL curUrl) {
    String url = curUrl.getUrl();
    HttpGet httpget = new HttpGet(url);
    RequestConfig requestConfig = getRequestConfigWithRedirectEnabled();
    httpget.setConfig(requestConfig);/*from  w w w .j av  a 2  s  .c om*/
    try {
        HttpClientContext context = HttpClientContext.create();
        long startingTime = System.currentTimeMillis();
        try (CloseableHttpResponse response = httpclient.execute(httpget, context)) {
            long endingTime = System.currentTimeMillis();
            HttpHost target = context.getTargetHost();
            List<URI> redirectLocations = context.getRedirectLocations();
            URI location = URIUtils.resolve(httpget.getURI(), target, redirectLocations);
            String redirectUrl = location.toString();
            curUrl.setRedirectTo(redirectUrl);
            curUrl.setResposneTime(((int) (endingTime - startingTime)) / 1000);
            redirectUrl = URLCanonicalizer.getCanonicalURL(redirectUrl);
            WebURL weburl = new WebURL(redirectUrl);
            weburl.addParent(curUrl);
            if (!config.links.contains(weburl)) {
                config.links.add(weburl);
            }
            try {
                if (redirectLocations != null) {
                    for (URI s : redirectLocations) {
                        String urls = URLCanonicalizer.getCanonicalURL(s.toString());
                        WebURL url1 = new WebURL(urls);
                        if (!config.links.contains(url1)) {
                            config.links.add(url1);
                        }
                    }
                }
            } catch (Exception ex) {
                Logger.getLogger(WebSpider.class.getName()).log(Level.SEVERE, null, ex);
            }
            EntityUtils.consumeQuietly(response.getEntity());
            HttpClientUtils.closeQuietly(response);
        }
    } catch (IOException | URISyntaxException ex) {
        System.out.println(curUrl.getUrl());
        curUrl.setErrorMsg(ex.toString());
        Logger.getLogger(WebSpider.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        System.out.println(curUrl.getUrl());
        curUrl.setErrorMsg(ex.toString());
        Logger.getLogger(WebSpider.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        httpget.releaseConnection();
    }
}

From source file:com.hp.mqm.client.MqmRestClientImpl.java

@Override
public JobConfiguration getJobConfiguration(String serverIdentity, String jobName) {
    HttpGet request = new HttpGet(
            createSharedSpaceInternalApiUri(URI_JOB_CONFIGURATION, serverIdentity, jobName));
    HttpResponse response = null;//from   ww  w. ja  v  a  2  s  . c  om
    try {
        response = execute(request);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw createRequestException("Job configuration retrieval failed", response);
        }
        String json = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        try {
            JSONObject jsonObject = JSONObject.fromObject(json);
            List<Pipeline> pipelines = new LinkedList<>();
            for (JSONObject relatedContext : getJSONObjectCollection(jsonObject, "data")) {
                if ("pipeline".equals(relatedContext.getString("contextEntityType"))) {
                    pipelines.add(toPipeline(relatedContext));
                } else {
                    logger.info(
                            "Context type '" + relatedContext.get("contextEntityType") + "' is not supported");
                }
            }
            return new JobConfiguration(pipelines);
        } catch (JSONException e) {
            throw new RequestErrorException("Failed to obtain job configuration", e);
        }
    } catch (IOException e) {
        throw new RequestErrorException("Cannot retrieve job configuration from MQM.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

From source file:com.comcast.drivethru.client.DefaultRestClient.java

@Override
public void close() throws IOException {
    HttpClientUtils.closeQuietly(delegate);
}

From source file:cf.client.DefaultCloudController.java

@Override
public UUID createServiceInstance(Token token, String name, UUID planGuid, UUID spaceGuid) {
    try {//from  w  w w .ja v  a 2  s . c o  m
        final ObjectNode json = mapper.createObjectNode();
        json.put("name", name);
        json.put("service_plan_guid", planGuid.toString());
        json.put("space_guid", spaceGuid.toString());
        final HttpPost post = new HttpPost(target.resolve(V2_SERVICE_INSTANCES));
        post.addHeader(token.toAuthorizationHeader());
        post.setEntity(new StringEntity(json.toString(), ContentType.APPLICATION_JSON));
        final HttpResponse response = httpClient.execute(post);
        try {
            validateResponse(response, 201);
            final JsonNode jsonResponse = mapper.readTree(response.getEntity().getContent());
            return UUID.fromString(jsonResponse.get("metadata").get("guid").asText());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jboss.additional.testsuite.jdkall.present.clustering.cluster.ejb.stateful.StatefulFailoverTestCase.java

private static int queryCount(HttpClient client, URI uri) throws IOException {
    HttpResponse response = client.execute(new HttpGet(uri));
    try {//from   w  ww. j a v a  2  s  .c  om
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        return Integer.parseInt(response.getFirstHeader("count").getValue());
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

From source file:org.jboss.as.test.clustering.modcluster.WorkerFailoverTestCase.java

@Test
public void workerFailoverTest() throws URISyntaxException, IOException {
    String address = TestSuiteEnvironment.getServerAddress("node0");
    URL url = new URL("http", address, 8080, "/jvmroute/jvmroute");
    URI uri = url.toURI();/*from w  w  w .  j a va2 s .  c  om*/

    /* Checks whether all servers are set as expected */
    infrastructureCheck();

    try (CloseableHttpClient httpClient = TestHttpClientUtils.promiscuousCookieHttpClient()) {
        HttpResponse response = null;
        String worker1, worker2;

        try {
            /* The first HTTP request */
            response = httpClient.execute(new HttpGet(uri));

            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            HttpEntity entity = response.getEntity();
            Assert.assertNotNull(entity);
            worker1 = EntityUtils.toString(entity);

            if (!worker1.equals("worker-1"))
                Assert.assertEquals("worker-2", worker1);

            /* Undeploy worker which responsed the first HTTP request */
            if (worker1.equals("worker-1")) {
                NodeUtil.undeploy(this.deployer, DEPLOYMENT_1);
                undeployedApp = DEPLOYMENT_1;
            } else {
                NodeUtil.undeploy(this.deployer, DEPLOYMENT_2);
                undeployedApp = DEPLOYMENT_2;
            }

            /* The second HTTP request */
            response = httpClient.execute(new HttpGet(uri));

            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            entity = response.getEntity();
            Assert.assertNotNull(entity);
            worker2 = EntityUtils.toString(entity);

            /* Checks that the second node responded the second request */
            if (worker1.equals("worker-1"))
                Assert.assertEquals("worker-2", worker2);
            else
                Assert.assertEquals("worker-1", worker2);

        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    }
}

From source file:com.hp.mqm.client.MqmRestClientImpl.java

@Override
public Pipeline createPipeline(String serverIdentity, String projectName, String pipelineName, long workspaceId,
        Long releaseId, String structureJson, String serverJson) {
    HttpPost request = new HttpPost(
            createSharedSpaceInternalApiUri(URI_JOB_CONFIGURATION, serverIdentity, projectName));
    JSONObject pipelineObject = new JSONObject();
    pipelineObject.put("contextEntityType", "pipeline");
    pipelineObject.put("contextEntityName", pipelineName);
    pipelineObject.put("workspaceId", workspaceId);
    pipelineObject.put("releaseId", releaseId);
    pipelineObject.put("server", JSONObject.fromObject(serverJson));
    pipelineObject.put("structure", JSONObject.fromObject(structureJson));
    request.setEntity(new StringEntity(pipelineObject.toString(), ContentType.APPLICATION_JSON));
    HttpResponse response = null;//w  w  w. j  a  v a 2 s  .  co m
    try {
        response = execute(request);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
            throw createRequestException("Pipeline creation failed", response);
        }
        String json = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        return getPipelineByName(json, pipelineName, workspaceId);
    } catch (IOException e) {
        throw new RequestErrorException("Cannot create pipeline in MQM.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}