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:br.com.autonomiccs.apacheCloudStack.client.ApacheCloudStackClient.java

/**
 * This method executes the given {@link ApacheCloudStackRequest}.
 * It will return the response as a plain {@link String}.
 * You should have in mind that if the parameter 'response' is not set, the default is 'XML'.
 *//*from   w  w w .j  av a  2  s .  c  om*/
public String executeRequest(ApacheCloudStackRequest request) {
    boolean isSecretKeyApiKeyAuthenticationMechanism = StringUtils
            .isNotBlank(this.apacheCloudStackUser.getApiKey());
    String urlRequest = createApacheCloudStackApiUrlRequest(request, isSecretKeyApiKeyAuthenticationMechanism);
    logger.debug("Executing request[%s].", urlRequest);
    CloseableHttpClient httpClient = createHttpClient();
    HttpContext httpContext = createHttpContextWithAuthenticatedSessionUsingUserCredentialsIfNeeded(httpClient,
            isSecretKeyApiKeyAuthenticationMechanism);
    try {
        return executeRequestGetResponseAsString(urlRequest, httpClient, httpContext);
    } finally {
        if (!isSecretKeyApiKeyAuthenticationMechanism) {
            executeUserLogout(httpClient, httpContext);
        }
        HttpClientUtils.closeQuietly(httpClient);
    }
}

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

