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.hp.mqm.client.MqmRestClientImpl.java

@Override
public Boolean isTestResultRelevant(String serverIdentity, String jobName) {

    URI supportsBase64Uri = createSharedSpaceInternalApiUri(URI_BASE64SUPPORT);
    HttpGet request = new HttpGet(supportsBase64Uri);
    HttpResponse response = null;/*from   www  . ja va2  s . co m*/
    String jobNameForSending = jobName;
    try {
        response = execute(request);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            logger.log(Level.INFO, "Octane supports base64 encoding");
            jobNameForSending = Base64.encodeBase64String(jobName.getBytes());
        }
    } catch (IOException ex) {
        logger.log(Level.INFO, "Octane does not support base64 encoding");
    }

    logger.log(Level.INFO,
            String.format("Job name before encoding: %s, after encoding : %s", jobName, jobNameForSending));

    URI getUri = createSharedSpaceInternalApiUri(URI_PREFLIGHT, serverIdentity, jobNameForSending);
    try {
        URIBuilder uriPreflight = new URIBuilder(
                createSharedSpaceInternalApiUri(URI_PREFLIGHT, serverIdentity, jobNameForSending))
                        .addParameter("isBase64", "true");

        logger.log(Level.INFO, String.format("test preflight URI: %s", uriPreflight.build().getPath()));

        getUri = uriPreflight.build();
    } catch (URISyntaxException ex) {
        logger.log(Level.SEVERE, "Error creating uri for test preflight!", ex);
    }

    request = new HttpGet(getUri);
    response = null;
    try {
        response = execute(request);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw createRequestException("Result status retrieval failed", response);
        }
        return Boolean.parseBoolean(IOUtils.toString(response.getEntity().getContent(), "UTF-8"));
    } catch (IOException e) {
        throw new RequestErrorException("Cannot obtain status.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

From source file:org.jboss.quickstarts.wfk.travelagent.travelplan.TravelPlanService.java

private long bookFlight(TravelSketch travelSketch) throws Exception {
    URI uri = new URIBuilder().setScheme("http").setHost("jbosscontactsangularjs-110336260.rhcloud.com")
            .setPath("/rest/bookings").build();
    HttpPost req = new HttpPost(uri);
    StringEntity params = new StringEntity("{\"customerId\":\"" + travelAgentFlight.toString()
            + "\",\"flightId\":\"" + travelSketch.getFlightId().toString() + "\",\"bookingDate\":\""
            + travelSketch.getBookingDate() + "\"}");
    req.addHeader("Content-Type", "application/json");
    req.setEntity(params);/*from  ww  w. j  a v  a2s .co m*/
    CloseableHttpResponse response = httpClient.execute(req);
    if (response.getStatusLine().getStatusCode() != 201) {
        throw new Exception("Failed to create a flight booking");
    }
    String responseBody = EntityUtils.toString(response.getEntity());
    JSONObject responseJson = new JSONObject(responseBody);
    long rtn = responseJson.getLong("id");
    HttpClientUtils.closeQuietly(response);
    return rtn;
}

From source file:org.gradle.caching.http.internal.HttpBuildCacheService.java

@Override
public void store(BuildCacheKey key, final BuildCacheEntryWriter output) throws BuildCacheException {
    final URI uri = root.resolve(key.getHashCode());
    HttpPut httpPut = new HttpPut(uri);
    httpPut.addHeader(HttpHeaders.CONTENT_TYPE, BUILD_CACHE_CONTENT_TYPE);
    addDiagnosticHeaders(httpPut);/*from   www.  j  av  a2  s.  c o m*/

    httpPut.setEntity(new AbstractHttpEntity() {
        @Override
        public boolean isRepeatable() {
            return false;
        }

        @Override
        public long getContentLength() {
            return output.getSize();
        }

        @Override
        public InputStream getContent() throws IOException, UnsupportedOperationException {
            throw new UnsupportedOperationException();
        }

        @Override
        public void writeTo(OutputStream outstream) throws IOException {
            output.writeTo(outstream);
        }

        @Override
        public boolean isStreaming() {
            return false;
        }
    });
    CloseableHttpResponse response = null;
    try {
        response = httpClientHelper.performHttpRequest(httpPut);
        StatusLine statusLine = response.getStatusLine();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Response for PUT {}: {}", safeUri(uri), statusLine);
        }
        int statusCode = statusLine.getStatusCode();
        if (!isHttpSuccess(statusCode)) {
            String defaultMessage = String.format("Storing entry at '%s' response status %d: %s", safeUri(uri),
                    statusCode, statusLine.getReasonPhrase());
            if (isRedirect(statusCode)) {
                handleRedirect(uri, response, statusCode, defaultMessage, "storing entry at");
            } else {
                throwHttpStatusCodeException(statusCode, defaultMessage);
            }
        }
    } catch (ClientProtocolException e) {
        Throwable cause = e.getCause();
        if (cause instanceof NonRepeatableRequestException) {
            throw wrap(cause.getCause());
        } else {
            throw wrap(cause);
        }
    } catch (IOException e) {
        throw wrap(e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

From source file:org.jboss.as.test.clustering.cluster.web.ClusteredWebFailoverAbstractCase.java

/**
 * Test simple undeploy failover:/*from  w  w w.j a  va2  s . co m*/
 * <p/>
 * 1/ Start 2 containers and deploy <distributable/> webapp.
 * 2/ Query first container creating a web session.
 * 3/ Undeploy application from the first container.
 * 4/ Query second container verifying sessions got replicated.
 * 5/ Redeploy application to the first container.
 * 6/ Query first container verifying that updated sessions replicated back.
 *
 * @throws IOException
 * @throws InterruptedException
 * @throws URISyntaxException
 */
@Test
public void testGracefulUndeployFailover(
        @ArquillianResource(SimpleServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
        @ArquillianResource(SimpleServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
        throws IOException, InterruptedException, URISyntaxException {

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

    String url1 = baseURL1.toString() + "simple";
    String url2 = baseURL2.toString() + "simple";

    try {
        HttpResponse response = client.execute(new HttpGet(url1));
        try {
            log.info("Requested " + url1 + ", got " + response.getFirstHeader("value").getValue() + ".");
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(1, Integer.parseInt(response.getFirstHeader("value").getValue()));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Lets do this twice to have more debug info if failover is slow.
        response = client.execute(new HttpGet(url1));
        try {
            log.info("Requested " + url1 + ", got " + response.getFirstHeader("value").getValue() + ".");
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(2, Integer.parseInt(response.getFirstHeader("value").getValue()));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Gracefully undeploy from the 1st container.
        undeploy(DEPLOYMENT_1);

        // Now check on the 2nd server

        // Note that this DOES rely on the fact that both servers are running on the "same" domain,
        // which is '127.0.0.1'. Otherwise you will have to spoof cookies. @Rado
        response = client.execute(new HttpGet(url2));
        try {
            log.info("Requested " + url2 + ", got " + response.getFirstHeader("value").getValue() + ".");
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals("Session failed to replicate after container 1 was shutdown.", 3,
                    Integer.parseInt(response.getFirstHeader("value").getValue()));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Lets do one more check.
        response = client.execute(new HttpGet(url2));
        try {
            log.info("Requested " + url2 + ", got " + response.getFirstHeader("value").getValue() + ".");
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(4, Integer.parseInt(response.getFirstHeader("value").getValue()));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Redeploy
        deploy(DEPLOYMENT_1);

        response = client.execute(new HttpGet(url1));
        try {
            log.info("Requested " + url1 + ", got " + response.getFirstHeader("value").getValue() + ".");
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals("Session failed to replicate after container 1 was brough up.", 5,
                    Integer.parseInt(response.getFirstHeader("value").getValue()));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Lets do this twice to have more debug info if failover is slow.
        response = client.execute(new HttpGet(url1));
        try {
            log.info("Requested " + url1 + ", got " + response.getFirstHeader("value").getValue() + ".");
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(6, Integer.parseInt(response.getFirstHeader("value").getValue()));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:org.jboss.as.test.clustering.cluster.web.DistributableTestCase.java

private void testGracefulServe(URL baseURL, Lifecycle lifecycle)
        throws URISyntaxException, IOException, InterruptedException {

    try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
        URI uri = SimpleServlet.createURI(baseURL);

        // Make sure a normal request will succeed
        HttpResponse response = client.execute(new HttpGet(uri));
        try {/*from w w w .j  av a 2  s  . co m*/
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Send a long request - in parallel
        URI longRunningURI = SimpleServlet.createURI(baseURL, REQUEST_DURATION);
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<HttpResponse> future = executor.submit(new RequestTask(client, longRunningURI));

        // Make sure long request has started
        Thread.sleep(1000);

        lifecycle.stop(NODE_1);

        // Get result of long request
        // This request should succeed since it initiated before server shutdown
        try {
            response = future.get();
            try {
                Assert.assertEquals("Request should succeed since it initiated before undeply or shutdown.",
                        HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            } finally {
                HttpClientUtils.closeQuietly(response);
            }
        } catch (ExecutionException e) {
            e.printStackTrace(System.err);
            Assert.fail(e.getCause().getMessage());
        }
    }
}

From source file:com.hp.mqm.clt.RestClient.java

protected CloseableHttpResponse execute(HttpUriRequest request) throws IOException {
    //doFirstLogin();
    if (LWSSO_TOKEN == null) {
        login();/*from ww w. j  av a  2 s  .  co m*/
    }
    HttpContext localContext = new BasicHttpContext();
    CookieStore localCookies = new BasicCookieStore();
    localCookies.addCookie(LWSSO_TOKEN);
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, localCookies);
    addClientTypeHeader(request);
    CloseableHttpResponse response = httpClient.execute(request, localContext);
    if (isLoginNecessary(response)) { // if request fails with 401 do login and execute request again
        HttpClientUtils.closeQuietly(response);
        login();
        localCookies.clear();
        localCookies.addCookie(LWSSO_TOKEN);
        localContext.setAttribute(HttpClientContext.COOKIE_STORE, localCookies);
        response = httpClient.execute(request, localContext);
    }
    return response;
}

From source file:com.mirth.connect.client.core.ConnectServiceUtil.java

public static int getNotificationCount(String serverId, String mirthVersion,
        Map<String, String> extensionVersions, Set<Integer> archivedNotifications, String[] protocols,
        String[] cipherSuites) {//from   w  w  w  . j a v a  2  s .c o m
    CloseableHttpClient client = null;
    HttpPost post = new HttpPost();
    CloseableHttpResponse response = null;

    int notificationCount = 0;

    try {
        ObjectMapper mapper = new ObjectMapper();
        String extensionVersionsJson = mapper.writeValueAsString(extensionVersions);
        NameValuePair[] params = { new BasicNameValuePair("op", NOTIFICATION_COUNT_GET),
                new BasicNameValuePair("serverId", serverId), new BasicNameValuePair("version", mirthVersion),
                new BasicNameValuePair("extensionVersions", extensionVersionsJson) };
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT)
                .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();

        post.setURI(URI.create(URL_CONNECT_SERVER + URL_NOTIFICATION_SERVLET));
        post.setEntity(new UrlEncodedFormEntity(Arrays.asList(params), Charset.forName("UTF-8")));

        HttpClientContext postContext = HttpClientContext.create();
        postContext.setRequestConfig(requestConfig);
        client = getClient(protocols, cipherSuites);
        response = client.execute(post, postContext);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if ((statusCode == HttpStatus.SC_OK)) {
            HttpEntity responseEntity = response.getEntity();
            Charset responseCharset = null;
            try {
                responseCharset = ContentType.getOrDefault(responseEntity).getCharset();
            } catch (Exception e) {
                responseCharset = ContentType.TEXT_PLAIN.getCharset();
            }

            List<Integer> notificationIds = mapper.readValue(
                    IOUtils.toString(responseEntity.getContent(), responseCharset).trim(),
                    new TypeReference<List<Integer>>() {
                    });
            for (int id : notificationIds) {
                if (!archivedNotifications.contains(id)) {
                    notificationCount++;
                }
            }
        }
    } catch (Exception e) {
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(client);
    }
    return notificationCount;
}

From source file:com.hp.octane.integrations.services.rest.OctaneRestClientImpl.java

private OctaneResponse executeRequest(OctaneRequest request, OctaneConfiguration configuration)
        throws IOException {
    OctaneResponse result;//from   ww  w  .  j a v a2s  . co  m
    HttpClientContext context;
    HttpUriRequest uriRequest = null;
    HttpResponse httpResponse = null;
    OctaneResponse loginResponse;
    if (LWSSO_TOKEN == null) {
        logger.info("initial login");
        loginResponse = login(configuration);
        if (loginResponse.getStatus() != 200) {
            logger.error("failed on initial login, status " + loginResponse.getStatus());
            return loginResponse;
        }
    }

    try {
        //  we are running this loop either once or twice: once - regular flow, twice - when retrying after re-login attempt
        for (int i = 0; i < 2; i++) {
            uriRequest = createHttpRequest(request);
            context = createHttpContext(request.getUrl(), false);
            synchronized (REQUESTS_LIST_LOCK) {
                ongoingRequests.add(uriRequest);
            }
            httpResponse = httpClient.execute(uriRequest, context);
            synchronized (REQUESTS_LIST_LOCK) {
                ongoingRequests.remove(uriRequest);
            }

            if (AUTHENTICATION_ERROR_CODES.contains(httpResponse.getStatusLine().getStatusCode())) {
                logger.info("doing RE-LOGIN due to status " + httpResponse.getStatusLine().getStatusCode()
                        + " received while calling " + request.getUrl());
                EntityUtils.consumeQuietly(httpResponse.getEntity());
                HttpClientUtils.closeQuietly(httpResponse);
                loginResponse = login(configuration);
                if (loginResponse.getStatus() != 200) {
                    logger.error("failed to RE-LOGIN with status " + loginResponse.getStatus()
                            + ", won't attempt the original request anymore");
                    return loginResponse;
                } else {
                    logger.info("re-attempting the original request (" + request.getUrl()
                            + ") having successful RE-LOGIN");
                }
            } else {
                refreshSecurityToken(context, false);
                break;
            }
        }

        result = createNGAResponse(httpResponse);
    } catch (IOException ioe) {
        logger.debug("failed executing " + request, ioe);
        throw ioe;
    } finally {
        if (uriRequest != null && ongoingRequests.contains(uriRequest)) {
            synchronized (REQUESTS_LIST_LOCK) {
                ongoingRequests.remove(uriRequest);
            }
        }
        if (httpResponse != null) {
            EntityUtils.consumeQuietly(httpResponse.getEntity());
            HttpClientUtils.closeQuietly(httpResponse);
        }
    }

    return result;
}

From source file:mx.openpay.client.core.impl.DefaultHttpServiceClient.java

protected HttpServiceResponse executeOperation(final HttpRequestBase request)
        throws ServiceUnavailableException {
    this.addHeaders(request);
    this.addAuthentication(request);
    long init = System.currentTimeMillis();
    CloseableHttpResponse response = this.callService(request);
    HttpServiceResponse serviceResponse;
    try {/*  w ww  .java  2 s . c om*/
        serviceResponse = this.createResult(response);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
    log.trace("Request Time: {}", (System.currentTimeMillis() - init));
    return serviceResponse;
}