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.mirth.connect.connectors.ws.WebServiceDispatcher.java

@Override
public void onHalt() throws ConnectorTaskException {
    for (CloseableHttpClient client : clients.toArray(new CloseableHttpClient[clients.size()])) {
        HttpClientUtils.closeQuietly(client);
    }/*from w  ww. j  av  a2s  . com*/
    clients.clear();

    if (executor != null) {
        boolean shutdown = executor.isShutdown();
        executor.shutdownNow();

        // Only log an error out if this is the first time the executor was shutdown
        if (!shutdown) {
            try {
                // Wait a bit for tasks to finish and remove themselves from the set
                executor.awaitTermination(100, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                throw new ConnectorTaskException(
                        "Halt task interrupted while waiting for executor to shutdown.", e);
            }

            int numTasks = dispatchTasks.size();
            if (numTasks > 0) {
                String message = "Error halting Web Service Sender: " + numTasks + " request"
                        + (numTasks == 1 ? "" : "s")
                        + " failed to be halted. This can potentially lead to a thread leak if the requests continue to hang.";
                logger.error(message);
                eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), null,
                        ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                        connectorProperties.getName(), message, null));
            }
        }
    }

    for (DispatchContainer dispatchContainer : dispatchContainers.values()
            .toArray(new DispatchContainer[dispatchContainers.size()])) {
        for (File tempFile : dispatchContainer.getTempFiles()
                .toArray(new File[dispatchContainer.getTempFiles().size()])) {
            tempFile.delete();
        }
    }
    dispatchContainers.clear();
}

From source file:org.jboss.as.test.clustering.cluster.singleton.SingletonPartitionTestCase.java

private static void checkSingletonNode(URL baseURL, ServiceName serviceName, String expectedProviderNode)
        throws IOException, URISyntaxException {
    URI uri = (expectedProviderNode != null)
            ? NodeServiceServlet.createURI(baseURL, serviceName, expectedProviderNode)
            : NodeServiceServlet.createURI(baseURL, serviceName);
    try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
        HttpResponse response = client.execute(new HttpGet(uri));
        try {/*w  w w  . j  av a2 s .  c o m*/
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Header header = response.getFirstHeader("node");
            if (header != null) {
                Assert.assertEquals("Expected different provider node", expectedProviderNode,
                        header.getValue());
            } else {
                Assert.assertNull("Unexpected provider node", expectedProviderNode);
            }
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    }
}

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