private long bookHotel(TravelSketch travelSketch) throws Exception {
    URI uri = new URIBuilder().setScheme("http").setHost("travel.gsp8181.co.uk").setPath("/rest/bookings")
            // .setHost("localhost")
            // .setPort(8080)
            // .setPath("/travel/rest/bookings")
            .build();//ww w .  j  av  a  2 s .c o  m
    HttpPost req = new HttpPost(uri);
    StringEntity params = new StringEntity("{\"customer\":{\"id\":\"" + travelAgentFlight.toString()
            + "\"},\"hotel\":{\"id\":\"" + travelSketch.getHotelId().toString() + "\"},\"bookingDate\":\""
            + travelSketch.getBookingDate() + "\"}");
    req.addHeader("Content-Type", "application/json");
    req.setEntity(params);
    CloseableHttpResponse response = httpClient.execute(req);
    if (response.getStatusLine().getStatusCode() != 201) {
        throw new Exception("Failed to create a hotel 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:com.mirth.connect.client.core.ServerConnection.java

public void shutdown() {
    // Shutdown the abort thread
    abortExecutor.shutdownNow();

    HttpClientUtils.closeQuietly(client);
}

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

public TestResultPushStatus getTestResultStatus(long id) {
    HttpGet request = new HttpGet(createWorkspaceApiUri(URI_TEST_RESULT_STATUS, id));
    CloseableHttpResponse response = null;
    try {/*  w  w w. j  av a  2 s. com*/
        response = execute(request);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new RuntimeException("Result status retrieval failed");
        }
        String json = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        JSONObject jsonObject = new JSONObject(json);
        Date until = null;
        if (jsonObject.has("until")) {
            try {
                until = parseDatetime(jsonObject.getString("until"));
            } catch (ParseException e) {
                throw new RuntimeException("Cannot obtain status", e);
            }
        }
        return new TestResultPushStatus(jsonObject.getString("status"), until);
    } catch (IOException e) {
        throw new RuntimeException("Cannot obtain status.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

From source file:org.jboss.quickstarts.wfk.travelplan.TravelPlanTest.java

@Test
@InSequence(1)/*  w w  w  . j  ava  2  s .  com*/
public void TestBooking() throws Exception {
    TravelSketch ts1 = new TravelSketch();
    ts1.setFlightId(10001L);
    ts1.setHotelId(1099L);
    ts1.setTaxiId(101L);
    ts1.setBookingDate("2018-03-29");
    ts1.setCustomerId(createTestCustomer());

    Response response = travelPlanRESTService.createTravelPlan(ts1);

    assertEquals("Unexpected response", 201, response.getStatus());

    long flightId = 0;
    long hotelId = 0;
    long taxiId = 0;

    Response r1 = travelPlanRESTService.retrieveAllTravelPlans();
    String responseBody = EntityUtils.toString((HttpEntity) r1.getEntity());
    JSONArray responseJSON = new JSONArray(responseBody);
    for (int i = 0; i < responseJSON.length(); i++) {
        JSONObject jo = responseJSON.getJSONObject(i);
        if (jo.getJSONObject("customer").getLong("id") == createTestCustomer()) {
            flightId = jo.getLong("flightBookingId");
            hotelId = jo.getLong("hotelBookingId");
            taxiId = jo.getLong("taxiBookingId");
        }
    }
    assertNotEquals("Flight did not book", 0L, flightId);
    assertNotEquals("Taxi did not book", 0L, taxiId);
    assertNotEquals("Hotel did not book", 0L, hotelId);

    URI uri = new URIBuilder().setScheme("http").setHost("travel.gsp8181.co.uk")
            .setPath("/rest/bookings/" + hotelId).build();
    HttpGet req = new HttpGet(uri);
    CloseableHttpResponse response2 = httpClient.execute(req);
    assertEquals("Hotel did not book", 200, response2.getStatusLine().getStatusCode());

    HttpClientUtils.closeQuietly(response2);

    URI uri1 = new URIBuilder().setScheme("http").setHost("jbosscontactsangularjs-110336260.rhcloud.com")
            .setPath("/rest/bookings/" + flightId).build();
    HttpGet req1 = new HttpGet(uri1);
    CloseableHttpResponse response3 = httpClient.execute(req1);
    assertEquals("Flight did not book", 200, response3.getStatusLine().getStatusCode());
    HttpClientUtils.closeQuietly(response3);

    URI uri2 = new URIBuilder().setScheme("http").setHost("jbosscontactsangularjs-110060653.rhcloud.com")
            .setPath("/rest/bookings/" + taxiId).build();
    HttpGet req2 = new HttpGet(uri2);
    CloseableHttpResponse response4 = httpClient.execute(req2);
    assertEquals("Taxi did not book", 200, response4.getStatusLine().getStatusCode());
    HttpClientUtils.closeQuietly(response4);

}

From source file:com.mirth.connect.connectors.http.HttpDispatcher.java

@Override
public void onStop() throws ConnectorTaskException {
    for (CloseableHttpClient client : clients.values().toArray(new CloseableHttpClient[clients.size()])) {
        HttpClientUtils.closeQuietly(client);
    }/*w ww  .  j  a v  a  2s .  c  om*/

    clients.clear();
}

From source file:com.mirth.connect.connectors.ws.WebServiceDispatcher.java

@Override
public void onStop() throws ConnectorTaskException {
    for (CloseableHttpClient client : clients.toArray(new CloseableHttpClient[clients.size()])) {
        HttpClientUtils.closeQuietly(client);
    }//from   w w w .ja  v  a 2 s. co m
    clients.clear();

    if (executor != null) {
        executor.shutdown();
    }

    for (DispatchContainer dispatchContainer : dispatchContainers.values()) {
        for (File tempFile : dispatchContainer.getTempFiles()) {
            tempFile.delete();
        }
    }
    dispatchContainers.clear();
}

From source file:org.jboss.as.test.clustering.cluster.ejb3.stateful.StatefulFailoverTestCase.java

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

From source file:com.mirth.connect.connectors.http.HttpDispatcher.java

@Override
public void onHalt() throws ConnectorTaskException {
    for (CloseableHttpClient client : clients.values().toArray(new CloseableHttpClient[clients.size()])) {
        HttpClientUtils.closeQuietly(client);
    }//www.  j a  v a  2s.  c  o m

    clients.clear();
}

From source file:fi.laverca.util.CommonsHTTPSender.java

/**
 * invoke creates a socket connection, sends the request SOAP message and then
 * reads the response SOAP message back from the SOAP server
 *
 * @param msgContext the messsage context
 *
 * @throws AxisFault if there was an error sending the SOAP message
 *///from  w w w  . j  a va2s. com
@Override
public void invoke(final MessageContext msgContext) throws AxisFault {

    HttpPost post = null;
    HttpResponse response = null;
    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke"));
    }
    try {

        HttpClient httpClient = settings.get();

        URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));

        Message reqMessage = msgContext.getRequestMessage();
        post = new HttpPost(targetURL.toString());

        // set false as default, addContentInfo can overwrite
        HttpParams params = post.getParams();
        HttpProtocolParams.setUseExpectContinue(params, false);

        addContextInfo(post, httpClient, msgContext, targetURL);

        MessageRequestEntity requestEntity = null;
        if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
            requestEntity = new GzipMessageRequestEntity(post, reqMessage, httpChunkStream);
        } else {
            requestEntity = new MessageRequestEntity(post, reqMessage, httpChunkStream);
        }
        post.setEntity(requestEntity);

        String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
        if (httpVersion != null) {
            if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) {
                params.setParameter(httpVersion, HttpVersion.HTTP_1_0);
            }
        }

        HttpContext localContext = new BasicHttpContext();

        if (httpClient == null) {
            // We might end up here if initThreadLocals() was not properly called
            log.fatal("Initialization failed: No HTTPClient");
            throw new AxisFault("Initialization failed: No HTTPClient");
        }

        response = httpClient.execute(post, localContext);
        int returnCode = response.getStatusLine().getStatusCode();

        String contentType = getHeader(post, HTTPConstants.HEADER_CONTENT_TYPE);
        String contentLocation = getHeader(post, HTTPConstants.HEADER_CONTENT_LOCATION);
        String contentLength = getHeader(post, HTTPConstants.HEADER_CONTENT_LENGTH);

        if ((returnCode > 199) && (returnCode < 300)) {

            // SOAP return is OK - so fall through
        } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            // For now, if we're SOAP 1.2, fall through, since the range of
            // valid result codes is much greater
        } else if ((contentType != null) && !contentType.equals("text/html")
                && ((returnCode > 499) && (returnCode < 600))) {
            // SOAP Fault should be in here - so fall through

        } else {
            String statusMessage = response.getStatusLine().getReasonPhrase();
            AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null);

            try {
                String body = getResponseBodyAsString(response);
                fault.setFaultDetailString(Messages.getMessage("return01", "" + returnCode, body));
                fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode));
                throw fault;
            } finally {
                HttpClientUtils.closeQuietly(response);
                post.releaseConnection();
            }
        }

        // After this phase, the response and post are NOT to be closed/released
        // in this code path! See comments further below at "AXIS closure processing rules"

        // Wrap the response body stream so that close() also releases
        // the connection back to the pool.
        InputStream releaseConnectionOnCloseStream = createConnectionReleasingInputStream(post, response);

        Header contentEncoding = response.getFirstHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
        if (contentEncoding != null) {
            if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) {
                releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream);
            } else {
                try {
                    releaseConnectionOnCloseStream.close();
                } catch (Throwable t) {
                    // ignore
                }
                throw new AxisFault("HTTP",
                        "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null,
                        null);
            }
        }
        Message outMsg = new Message(releaseConnectionOnCloseStream, false, contentType, contentLocation);
        // Transfer HTTP headers of HTTP message to MIME headers of SOAP message
        Header[] responseHeaders = post.getAllHeaders();
        MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders();
        for (int i = 0; i < responseHeaders.length; i++) {
            Header responseHeader = responseHeaders[i];
            responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue());
        }
        outMsg.setMessageType(Message.RESPONSE);
        msgContext.setResponseMessage(outMsg);
        if (log.isDebugEnabled()) {
            if (null == contentLength) {
                log.debug("\n" + Messages.getMessage("no00", "Content-Length"));
            }
            log.debug("\n" + Messages.getMessage("xmlRecd00"));
            log.debug("-----------------------------------------------");
            log.debug(outMsg.getSOAPPartAsString());
        }

    } catch (Exception e) {
        log.debug(e);
        throw AxisFault.makeFault(e);

    } finally {

        // AXIS closure processing rules..
        //
        // 1: Always release the connection back to the pool
        //    IF it was ONE WAY invocation

        if (msgContext.isPropertyTrue("axis.one.way")) {
            HttpClientUtils.closeQuietly(response);
            if (post != null) {
                post.releaseConnection();
            }
        } else {
            log.debug("A HTTP POST which did NOT plan to release the HTTP connection back to the pool");
        }

        // 2: Otherwise the Axis machinery will process call
        //    close() on the releaseConnectionOnCloseStream.
    }

    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke"));
    }
}