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:com.ibm.mobilefirstplatform.serversdk.java.push.PushNotifications.java

protected static void executePushPostRequest(HttpPost pushPost, CloseableHttpClient httpClient,
        PushNotificationsResponseListener listener) {
    CloseableHttpResponse response = null;

    try {//from w w  w  .  j  ava 2 s.co  m
        response = httpClient.execute(pushPost);

        if (listener != null) {
            sendResponseToListener(response, listener);
        }
    } catch (ClientProtocolException e) {
        logger.log(Level.SEVERE, e.toString(), e);
        if (listener != null) {
            listener.onFailure(null, null, e);
        }
    } catch (IOException e) {
        logger.log(Level.SEVERE, e.toString(), e);
        if (listener != null) {
            listener.onFailure(null, null, e);
        }
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                // Closing response is merely a best effort.
            }
        }
    }
}

From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java

/**
 * Do delete./*  w w w.  j a  v  a 2 s.c  om*/
 *
 * @param uri the uri
 * @param headers the headers
 * @return the http get simple resp
 * @throws ClientProtocolException the client protocol exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws HttpResponseException the http response exception
 */
public static HttpGetSimpleResp doDelete(String uri, HashMap<String, String> headers)
        throws ClientProtocolException, IOException, HttpResponseException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGetSimpleResp resp = new HttpGetSimpleResp();
    try {
        HttpDelete httpDelete = new HttpDelete(uri);
        for (String key : headers.keySet()) {
            httpDelete.addHeader(key, headers.get(key));
        }
        CloseableHttpResponse response = httpclient.execute(httpDelete);

        resp.setStatusCode(response.getStatusLine().getStatusCode());
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT) {
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    // TODO to use for performance in the future
                    resp.setResult(new BasicResponseHandler().handleResponse(response));
                }
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } else {
            // TODO optimiz (repeating code)
            throw new HttpResponseException(response.getStatusLine().getStatusCode(),
                    response.getStatusLine().getReasonPhrase());
        }
    } finally {
        httpclient.close();
    }
    return resp;
}

From source file:com.vmware.identity.samlservice.impl.SamlServiceImpl.java

/**
 * Utility method to send a slo request to a participant via GET message.
 * @param requestUrl/*w  ww.j  a  v a  2  s .  c o  m*/
 * @throws URISyntaxException
 * @throws IOException
 * @throws ClientProtocolException
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
static void sendSLORequestToOtherParticipant(String requestUrl)
        throws URISyntaxException, ClientProtocolException, IOException, NoSuchAlgorithmException,
        KeyStoreException, KeyManagementException {

    if (requestUrl == null || requestUrl.isEmpty())
        return;

    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(builder.build(),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    URI httpUri = new URI(requestUrl);
    HttpGet httpGet = new HttpGet(httpUri);
    CloseableHttpResponse response = client.execute(httpGet);
    response.close();
}

From source file:de.intevation.irix.ImageClient.java

/** Obtains a Report from mapfish-print service.
 *
 * @param imageUrl The url to send the request to.
 * @param timeout the timeout for the httpconnection.
 *
 * @return byte[] with the report./*from   w ww. ja  v a  2s  .  c  o  m*/
 *
 * @throws IOException if communication with print service failed.
 * @throws ImageException if the print job failed.
 */
public static byte[] getImage(String imageUrl, int timeout) throws IOException, ImageException {

    RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).build();

    CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build();

    HttpGet get = new HttpGet(imageUrl);
    CloseableHttpResponse resp = client.execute(get);

    StatusLine status = resp.getStatusLine();

    byte[] retval = null;
    try {
        HttpEntity respEnt = resp.getEntity();
        InputStream in = respEnt.getContent();
        if (in != null) {
            try {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buf = new byte[BYTE_ARRAY_SIZE];
                int r;
                while ((r = in.read(buf)) >= 0) {
                    out.write(buf, 0, r);
                }
                retval = out.toByteArray();
            } finally {
                in.close();
                EntityUtils.consume(respEnt);
            }
        }
    } finally {
        resp.close();
    }

    if (status.getStatusCode() < HttpURLConnection.HTTP_OK
            || status.getStatusCode() >= HttpURLConnection.HTTP_MULT_CHOICE) {
        if (retval != null) {
            throw new ImageException(new String(retval));
        } else {
            throw new ImageException("Communication with print service '" + imageUrl + "' failed."
                    + "\nNo response from print service.");
        }
    }
    return retval;
}

