Example usage for org.apache.http.client.methods CloseableHttpResponse close

List of usage examples for org.apache.http.client.methods CloseableHttpResponse close

Introduction

In this page you can find the example usage for org.apache.http.client.methods CloseableHttpResponse 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:org.elasticsearch.river.solr.support.SolrIndexer.java

public void indexDocuments(Map<String, Map<String, Object>> documents) throws IOException {
    StringBuilder jsonBuilder = new StringBuilder("[");
    int i = 0;//from  w ww.  ja  v a 2s . com
    for (Map<String, Object> doc : documents.values()) {
        jsonBuilder.append(objectMapper.writeValueAsString(doc));

        if (i < documents.values().size() - 1) {
            jsonBuilder.append(",");
        }
        i++;
    }
    jsonBuilder.append("]");

    HttpPost httpPost = new HttpPost(solrUrl + "?commit=true");
    httpPost.setHeader("Content-type", "application/json");
    httpPost.setEntity(new StringEntity(jsonBuilder.toString()));

    CloseableHttpResponse response = httpClient.execute(httpPost);
    try {
        EntityUtils.consume(response.getEntity());
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("documents were not properly indexed");
        }
    } finally {
        EntityUtils.consume(response.getEntity());
        response.close();
    }
}

From source file:at.bitfire.davdroid.webdav.DavHttpClientTest.java

public void testCookies() throws IOException {
    CloseableHttpResponse response = null;

    HttpGetHC4 get = new HttpGetHC4(testCookieURI);
    get.setHeader("Accept", "text/xml");

    // at first, DavHttpClient doesn't send a cookie
    try {// w  w w .ja  va  2 s . c  o  m
        response = httpClient.execute(get);
        assertEquals(412, response.getStatusLine().getStatusCode());
    } finally {
        if (response != null)
            response.close();
    }

    // POST sets a cookie to DavHttpClient
    try {
        response = httpClient.execute(new HttpPostHC4(testCookieURI));
        assertEquals(200, response.getStatusLine().getStatusCode());
    } finally {
        if (response != null)
            response.close();
    }

    // and now DavHttpClient sends a cookie for GET, too
    try {
        response = httpClient.execute(get);
        assertEquals(200, response.getStatusLine().getStatusCode());
    } finally {
        if (response != null)
            response.close();
    }
}

From source file:org.wso2.carbon.ml.analysis.test.ModelConfigurationsTestCase.java

/**
 * Test adding default values to customized features an analysis.
 * //w  w  w .  j a v a 2 s. c  o  m
 * @throws MLHttpClientException 
 * @throws IOException
 */
