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:org.neo4j.ogm.session.transaction.TransactionManager.java

private HttpResponse executeRequest(HttpRequestBase request) {

    try {//from  w  ww. j a v a2s  . c o m

        request.setHeader(new BasicHeader("Accept", "application/json;charset=UTF-8"));
        HttpRequestAuthorization.authorize(request, credentials);

        HttpResponse response = httpClient.execute(request);
        StatusLine statusLine = response.getStatusLine();

        logger.debug("Status code: {}", statusLine.getStatusCode());

        if (statusLine.getStatusCode() >= 300) {
            throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
        }

        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            String responseText = EntityUtils.toString(responseEntity);
            logger.debug(responseText);
            EntityUtils.consume(responseEntity);
            if (responseText.contains("\"errors\":[{") || responseText.contains("\"errors\": [{")) {
                throw new ErrorsException(responseText);
            }
        }
        return response;
    }

    catch (Exception e) {
        throw new ResultProcessingException("Failed to execute request: ", e);
    }

    // always clean up the connection and the thread-local transaction instance;
    finally {
        request.releaseConnection();
        transaction.remove();
    }
}

From source file:com.signicat.hystrix.servlet.AsyncWrapperServletTest.java

@Test
public void require_That_Servlet_Timeout_Kicks_In_And_Hystrix_Timeout_Also_Kicks_In() throws Exception {
    CountDownLatch servletTimeout = new CountDownLatch(1);
    CountDownLatch hystrixError = new CountDownLatch(1);

    final AsyncTestServlet servlet = new AsyncTestServlet(new CountDownLatch(1), servletTimeout,
            new CountDownLatch(1), new CountDownLatch(1), hystrixError, new CountDownLatch(1), null,
            new TimeoutServlet(servletTimeout, hystrixError), 1000L);
    try (TestServer server = new TestServer(0, servlet)) {
        server.start();// w w w.  j  av a 2  s. c  o  m
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet("http://localhost:" + server.getPort() + "/bananarama");
            try (CloseableHttpResponse httpResponse = httpclient.execute(httpGet)) {
                StatusLine statusLine = httpResponse.getStatusLine();
                assertThat(statusLine.getStatusCode(), equalTo(504));
                assertThat(statusLine.getReasonPhrase(), equalTo("Timeout from async listener"));
                EntityUtils.consume(httpResponse.getEntity());
                assertThat(servlet.servletTimeout.await(60, TimeUnit.SECONDS), is(true));
                assertThat(servlet.servletComplete.await(60, TimeUnit.SECONDS), is(true));
                assertThat(servlet.servletError.getCount(), equalTo(1L));
                assertThat(servlet.hystrixError.await(60, TimeUnit.SECONDS), is(true));
                assertThat(servlet.hystrixCompleted.getCount(), equalTo(1L));
                assertThat(servlet.hystrixNext.getCount(), equalTo(1L));
            }
        }
    }
}

From source file:nl.salp.warcraft4j.battlenet.api.BattlenetHttpApi.java

/**
 * Execute the request and return the result body.
 *
 * @param request The request to execute.
 * @param client  The client to use for executing the request.
 *
 * @return The result body.//from   w  w  w.j av  a2 s .com
 *
 * @throws IOException When the call couldn't be executed or the server returned an error.
 */
private String execute(HttpUriRequest request, CloseableHttpClient client) throws IOException {
    try (CloseableHttpResponse response = client.execute(request)) {
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() > 300) {
            LOGGER.error("Request to '{}' returned code {} with message '{}'", request.getURI().toASCIIString(),
                    statusLine.getStatusCode(), statusLine.getReasonPhrase());
            throw new IOException(
                    format("Error %d: %s", statusLine.getStatusCode(), statusLine.getReasonPhrase()));
        }
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity);
        EntityUtils.consume(entity);
        LOGGER.debug("Request to '{}' successfully completed with code {}", request.getURI().toASCIIString(),
                statusLine.getStatusCode());
        return result;
    }
}

From source file:org.jmonkey.external.bintray.BintrayApiClient.java