From source file:de.intevation.irix.PrintClient.java

/** Obtains a Report from mapfish-print service.
 *
 * @param printUrl The url to send the request to.
 * @param json The json spec for the print request.
 * @param timeout the timeout for the httpconnection.
 *
 * @return byte[] with the report./* www . j a  v  a2s .  com*/
 *
 * @throws IOException if communication with print service failed.
 * @throws PrintException if the print job failed.
 */
public static byte[] getReport(String printUrl, String json, int timeout) throws IOException, PrintException {

    RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).build();

    CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build();

    HttpEntity entity = new StringEntity(json,
            ContentType.create("application/json", Charset.forName("UTF-8")));

    HttpPost post = new HttpPost(printUrl);
    post.setEntity(entity);
    CloseableHttpResponse resp = client.execute(post);

    StatusLine status = resp.getStatusLine();

    byte[] retval = null;
    try {
        HttpEntity respEnt = resp.getEntity();
        InputStream in = respEnt.getContent();
        if (in != null) {
            try {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buf = new byte[BYTE_ARRAY_SIZE];
                int r;
                while ((r = in.read(buf)) >= 0) {
                    out.write(buf, 0, r);
                }
                retval = out.toByteArray();
            } finally {
                in.close();
                EntityUtils.consume(respEnt);
            }
        }
    } finally {
        resp.close();
    }

    if (status.getStatusCode() < HttpURLConnection.HTTP_OK
            || status.getStatusCode() >= HttpURLConnection.HTTP_MULT_CHOICE) {
        if (retval != null) {
            throw new PrintException(new String(retval));
        } else {
            throw new PrintException("Communication with print service '" + printUrl + "' failed."
                    + "\nNo response from print service.");
        }
    }
    return retval;
}

From source file:org.dashbuilder.dataprovider.backend.elasticsearch.ElasticSearchDataSetTestBase.java

protected static Object[] doGet(String url) throws Exception {
    Object[] response = null;//from ww  w . ja  va2  s .c om
    if (url == null || url.trim().length() == 0)
        return response;

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);
    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    try {
        HttpEntity entity1 = response1.getEntity();
        String responseBody = responseAsString(response1);
        int responseStatus = response1.getStatusLine().getStatusCode();
        response = new Object[] { responseStatus, responseBody };

        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity1);
    } finally {
        response1.close();
    }

    return response;
}

From source file:org.sead.repositories.reference.util.SEADAuthenticator.java

static public HttpClientContext authenticate(String server) {

    boolean authenticated = false;
    log.info("Authenticating");

    String accessToken = SEADGoogleLogin.getAccessToken();

    // Now login to server and create a session
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//from   w ww . j  av a2  s  .  co  m
        // //DoLogin is the auth endpoint when using the AUthFilter, versus
        // the api/authenticate endpoint when connecting to the ACR directly
        HttpPost seadAuthenticate = new HttpPost(server + "/DoLogin");
        List<NameValuePair> nvpList = new ArrayList<NameValuePair>(1);
        nvpList.add(0, new BasicNameValuePair("googleAccessToken", accessToken));

        seadAuthenticate.setEntity(new UrlEncodedFormEntity(nvpList));

        CloseableHttpResponse response = httpclient.execute(seadAuthenticate, localContext);
        try {
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    // String seadSessionId =
                    // EntityUtils.toString(resEntity);
                    authenticated = true;
                }
            } else {
                // Seems to occur when google device id is not set on server
                // - with a Not Found response...
                log.error("Error response from " + server + " : " + response.getStatusLine().getReasonPhrase());
            }
        } finally {
            response.close();
            httpclient.close();
        }
    } catch (IOException e) {
        log.error("Cannot read sead-google.json");
        log.error(e.getMessage());
    }

    // localContext should have the cookie with the SEAD session key, which
    // nominally is all that's needed.
    // FixMe: If there is no activity for more than 15 minutes, the session
    // may expire, in which case,
    // re-authentication using the refresh token to get a new google token
    // to allow SEAD login again may be required

    // also need to watch the 60 minutes google token timeout - project
    // spaces will invalidate the session at 60 minutes even if there is
    // activity
    authTime = System.currentTimeMillis();

    if (authenticated) {
        return localContext;
    }
    return null;
}

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

