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:fr.treeptik.cloudunit.cli.rest.RestUtils.java

/**
 * sendPostCommand// www. ja v a 2s.  c  om
 *
 * @param url
 * @param parameters
 * @return
 * @throws ClientProtocolException
 */
public Map<String, Object> sendPostCommand(String url, Map<String, Object> credentials,
        Map<String, String> parameters) throws ManagerResponseException {
    Map<String, Object> response = new HashMap<String, Object>();
    CloseableHttpClient httpclient = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost(url);
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");
    try {
        ObjectMapper mapper = new ObjectMapper();
        StringEntity entity = new StringEntity(mapper.writeValueAsString(parameters));
        httpPost.setEntity(entity);
        CloseableHttpResponse httpResponse = httpclient.execute(httpPost, localContext);
        ResponseHandler<String> handler = new CustomResponseErrorHandler();
        String body = handler.handleResponse(httpResponse);
        response.put("body", body);
        httpResponse.close();
    } catch (Exception e) {
        throw new ManagerResponseException(e.getMessage(), e);
    }

    return response;
}

From source file:fr.treeptik.cloudunit.cli.rest.RestUtils.java

/**
 * sendPutCommand// w  w w. ja v a  2  s  . com
 *
 * @param url
 * @param parameters
 * @return
 * @throws ClientProtocolException
 */
public Map<String, Object> sendPutCommand(String url, Map<String, Object> credentials,
        Map<String, String> parameters) throws ManagerResponseException {
    Map<String, Object> response = new HashMap<String, Object>();
    CloseableHttpClient httpclient = HttpClients.createDefault();

    HttpPut httpPut = new HttpPut(url);
    httpPut.setHeader("Accept", "application/json");
    httpPut.setHeader("Content-type", "application/json");

    try {
        ObjectMapper mapper = new ObjectMapper();
        StringEntity entity = new StringEntity(mapper.writeValueAsString(parameters));
        httpPut.setEntity(entity);
        CloseableHttpResponse httpResponse = httpclient.execute(httpPut, localContext);
        ResponseHandler<String> handler = new CustomResponseErrorHandler();
        String body = handler.handleResponse(httpResponse);
        response.put("body", body);
        httpResponse.close();
    } catch (Exception e) {
        throw new ManagerResponseException(e.getMessage(), e);
    }

    return response;
}

From source file:fr.treeptik.cloudunit.cli.rest.RestUtils.java

public Map<String, String> connect(String url, Map<String, Object> parameters) throws ManagerResponseException {

    Map<String, String> response = new HashMap<String, String>();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    List<NameValuePair> nvps = new ArrayList<>();
    nvps.add(new BasicNameValuePair("j_username", (String) parameters.get("login")));
    nvps.add(new BasicNameValuePair("j_password", (String) parameters.get("password")));
    localContext = HttpClientContext.create();
    localContext.setCookieStore(new BasicCookieStore());
    HttpPost httpPost = new HttpPost(url);

    try {/* w  w w  .  j a v  a  2s.  c o  m*/
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        CloseableHttpResponse httpResponse = httpclient.execute(httpPost, localContext);
        ResponseHandler<String> handler = new CustomResponseErrorHandler();
        String body = handler.handleResponse(httpResponse);
        response.put("body", body);
        httpResponse.close();
    } catch (Exception e) {
        authentificationUtils.getMap().clear();
        throw new ManagerResponseException(e.getMessage(), e);
    }

    return response;
}

From source file:co.cask.cdap.client.rest.RestStreamClient.java

@Override
public void setTTL(String stream, long ttl) throws IOException {
    HttpPut putRequest = new HttpPut(restClient.getBaseURL()
            .resolve(String.format("/%s/streams/%s/config", restClient.getVersion(), stream)));
    StringEntity entity = new StringEntity(GSON.toJson(ImmutableMap.of(TTL_ATTRIBUTE_NAME, ttl)));
    entity.setContentType(MediaType.APPLICATION_JSON);
    putRequest.setEntity(entity);//  w  w w.  j a v  a  2  s .  c  om
    CloseableHttpResponse httpResponse = restClient.execute(putRequest);
    try {
        int responseCode = httpResponse.getStatusLine().getStatusCode();
        LOG.debug("Set TTL Response Code : {}", responseCode);
        RestClient.responseCodeAnalysis(httpResponse);
    } finally {
        httpResponse.close();
    }
}

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

