Example usage for org.apache.http.util EntityUtils consume

List of usage examples for org.apache.http.util EntityUtils consume

Introduction

In this page you can find the example usage for org.apache.http.util EntityUtils consume.

Prototype

public static void consume(HttpEntity httpEntity) throws IOException 

Source Link

Usage

From source file:it.component.ProjectSearchTest.java

/**
 * SONAR-3105/*from  ww w. j a v  a  2s .c o  m*/
 */
@Test
public void projects_web_service() throws IOException {
    SonarScanner build = SonarScanner.create(projectDir("shared/xoo-sample"));
    orchestrator.executeBuild(build);

    String url = orchestrator.getServer().getUrl() + "/api/projects/index?key=sample&versions=true";
    HttpClient httpclient = new DefaultHttpClient();
    try {
        HttpGet get = new HttpGet(url);
        HttpResponse response = httpclient.execute(get);

        assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
        String content = IOUtils.toString(response.getEntity().getContent());
        assertThat(content).doesNotContain("error");
        assertThat(content).contains("sample");
        EntityUtils.consume(response.getEntity());

    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.helm.notation2.wsadapter.NucleotideWSSaver.java

/**
 * Adds or updates a single nucleotide to the nucleotide store using the URL configured in
 * {@code MonomerStoreConfiguration}./*from ww  w . j  a  v  a 2s .  c o  m*/
 * 
 * @param nucleotide to save
 */
public String saveNucleotideToStore(Nucleotide nucleotide) {
    String res = "";
    CloseableHttpResponse response = null;

    try {
        response = WSAdapterUtils.putResource(nucleotide.toJSON(),
                MonomerStoreConfiguration.getInstance().getWebserviceNucleotidesPutFullURL());
        LOG.debug(response.getStatusLine().toString());

        EntityUtils.consume(response.getEntity());

    } catch (Exception e) {
        LOG.error("Saving nucleotide failed!", e);
        return "";
    } finally {
        try {
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            LOG.debug("Closing resources failed.", e);
            return res;
        }
    }

    return res;
}

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

@Test
public void testActive() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme("http").setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpGet httpGet = new HttpGet(uri);

    try (CloseableHttpResponse response = httpclient.execute(httpGet)) {

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

        HttpEntity entity = response.getEntity();

        String buff;/*from  w ww. ja  v a 2 s  .  com*/
        try (BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()))) {
            buff = in.readLine();
            while (buff != null) {
                assertEquals(buff, TestController.TEST_STRING);
                buff = in.readLine();
            }
        }

        EntityUtils.consume(entity);
    }
}

From source file:crawler.PageFetchResult.java

public void discardContentIfNotConsumed() {
    try {/* w  ww  .j a  va  2  s.  c o m*/
        if (entity != null) {
            EntityUtils.consume(entity);
        }
    } catch (IOException ignored) {
        // We can EOFException (extends IOException) exception. It can happen on compressed
        // streams which are not
        // repeatable
        // We can ignore this exception. It can happen if the stream is closed.
    } catch (Exception e) {
        logger.warn("Unexpected error occurred while trying to discard content", e);
    }
}

From source file:com.foundationdb.http.HttpMonitorVerifyIT.java

private static int openRestURL(HttpClient client, String userInfo, int port, String path) throws Exception {
    URI uri = new URI("http", userInfo, "localhost", port, path, null, null);
    HttpGet get = new HttpGet(uri);
    HttpResponse response = client.execute(get);
    int code = response.getStatusLine().getStatusCode();
    EntityUtils.consume(response.getEntity());
    return code;/* www  .  j a v  a  2s  .  c om*/
}

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.//from  ww  w  .j av  a  2s. c o  m
 *
 * @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:it.componentSearch.ProjectSearchTest.java

/**
 * SONAR-3105/*from  w  ww. ja  va 2s  .co m*/
 */