private static void loadFormFile(String host, File file) {
    Scanner scan = null;//from w w w.j  a va  2  s  .co  m
    try {
        scan = new Scanner(file, Loader.encoding);
        // the content is only the data portion.
        String content = scan.useDelimiter("\\Z").next();
        // convert to map
        Map<String, Object> newMap = ServiceLocator.getInstance().getMapper().readValue(content,
                new TypeReference<HashMap<String, Object>>() {
                });
        String formId = (String) newMap.get("formId");
        Map<String, Object> oldMap = (Map<String, Object>) formMap.get(formId);
        boolean changed = false;
        if (oldMap == null) {
            // never loaded before.
            changed = true;
        } else {
            if (newMap.get("action") != null && !newMap.get("action").equals(oldMap.get("action"))) {
                changed = true;
            }
            if (!changed && newMap.get("schema") != null
                    && !newMap.get("schema").equals(oldMap.get("schema"))) {
                changed = true;
            }
            if (!changed && newMap.get("form") != null && !newMap.get("form").equals(oldMap.get("form"))) {
                changed = true;
            }
            if (!changed && newMap.get("modelData") != null
                    && !newMap.get("modelData").equals(oldMap.get("modelData"))) {
                changed = true;
            }
        }
        if (changed) {
            Map<String, Object> inputMap = new HashMap<String, Object>();
            inputMap.put("category", "form");
            inputMap.put("name", "impForm");
            inputMap.put("readOnly", false);

            Map<String, Object> data = new HashMap<String, Object>();
            data.put("content", content);
            inputMap.put("data", data);
            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);
            CloseableHttpResponse response = httpclient.execute(httpPost);

            try {
                System.out.println("Form: " + file.getAbsolutePath() + " is loaded with status "
                        + response.getStatusLine());
                HttpEntity entity = response.getEntity();
                BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
                String json = "";
                String line = "";
                while ((line = rd.readLine()) != null) {
                    json = json + line;
                }
                //System.out.println("json = " + json);
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        if (scan != null)
            scan.close();
    }
}

From source file:org.wuspba.ctams.ws.ITBandRegistrationController.java

protected static void delete() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
            .setParameter("id", TestFixture.INSTANCE.bandRegistration.getId()).build();

    HttpDelete httpDelete = new HttpDelete(uri);

    CloseableHttpResponse response = null;

    try {/*from w w  w .  j  av  a  2 s. c o m*/
        response = httpclient.execute(httpDelete);

        assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

        HttpEntity responseEntity = response.getEntity();

        EntityUtils.consume(responseEntity);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Unsupported coding", ex);
    } catch (IOException ioex) {
        LOG.error("IOException", ioex);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ex) {
                LOG.error("Could not close response", ex);
            }
        }
    }

    ITBandController.delete();
}

From source file:org.wuspba.ctams.ws.ITSoloRegistrationController.java

protected static void delete() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
            .setParameter("id", TestFixture.INSTANCE.soloRegistration.getId()).build();

    HttpDelete httpDelete = new HttpDelete(uri);

    CloseableHttpResponse response = null;

    try {//from  ww  w . j a v a  2  s .co m
        response = httpclient.execute(httpDelete);

        assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

        HttpEntity responseEntity = response.getEntity();

        EntityUtils.consume(responseEntity);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Unsupported coding", ex);
    } catch (IOException ioex) {
        LOG.error("IOException", ioex);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ex) {
                LOG.error("Could not close response", ex);
            }
        }
    }

    ITPersonController.delete();
}