@Override
public JSONObject getBdiConfiguration() {
    HttpGet request = new HttpGet(createSharedSpaceInternalApiUri(URI_BDI_CONFIGURATION));
    HttpResponse response = null;/*from   w w  w  .  ja  va 2  s .  c om*/
    try {
        response = execute(request);

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_NO_CONTENT) {
            logger.config("BDI is not configured in Octane");
            return null;
        }

        if (statusCode != HttpStatus.SC_OK) {
            throw createRequestException("BDI configuration retrieval failed", response);
        }

        String bdiConfiguration = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        return JSONObject.fromObject(bdiConfiguration);
    } catch (IOException e) {
        throw new RequestErrorException("Cannot obtain status.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

From source file:org.apache.vxquery.rest.ErrorResponseTest.java

private void runTest(URI uri, String accepts, int expectedStatusCode, String httpMethod) throws Exception {
    CloseableHttpClient httpClient = HttpClients.custom().setConnectionTimeToLive(20, TimeUnit.SECONDS).build();

    ErrorResponse errorResponse;//ww  w  . j a  v  a 2 s  .co  m
    try {
        HttpUriRequest request = getRequest(uri, httpMethod);
        if (accepts != null) {
            request.setHeader(HttpHeaders.ACCEPT, accepts);
        }

        try (CloseableHttpResponse httpResponse = httpClient.execute(request)) {
            Assert.assertEquals(expectedStatusCode, httpResponse.getStatusLine().getStatusCode());
            if (accepts != null) {
                Assert.assertEquals(accepts, httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
            }

            HttpEntity entity = httpResponse.getEntity();
            Assert.assertNotNull(entity);

            String response = RestUtils.readEntity(entity);
            errorResponse = RestUtils.mapEntity(response, ErrorResponse.class, accepts);
        }
    } finally {
        HttpClientUtils.closeQuietly(httpClient);
    }

    Assert.assertNotNull(errorResponse);
    Assert.assertNotNull(errorResponse.getError().getMessage());
    Assert.assertEquals(errorResponse.getError().getCode(), expectedStatusCode);
}

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

private void revert(TravelPlan travelPlan) throws Exception {
    // do independently
    if (travelPlan.getHotelBookingId() != null) {
        URI uri = new URIBuilder().setScheme("http").setHost("travel.gsp8181.co.uk")
                .setPath("/rest/bookings/" + travelPlan.getHotelBookingId())
                // .setHost("localhost")
                // .setPort(8080)
                // .setPath("/travel/rest/bookings/" +
                // travelPlan.getHotelBookingId())
                .build();/*from  w  w  w.j ava  2s.c  o m*/
        HttpDelete req = new HttpDelete(uri);
        CloseableHttpResponse response = httpClient.execute(req);
        if (response.getStatusLine().getStatusCode() != 204) {

        }
        // String responseBody = EntityUtils.toString(response.getEntity());
        HttpClientUtils.closeQuietly(response);
    }

    if (travelPlan.getFlightBookingId() != null) {
        URI uri = new URIBuilder().setScheme("http").setHost("jbosscontactsangularjs-110336260.rhcloud.com")
                .setPath("/rest/bookings/" + travelPlan.getFlightBookingId()).build();
        HttpDelete req = new HttpDelete(uri);
        CloseableHttpResponse response = httpClient.execute(req);
        if (response.getStatusLine().getStatusCode() != 204) {

        }
        // String responseBody = EntityUtils.toString(response.getEntity());
        HttpClientUtils.closeQuietly(response);
    }
    if (travelPlan.getTaxiBookingId() != null) {
        URI uri = new URIBuilder().setScheme("http").setHost("jbosscontactsangularjs-110060653.rhcloud.com")
                .setPath("/rest/bookings/" + travelPlan.getTaxiBookingId()).build();
        HttpDelete req = new HttpDelete(uri);
        CloseableHttpResponse response = httpClient.execute(req);
        if (response.getStatusLine().getStatusCode() != 204) {

        }
        // String responseBody = EntityUtils.toString(response.getEntity());
        HttpClientUtils.closeQuietly(response);
    }
}

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

/**
 * Allows one request at a time.//from ww w  . j av a 2 s  . c  o  m
 */
private synchronized ClientResponse executeSync(ClientRequest request, Operation operation)
        throws ClientException {
    synchronized (currentOp) {
        currentOp.setName(operation.getName());
        currentOp.setDisplayName(operation.getDisplayName());
        currentOp.setAuditable(operation.isAuditable());
    }

    HttpRequestBase requestBase = null;
    CloseableHttpResponse response = null;
    boolean shouldClose = true;

    try {
        requestBase = setupRequestBase(request, ExecuteType.SYNC);
        response = client.execute(requestBase);
        ClientResponse responseContext = handleResponse(request, requestBase, response, true);
        if (responseContext.hasEntity()) {
            shouldClose = false;
        }
        return responseContext;
    } catch (Exception e) {
        if (requestBase != null && requestBase.isAborted()) {
            throw new RequestAbortedException(e);
        } else if (e instanceof ClientException) {
            throw (ClientException) e;
        }
        throw new ClientException(e);
    } finally {
        if (shouldClose) {
            HttpClientUtils.closeQuietly(response);

            synchronized (currentOp) {
                currentOp.setName(null);
                currentOp.setDisplayName(null);
                currentOp.setAuditable(false);
            }
        }
    }
}

From source file:org.jboss.as.test.clustering.cluster.singleton.SingletonPartitionTestCase.java

private static void partition(boolean partition, URL... baseURIs) {
    Arrays.stream(baseURIs).parallel().forEach(baseURI -> {
        try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
            HttpResponse response = client.execute(new HttpGet(PartitionServlet.createURI(baseURI, partition)));
            try {
                Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            } finally {
                HttpClientUtils.closeQuietly(response);
            }/*from w  w  w .  j  ava 2 s.co  m*/
        } catch (Exception ignored) {
        }
    });
}

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

@Override
public String getBdiTokenData() {
    HttpGet request = new HttpGet(createSharedSpaceInternalApiUri(URI_BDI_ACCESS_TOKEN));
    HttpResponse response = null;//from www .  java2 s .  c  o m
    try {
        response = execute(request);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        } else {
            throw createRequestException("BDI token retrieval failed", response);
        }
    } catch (IOException e) {
        throw new RequestErrorException("failed to parse token data response", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

From source file:org.wso2.appcloud.integration.test.utils.clients.BaseClient.java

public HttpResponse doPostRequest(String endpoint, List<NameValuePair> nameValuePairs)
        throws AppCloudIntegrationTestException {
    HttpClient httpclient = null;//from  w  ww. j  a  v a  2 s  . co  m
    int timeout = (int) AppCloudIntegrationTestUtils.getTimeOutPeriod();
    try {
        httpclient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).build();
        HttpPost httppost = new HttpPost(endpoint);
        httppost.setConfig(requestConfig);

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        httppost.setHeader(HEADER_COOKIE, getRequestHeaders().get(HEADER_COOKIE));
        org.apache.http.HttpResponse httpResponse = (httpclient.execute(httppost));
        return new HttpResponse(EntityUtils.toString(httpResponse.getEntity(), "UTF-8").replaceAll("\\s+", ""),
                httpResponse.getStatusLine().getStatusCode());
    } catch (ConnectTimeoutException | java.net.SocketTimeoutException e1) {
        // In most of the cases, even though connection is timed out, actual activity is completed.
        log.warn("Failed to get 200 ok response from endpoint:" + endpoint, e1);
        return new HttpResponse(e1.getMessage(), HttpStatus.SC_REQUEST_TIMEOUT);
    } catch (IOException e) {
        log.error("Failed to invoke API endpoint:" + endpoint, e);
        throw new AppCloudIntegrationTestException("Failed to invoke API endpoint:" + endpoint, e);
    } finally {
        HttpClientUtils.closeQuietly(httpclient);
    }
}