@Test
public void projects_web_service() throws IOException {
    SonarRunner build = SonarRunner.create(projectDir("shared/xoo-sample"));
    orchestrator.executeBuild(build);

    String url = orchestrator.getServer().getUrl() + "/api/projects?key=sample&versions=true";
    HttpClient httpclient = new DefaultHttpClient();
    try {
        HttpGet get = new HttpGet(url);
        HttpResponse response = httpclient.execute(get);

        assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
        String content = IOUtils.toString(response.getEntity().getContent());
        assertThat(content).doesNotContain("error");
        assertThat(content).contains("sample");
        EntityUtils.consume(response.getEntity());

    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.drftpd.protocol.speedtest.net.slave.SpeedTestCallable.java

@Override
public Long call() throws Exception {
    Long bytes = 0L;//w  ww .ja va  2s .c o  m
    try {
        if (httpPost != null) {
            response = httpClient.execute(httpPost);
            final int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                throw new Exception("Error code " + statusCode + " while running upload test.");
            }

            HttpEntity entity = response.getEntity();
            String data = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
            if (!data.startsWith("size=")) {
                throw new Exception(
                        "Wrong return result from upload messurement from test server.\nReceived: " + data);
            }
            bytes = Long.parseLong(data.replaceAll("\\D", ""));
        } else if (httpGet != null) {
            response = httpClient.execute(httpGet);
            final int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                throw new Exception("Error code " + statusCode + " while running upload test.");
            }
            HttpEntity entity = response.getEntity();
            InputStream instream = entity.getContent();
            int bufferSize = 10240;
            byte[] buffer = new byte[bufferSize];
            int len;
            while ((len = instream.read(buffer)) != -1) {
                bytes = bytes + len;
            }
            EntityUtils.consume(entity);
        }
    } catch (Exception e) {
        throw new ExecutionException(e);
    } finally {
        try {
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            // Must already be closed, ignore.
        }
    }

    return bytes;
}

From source file:com.googlecode.noweco.webmail.portal.lotuslive.LotusLivePortalConnector.java

public PortalConnection connect(final HttpHost proxy, final String user, final String password)
        throws IOException {
    DefaultHttpClient httpclient = UnsecureHttpClientFactory.INSTANCE.createUnsecureHttpClient(proxy);

    HttpGet httpGet;//from  w  w w .  j  a v  a  2 s. co m
    HttpPost httpost;
    HttpResponse rsp;
    HttpEntity entity;

    // STEP 1 : Login page

    httpGet = new HttpGet("https://apps.lotuslive.com/manage/account/dashboardHandler/input");
    rsp = httpclient.execute(httpGet);

    entity = rsp.getEntity();
    if (entity != null) {
        EntityUtils.consume(entity);
    }

    // STEP 2 : Send form

    // prepare the request
    httpost = new HttpPost("https://apps.lotuslive.com/pkmslogin.form");
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("login-form-type", "pwd"));
    nvps.add(new BasicNameValuePair("username", user));
    nvps.add(new BasicNameValuePair("password", password));
    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

    // send the request
    rsp = httpclient.execute(httpost);

    // free result resources
    entity = rsp.getEntity();
    if (entity != null) {
        EntityUtils.consume(entity);
    }

    int statusCode = rsp.getStatusLine().getStatusCode();
    if (statusCode != 302) {
        throw new IOException("Unable to connect to lotus live portail, status code : " + statusCode);
    }

    // STEP 3 : Fetch SAML token

    httpGet = new HttpGet("https://mail.lotuslive.com/mail/loginlanding");
    rsp = httpclient.execute(httpGet);

    entity = rsp.getEntity();
    String firstEntity = EntityUtils.toString(entity);
    if (entity != null) {
        EntityUtils.consume(entity);
    }

    // STEP 4 : Use SAML token to identify

    httpost = new HttpPost("https://mail.lotuslive.com/auth/tfim");
    nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("TARGET", "http://mail.lotuslive.com/mail"));
    Matcher samlMatcher = SAML_RESPONSE.matcher(firstEntity);
    if (!samlMatcher.find()) {
        throw new IOException("Unable to find SAML token");
    }
    nvps.add(new BasicNameValuePair("SAMLResponse", samlMatcher.group(1)));

    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    // send the request
    rsp = httpclient.execute(httpost);

    entity = rsp.getEntity();
    if (entity != null) {
        EntityUtils.consume(entity);
    }

    // STEP 5 : VIEW ROOT PAGE (TODO can delete ?)

    httpGet = new HttpGet("https://mail-usw.lotuslive.com/mail/mail/listing/INBOX");
    rsp = httpclient.execute(httpGet);

    entity = rsp.getEntity();
    if (entity != null) {
        EntityUtils.consume(entity);
    }

    return new DefaultPortalConnection(httpclient, new HttpHost("mail-usw.lotuslive.com", 443), "");
}

From source file:org.apache.abdera2.protocol.client.AbderaResponseHandler.java

public Document<? extends Element> handleResponse(HttpResponse response)
        throws ClientProtocolException, IOException {
    ResponseType type = ResponseType.select(response.getStatusLine().getStatusCode());
    switch (type) {
    case SUCCESSFUL:
        return options == null ? abdera.getParser().parse(getInputStream(response))
                : abdera.getParser().parse(getInputStream(response), options);
    default://  ww  w  . j a v a2  s  . c o  m
        EntityUtils.consume(response.getEntity());
        StatusLine status = response.getStatusLine();
        throw new HttpResponseException(status.getStatusCode(), status.getReasonPhrase());
    }

}