public BintrayFile get(final String packageName) throws IOException {

    try (CloseableHttpClient httpClient = this.createClient()) {

        HttpUriRequest request = RequestBuilder.get().setUri("https://api.bintray.com/packages/"
                + config.getSubject() + "/" + config.getRepo() + "/" + cleanQuery(packageName)).build();

        try (CloseableHttpResponse httpResponse = httpClient.execute(request)) {

            int statusCode = httpResponse.getStatusLine().getStatusCode();

            if (statusCode >= 400) {
                // @TODO: provide a consumable error
            }//from w w  w. j  a va2s. c o m

            HttpEntity entity = httpResponse.getEntity();
            String entityString = EntityUtils.toString(entity);
            EntityUtils.consume(entity);

            BintrayFile result = JmeResourceWebsite.getObjectMapper().readValue(entityString,
                    BintrayFile.class);

            return result;
        }
    }
}

From source file:org.jboss.as.test.integration.web.security.jaspi.WebSecurityJaspiTestCase.java

protected void makeCall(String user, String pass, int expectedStatusCode) throws Exception {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()),
            new UsernamePasswordCredentials(user, pass));
    try (CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credentialsProvider).build()) {

        HttpGet httpget = new HttpGet(url.toExternalForm() + "secured/");

        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        StatusLine statusLine = response.getStatusLine();
        if (entity != null) {
            log.trace("Response content length: " + entity.getContentLength());
        }/*w  ww.java2 s.c  o m*/
        assertEquals(expectedStatusCode, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    }
}

From source file:org.lazydevs.api.gog.GogApi.java

public void login(String username, String password) {

    // Retrieve 'buk' - this param needs to be in the login request to succeed
    GogUser user = loadUser();/*from  w  ww . j a  v a  2s.c  o m*/

    // Execute login request
    List<NameValuePair> params = new ArrayList<NameValuePair>();

    params.add(new BasicNameValuePair(PARAM_USER, username));
    params.add(new BasicNameValuePair(PARAM_PASSWORD, password));
    params.add(new BasicNameValuePair(PARAM_UNLOCK_SETTINGS, "1"));
    params.add(new BasicNameValuePair(PARAM_BUK, user.getBuk()));

    HttpResponse response = HttpClientUtil.post(client, context, URL_LOGIN, params);

    try {
        EntityUtils.consume(response.getEntity());
    } catch (IOException e) {
        throw new GogApiException("Error closing login request.", e);
    }

    // Load user again to check if we are logged in
    user = loadUser();

    loggedIn = username.equalsIgnoreCase(user.getEmail());
}

From source file:eu.delving.sip.base.Harvestor.java

@Override
public void run() {
    try {//from  w  w w  . j  av a  2 s . co  m
        if (context.harvestPrefix() == null || context.harvestPrefix().trim().isEmpty()) {
            throw new IllegalArgumentException("Harvest prefix missing");
        }
        new URL(context.harvestUrl()); // throws MalformedUrlException if it is
        OutputStream outputStream = new GZIPOutputStream(new FileOutputStream(dataSet.importedOutput()));
        XMLEventWriter out = outputFactory.createXMLEventWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        out.add(eventFactory.createStartDocument());
        out.add(eventFactory.createCharacters("\n"));
        progressListener.setProgress(recordCount);
        HttpEntity fetchedRecords = fetchFirstEntity();
        String resumptionToken = saveRecords(fetchedRecords, out);
        while (isValidResumptionToken(resumptionToken) && recordCount > 0) {
            EntityUtils.consume(fetchedRecords);
            progressListener.setProgress(recordCount);
            fetchedRecords = fetchNextEntity(resumptionToken);
            resumptionToken = saveRecords(fetchedRecords, out);
            if (!isValidResumptionToken(resumptionToken) && recordCount > 0)
                EntityUtils.consume(fetchedRecords);
        }
        out.add(eventFactory.createEndElement("", "", ENVELOPE_TAG));
        out.add(eventFactory.createCharacters("\n"));
        out.add(eventFactory.createEndDocument());
        out.flush();
        outputStream.close();
    } catch (CancelException e) {
        progressListener.getFeedback().alert("Cancelled harvest of " + context.harvestUrl(), e);
        recordCount = 0;
    } catch (Exception e) {
        progressListener.getFeedback().alert(String.format("Unable to complete harvest of %s because of: %s",
                context.harvestUrl(), e.getMessage()), e);
        recordCount = 0;
    } finally {
        if (recordCount > 0) {
            progressListener.getFeedback().alert(String.format("Harvest of %s successfully fetched %d records",
                    context.harvestUrl(), recordCount));
        } else {
            FileUtils.deleteQuietly(dataSet.importedOutput());
        }
    }
}

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

private static int openRestURL(HttpClient client, String userInfo, int port, String path) throws Exception {
    URI uri = new URI("https", 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;/*  w ww.  j a v  a2  s .  c  o  m*/
}