/**
 * Test retrieving all the available data-sets
 * @throws MLHttpClientException /*from w  ww . j  ava 2 s  . c om*/
 * @throws IOException 
 */
@Test(description = "Get all available datasets")
public void testGetAllDatasets() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient.doHttpGet("/api/datasets");
    Assert.assertEquals("Unexpected response received", Response.Status.OK.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:org.wso2.carbon.ml.project.test.MLProjectsTestCase.java

/**
 * Test creating a project./*  w  w  w .jav a 2  s  . c om*/
 * 
 * @throws MLHttpClientException
 * @throws IOException
 */
@Test(priority = 1, description = "Create a project")
public void testCreateProject() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient.createProject(
            MLIntegrationTestConstants.PROJECT_NAME_DIABETES, MLIntegrationTestConstants.DATASET_NAME_DIABETES);
    assertEquals("Unexpected response received", Response.Status.OK.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:sms.SendRequest.java

/**
 * //  w  ww .j  a v a2 s  .c om
 * @param moId
 * @param sender
 * @param serviceId
 * @param receiver
 * @param contentType
 * @param messageType
 * @param username
 * @param messageIndex
 * @param message
 * @param operator
 * @param commandCode
 * @return
 * @throws URISyntaxException
 * @throws IOException 
 */
public String sendRequests(String moId, String sender, String serviceId, String message, String operator,
        String commandCode, String username) throws URISyntaxException, IOException {
    Date d = new Date();
    SimpleDateFormat fm = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
    URI uri = new URIBuilder().setScheme("http").setHost("222.255.167.6:8080").setPath("/SMS/Ctnet/sms")
            .setParameter("mo_id", moId).setParameter("username", username)
            .setParameter("key", Common.getMD5(username + "|" + moId + "|ctnet2015"))
            .setParameter("sender", sender).setParameter("serviceId", serviceId)
            .setParameter("message", message).setParameter("operator", operator)
            .setParameter("commandCode", commandCode).build();
    HttpGet httpPost = new HttpGet(uri);
    httpPost.addHeader("content-type", "application/x-www-form-urlencoded");
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response = httpclient.execute(httpPost);

    try {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            long len = entity.getContentLength();
            if (len != -1 && len < 2048) {
                return EntityUtils.toString(entity);
            } else {
                // Stream content out
            }
        }
    } finally {
        response.close();
    }
    return "";
}

From source file:co.cask.cdap.client.rest.RestStreamClient.java

@Override
public void truncate(String stream) throws IOException {
    HttpPost postRequest = new HttpPost(restClient.getBaseURL()
            .resolve(String.format("/%s/streams/%s/truncate", restClient.getVersion(), stream)));
    CloseableHttpResponse httpResponse = restClient.execute(postRequest);
    try {//from w w w.ja  v a  2s.  com
        int responseCode = httpResponse.getStatusLine().getStatusCode();
        LOG.debug("Truncate stream Response Code : {}", responseCode);
        RestClient.responseCodeAnalysis(httpResponse);
    } finally {
        httpResponse.close();
    }
}

From source file:org.apache.hadoop.gateway.GatewaySslFuncTest.java

@Test(timeout = TestUtils.MEDIUM_TIMEOUT)
public void testKnox674SslCipherSuiteConfig() throws Exception {
    LOG_ENTER();//from w  w w. j a v a  2 s  . co  m

    String topoStr = TestUtils.merge(DAT, "test-admin-topology.xml", params);
    File topoFile = new File(config.getGatewayTopologyDir(), "test-topology.xml");
    FileUtils.writeStringToFile(topoFile, topoStr);

    topos.reloadTopologies();

    String username = "guest";
    String password = "guest-password";
    String serviceUrl = gatewayUrl + "/test-topology/api/v1/version";

    HttpHost targetHost = new HttpHost("localhost", gatewayPort, gatewayScheme);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);

    CloseableHttpClient client = HttpClients.custom()
            .setSSLSocketFactory(
                    new SSLConnectionSocketFactory(createInsecureSslContext(), new String[] { "TLSv1.2" },
                            new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" }, new TrustAllHosts()))
            .build();
    HttpGet request = new HttpGet(serviceUrl);
    CloseableHttpResponse response = client.execute(request, context);
    assertThat(the(new StreamSource(response.getEntity().getContent())), hasXPath("/ServerVersion/version"));
    response.close();
    client.close();

    gateway.stop();
    config.setExcludedSSLCiphers(Arrays.asList(new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" }));
    config.setIncludedSSLCiphers(Arrays.asList(new String[] { "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" }));

    startGatewayServer();
    serviceUrl = gatewayUrl + "/test-topology/api/v1/version";

    try {
        client = HttpClients.custom()
                .setSSLSocketFactory(
                        new SSLConnectionSocketFactory(createInsecureSslContext(), new String[] { "TLSv1.2" },
                                new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" }, new TrustAllHosts()))
                .build();
        request = new HttpGet(serviceUrl);
        client.execute(request, context);
        fail("Expected SSLHandshakeException");
    } catch (SSLHandshakeException e) {
        // Expected.
        client.close();
    }

    client = HttpClients.custom()
            .setSSLSocketFactory(
                    new SSLConnectionSocketFactory(createInsecureSslContext(), new String[] { "TLSv1.2" },
                            new String[] { "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" }, new TrustAllHosts()))
            .build();
    request = new HttpGet(serviceUrl);
    response = client.execute(request, context);
    assertThat(the(new StreamSource(response.getEntity().getContent())), hasXPath("/ServerVersion/version"));
    response.close();
    client.close();

    LOG_EXIT();
}

From source file:ch.ralscha.extdirectspring_itest.SecuredServiceTest.java

@Test
public void callSecretLoggedIn() throws IOException, JsonParseException, JsonMappingException {

    CloseableHttpClient client = HttpClientBuilder.create().build();
    CloseableHttpResponse response = null;
    try {//  ww  w .j a va  2 s  .  c  om

        HttpGet login = new HttpGet("http://localhost:9998/controller/login");
        response = client.execute(login);
        HttpEntity entity = response.getEntity();
        String responseString = EntityUtils.toString(entity);
        System.out.println(responseString);
        response.close();

        HttpPost post = new HttpPost("http://localhost:9998/controller/router");

        StringEntity postEntity = new StringEntity(
                "{\"action\":\"securedService\",\"method\":\"secret\",\"data\":[\"ralph\"],\"type\":\"rpc\",\"tid\":1}",
                "UTF-8");

        post.setEntity(postEntity);
        post.setHeader("Content-Type", "application/json; charset=UTF-8");

        response = client.execute(post);
        entity = response.getEntity();
        assertThat(entity).isNotNull();
        responseString = EntityUtils.toString(entity);

        assertThat(responseString).isNotNull();
        assertThat(responseString.startsWith("[") && responseString.endsWith("]")).isTrue();
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> rootAsMap = mapper
                .readValue(responseString.substring(1, responseString.length() - 1), Map.class);
        assertThat(rootAsMap).hasSize(5);
        assertThat(rootAsMap.get("result")).isEqualTo("RALPH,jimi");
        assertThat(rootAsMap.get("method")).isEqualTo("secret");
        assertThat(rootAsMap.get("type")).isEqualTo("rpc");
        assertThat(rootAsMap.get("action")).isEqualTo("securedService");
        assertThat(rootAsMap.get("tid")).isEqualTo(1);
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(client);
    }
}