Example usage for org.apache.http.impl.client CloseableHttpClient close

List of usage examples for org.apache.http.impl.client CloseableHttpClient close

Introduction

In this page you can find the example usage for org.apache.http.impl.client CloseableHttpClient close.

Prototype

public void close() throws IOException;

Source Link

Document

Closes this stream and releases any system resources associated with it.

Usage

From source file:net.officefloor.plugin.servlet.webxml.AbstractWebXmlTestCase.java

@Override
protected void tearDown() throws Exception {

    // Stop the HTTP clients
    for (CloseableHttpClient client : this.clients) {
        client.close();
    }/*  w w  w.  ja va  2s . c  o m*/

    // Stop servlet application (if started)
    if (this.officeFloor != null) {
        this.stopServletApplication();
    }
}

From source file:org.palo.it.devoxx.raspberry.rest.Sender.java

private int sendPost(final HttpPost httppost) throws UnsupportedEncodingException, IOException {
    final CloseableHttpClient httpclient = HttpClients.createDefault();

    int resultCode = 500;

    CloseableHttpResponse response = null;
    try {//w w w  .  j a  v  a  2 s .c om
        response = httpclient.execute(httppost);
        resultCode = response.getStatusLine().getStatusCode();
    } catch (final IOException e) {
        LOGGER.error(e.getMessage(), e);
    } finally {
        if (response != null) {
            response.close();
        }
    }
    httpclient.close();
    return resultCode;
}

From source file:org.docx4j.services.client.ConverterHttp.java

/**
 * Convert byte array fromFormat to toFormat, streaming result to OutputStream os.
 * //from   w w w .  j a  v a2  s .  com
 * fromFormat supported: DOC, DOCX
 * 
 * toFormat supported: PDF
 * 
 * @param bytesIn
 * @param fromFormat
 * @param toFormat
 * @param os
 * @throws IOException
 * @throws ConversionException
 */
public void convert(byte[] bytesIn, Format fromFormat, Format toFormat, OutputStream os)
        throws IOException, ConversionException {

    checkParameters(fromFormat, toFormat);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = getUrlForFormat(toFormat);

        HttpEntity reqEntity = new ByteArrayEntity(bytesIn, map(fromFormat)); // messy that API is different to FileEntity

        httppost.setEntity(reqEntity);

        execute(httpclient, httppost, os);

    } finally {
        httpclient.close();
    }

}

From source file:com.ibm.mil.readyapps.telco.adapters.CloudantGeoAdapterResource.java

@GET
@Produces(MediaType.APPLICATION_JSON)/*from   w  w  w  .  j ava  2s .  c o m*/
@Path("/{user_id}/wifi")
public Response getWifiLocations(@PathParam("user_id") String name, @QueryParam(value = "lat") double latitude,
        @QueryParam(value = "lon") double longitude) {

    GeoJsonPoint userLocation = new GeoJsonPoint(latitude, longitude);

    try {
        HttpGet httpget = new HttpGet(GeoRadiusURI.build(DEMO_LOCATION));

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpResponse httpResponse = httpClient.execute(httpget);

        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.OK.getCode()) {
            String jsonString = EntityUtils.toString(httpResponse.getEntity());

            List<WifiHotspotFlat> hotspots = WifiHotspotUtils.parseAndOffsetHotspots(jsonString, userLocation);

            return Response.ok(new Gson().toJson(hotspots), MediaType.APPLICATION_JSON).build();
        }

        httpClient.close();
        return Response.serverError().entity(httpResponse.getStatusLine()).build();
    } catch (URISyntaxException | ParseException | IOException e) {
        e.printStackTrace();
        return Response.serverError().entity("Error").build();

    }
}

From source file:org.apache.solr.prometheus.exporter.SolrExporterTest.java