@Test(priority = 1, description = "Add model configurations to the analysis")
public void testSetModelConfigurations() throws MLHttpClientException, IOException {
    Map<String, String> configurations = new HashMap<String, String>();
    configurations.put(MLConstants.ALGORITHM_NAME, ALGORITHM_NAME);
    configurations.put(MLConstants.ALGORITHM_TYPE, "Classification");
    configurations.put(MLConstants.RESPONSE_VARIABLE, "Class");
    configurations.put(MLConstants.TRAIN_DATA_FRACTION, "0.7");
    CloseableHttpResponse response = mlHttpclient.setModelConfiguration(analysisId, configurations);
    assertEquals("Unexpected response received", Response.Status.OK.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:com.srotya.sidewinder.cluster.storage.ClusteredMemStorageEngine.java

@Override
public void dropDatabase(String dbName) throws Exception {
    List<String> proxies = new ArrayList<>();
    dbName = decodeDbAndProxyNames(proxies, dbName);
    if (proxies.size() > 0) {
        local.dropDatabase(dbName);/* ww w .  j a va  2 s.c  o  m*/
    } else {
        local.dropDatabase(dbName);
        for (Entry<Integer, WorkerEntry> entry : columbus.getWorkerMap().entrySet()) {
            if (entry.getKey() != columbus.getSelfWorkerId()) {
                String newDbName = encodeDbAndProxyName(dbName, String.valueOf(columbus.getSelfWorkerId()));
                // http call
                CloseableHttpClient client = Utils.getClient(
                        "http://" + entry.getValue().getWorkerAddress().getHostAddress() + ":8080/", 5000,
                        5000);
                HttpDelete post = new HttpDelete("http://"
                        + entry.getValue().getWorkerAddress().getHostAddress() + ":8080/database/" + newDbName);
                CloseableHttpResponse result = client.execute(post);
                result.close();
                client.close();
            }
        }
    }
}

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 {/*from   www .  j a v a2 s .c  o m*/
        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.wso2.carbon.ml.analysis.test.ModelConfigurationsTestCase.java

/**
 * @throws MLHttpClientException/*from w  w  w. ja  v  a 2 s . c  o m*/
 * @throws NamingException
 * @throws IOException
 */
@Test(priority = 2, description = "Get response variable for malformed analysis id")
public void testGetResponseVariableForMalformedAnalysisId()
        throws MLHttpClientException, NamingException, IOException {
    CloseableHttpResponse response = mlHttpclient.doHttpGet("/api/analyses/abc/responseVariables");
    assertEquals("Unexpected response received", Response.Status.NOT_FOUND.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:org.wso2.carbon.ml.dataset.test.CreateDatasetTestCase.java

/**
 * Test creating a dataset without data source.
 * /*from   w w  w.  j a va2  s  . c  o  m*/
 * @throws MLHttpClientException
 * @throws IOException
 */
@Test(description = "Create a dataset without datasource")
public void testCreateDatasetWithoutDataSource() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient.uploadDatasetFromCSV("SampleDataForCreateDatasetTestCase_4",
            "1.0", null);
    assertEquals("Unexpected response received", Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:com.networknt.light.server.handler.loader.FormLoader.java

/**
 * Get all forms from the server and construct a map in order to compare content
 * to detect changes or not.//from  w w  w .  j  av a 2s  . c  o m
 *
 */
private static void getFormMap(String host) {

    Map<String, Object> inputMap = new HashMap<String, Object>();
    inputMap.put("category", "form");
    inputMap.put("name", "getFormMap");
    inputMap.put("readOnly", true);

    CloseableHttpResponse response = null;
    try {
        HttpPost httpPost = new HttpPost(host + "/api/rs");
        httpPost.addHeader("Authorization", "Bearer " + jwt);
        StringEntity input = new StringEntity(
                ServiceLocator.getInstance().getMapper().writeValueAsString(inputMap));
        input.setContentType("application/json");
        httpPost.setEntity(input);
        response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
        String json = "";
        String line = "";
        while ((line = rd.readLine()) != null) {
            json = json + line;
        }
        EntityUtils.consume(entity);
        System.out.println("Got form map from server");
        if (json != null && json.trim().length() > 0) {
            formMap = ServiceLocator.getInstance().getMapper().readValue(json,
                    new TypeReference<HashMap<String, Map<String, Object>>>() {
                    });
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:ext.deployit.onfailurehandler.OnReleaseFailureEventListener.java

private void invokeOnFailureHandler(Release release) throws IOException, URISyntaxException {
    String handlerEndpoint = getHandlerEndpoint();
    // sentinel object so OK to use ==
    if (handlerEndpoint == UNINITIALIZED) {
        logger.error("Global variable '{}' not found! Doing nothing", ENDPOINT_VARIABLE_NAME);
        return;/* w  ww . j av a  2 s .  co  m*/
    }

    URIBuilder requestUri = new URIBuilder().setScheme(ENDPOINT_SCHEME).setHost(ENDPOINT_HOST)
            .setPort(ENDPOINT_PORT).setPath(getHandlerEndpoint()).addParameter("releaseId", release.getId())
            .addParameter("onFailureUser", ENDPOINT_USER);
    HttpGet request = new HttpGet(requestUri.build());
    // without this, Apache HC will only send auth *after* a failure
    HttpClientContext authenticatingContext = HttpClientContext.create();
    authenticatingContext.setAuthCache(PREEMPTIVE_AUTH_CACHE);
    logger.debug("About to execute callback to {}", request);
    CloseableHttpResponse response = HTTP_CLIENT.execute(request, authenticatingContext);
    try {
        logger.info("Response line from request: {}", response.getStatusLine());
        logger.debug("Response body: {}", EntityUtils.toString(response.getEntity()));
    } finally {
        response.close();
    }
}

From source file:org.wso2.carbon.ml.dataset.test.CreateDatasetTestCase.java

/**
 * Test creating a dataset without name.
 * // w ww.ja v  a 2s  .  c  om
 * @throws MLHttpClientException
 * @throws IOException
 */
@Test(description = "Create a dataset without name")
public void testCreateDatasetWithoutName() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient.uploadDatasetFromCSV(null, "1.0",
            MLIntegrationTestConstants.DIABETES_DATASET_SAMPLE);
    assertEquals("Unexpected response received", Response.Status.BAD_REQUEST.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}