@Test
public void testExecute() throws Exception {
    // solr client
    CloudSolrClient cloudSolrClient = cluster.getSolrClient();

    int port;//from ww w  .ja va  2s.  c  o  m
    ServerSocket socket = null;
    try {
        socket = new ServerSocket(0);
        port = socket.getLocalPort();
    } finally {
        socket.close();
    }

    // index sample docs
    File exampleDocsDir = new File(getFile("exampledocs").getAbsolutePath());
    List<File> xmlFiles = Arrays.asList(exampleDocsDir.listFiles((dir, name) -> name.endsWith(".xml")));
    for (File xml : xmlFiles) {
        ContentStreamUpdateRequest req = new ContentStreamUpdateRequest("/update");
        req.addFile(xml, "application/xml");
        cloudSolrClient.request(req, "collection1");
    }
    cloudSolrClient.commit("collection1");

    // start exporter
    SolrExporter solrExporter = new SolrExporter(port, cloudSolrClient,
            getFile("conf/solr-exporter-config.xml").toPath(), 1);
    try {
        solrExporter.start();

        URI uri = new URI("http://localhost:" + String.valueOf(port) + "/metrics");

        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            HttpGet request = new HttpGet(uri);
            response = httpclient.execute(request);

            int expectedHTTPStatusCode = HttpStatus.SC_OK;
            int actualHTTPStatusCode = response.getStatusLine().getStatusCode();
            assertEquals(expectedHTTPStatusCode, actualHTTPStatusCode);
        } finally {
            response.close();
            httpclient.close();
        }
    } finally {
        solrExporter.stop();
    }
}

From source file:org.artifactory.util.HttpClientConfiguratorTest.java

public void testHost() throws IOException {
    CloseableHttpClient client = new HttpClientConfigurator().host("bob").getClient();
    DefaultRoutePlanner routePlanner = getRoutePlanner(client);
    assertThat(routePlanner).isInstanceOf(HttpClientConfigurator.DefaultHostRoutePlanner.class);
    assertEquals(((HttpClientConfigurator.DefaultHostRoutePlanner) routePlanner).getDefaultHost().getHostName(),
            "bob", "Unexpected host.");
    client.close();
}

From source file:org.docx4j.services.client.ConverterHttp.java

/**
 * Convert File fromFormat to toFormat, streaming result to OutputStream os.
 * /*from www . j av  a  2 s .  c om*/
 * fromFormat supported: DOC, DOCX
 * 
 * toFormat supported: PDF
 * 
 * @param f
 * @param fromFormat
 * @param toFormat
 * @param os
 * @throws IOException
 * @throws ConversionException
 */
public void convert(File f, Format fromFormat, Format toFormat, OutputStream os)
        throws IOException, ConversionException {

    checkParameters(fromFormat, toFormat);

    //        CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpClient httpclient = HttpClients.custom().setRetryHandler(new MyRetryHandler()).build();

    try {
        HttpPost httppost = getUrlForFormat(toFormat);

        HttpEntity reqEntity = new FileEntity(f, map(fromFormat));

        httppost.setEntity(reqEntity);

        execute(httpclient, httppost, os);
        log.debug("..done");
    } finally {
        httpclient.close();
    }

}

From source file:org.hawkular.alerter.prometheus.PrometheusQueryTest.java

@Ignore
@Test//  www .j  a v a 2s  .  c o m
public void queryEncodedUrl() throws Exception {
    CloseableHttpClient client = HttpClients.createDefault();

    StringBuffer url = new StringBuffer("http://localhost:9090");
    url.append("/api/v1/query?");
    BasicNameValuePair param = new BasicNameValuePair("query",
            "rate(http_requests_total{handler=\"query\",job=\"prometheus\"}[5m])>0");
    url.append(URLEncodedUtils.format(Arrays.asList(param), "UTF-8"));
    HttpGet getRequest = new HttpGet(url.toString());
    HttpResponse response = client.execute(getRequest);
    assertEquals(200, response.getStatusLine().getStatusCode());
    client.close();
}