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

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

Introduction

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

Prototype

public static void consumeQuietly(HttpEntity httpEntity) 

Source Link

Usage

From source file:org.keycloak.testsuite.admin.concurrency.ConcurrentLoginTest.java

protected String parseAndCloseResponse(CloseableHttpResponse response) {
    try {/*  www.  j  ava  2  s .  c om*/
        int responseCode = response.getStatusLine().getStatusCode();
        String resp = EntityUtils.toString(response.getEntity());

        if (responseCode != 200) {
            log.debugf("Response Code: %d, Body: %s", responseCode, resp);
        }
        return resp;
    } catch (IOException | UnsupportedOperationException ex) {
        throw new RuntimeException(ex);
    } finally {
        if (response != null) {
            EntityUtils.consumeQuietly(response.getEntity());
            try {
                response.close();
            } catch (IOException ex) {
            }
        }
    }
}

From source file:com.yahoo.ycsb.webservice.rest.RestClient.java

private int httpExecute(HttpEntityEnclosingRequestBase request, String data) throws IOException {
    requestTimedout.setIsSatisfied(false);
    Thread timer = new Thread(new Timer(execTimeout, requestTimedout));
    timer.start();/*from  w w  w .  jav  a2  s  .c o  m*/
    int responseCode = 200;
    for (int i = 0; i < headers.length; i = i + 2) {
        request.setHeader(headers[i], headers[i + 1]);
    }
    InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(data.getBytes()),
            ContentType.APPLICATION_FORM_URLENCODED);
    reqEntity.setChunked(true);
    request.setEntity(reqEntity);
    CloseableHttpResponse response = client.execute(request);
    responseCode = response.getStatusLine().getStatusCode();
    HttpEntity responseEntity = response.getEntity();
    // If null entity don't bother about connection release.
    if (responseEntity != null) {
        InputStream stream = responseEntity.getContent();
        if (compressedResponse) {
            stream = new GZIPInputStream(stream);
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        StringBuffer responseContent = new StringBuffer();
        String line = "";
        while ((line = reader.readLine()) != null) {
            if (requestTimedout.isSatisfied()) {
                // Must avoid memory leak.
                reader.close();
                stream.close();
                EntityUtils.consumeQuietly(responseEntity);
                response.close();
                client.close();
                throw new TimeoutException();
            }
            responseContent.append(line);
        }
        timer.interrupt();
        // Closing the input stream will trigger connection release.
        stream.close();
    }
    EntityUtils.consumeQuietly(responseEntity);
    response.close();
    client.close();
    return responseCode;
}

From source file:ai.susi.server.ClientConnection.java

public void close() {
    HttpEntity httpEntity = this.httpResponse.getEntity();
    if (httpEntity != null)
        EntityUtils.consumeQuietly(httpEntity);
    try {//  ww w  .j  a v a 2  s . co m
        this.inputStream.close();
    } catch (IOException e) {
    } finally {
        this.request.releaseConnection();
    }
}

From source file:jp.classmethod.aws.brian.BrianClient.java

@Override
public CreateTriggerResult createTrigger(BrianTrigger trigger)
        throws BrianClientException, BrianServerException {
    logger.debug("create trigger: {}/{}", trigger.getGroup(), trigger.getName());
    HttpResponse httpResponse = null;/*from  w ww .  j  a  va 2  s .  co  m*/
    try {
        BrianTriggerRequest request = trigger.toBrianTriggerRequest();
        String requestBody = mapper.writeValueAsString(request);
        logger.trace("create: requestBody = {}", requestBody);
        HttpEntity entity = new StringEntity(requestBody);

        String path = String.format("/triggers/%s", trigger.getGroup());
        URI uri = new URI(scheme, null, hostname, port, path, null, null);
        HttpUriRequest httpRequest = RequestBuilder.post().setUri(uri).setEntity(entity).build();
        httpResponse = httpClientExecute(httpRequest);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        logger.debug("statusCode: {}", statusCode);
        JsonNode tree = mapper.readTree(httpResponse.getEntity().getContent());
        if (statusCode == HttpStatus.SC_CREATED) {
            String nextFireTime = tree.path("content").path("nextFireTime").asText();
            logger.info("trigger created: nextFireTime = {}", nextFireTime);
            return new CreateTriggerResult(Instant.parse(nextFireTime));
        } else if (statusCode >= 500) {
            throw new BrianServerException(String.format("status = %d; message = %s",
                    new Object[] { statusCode, tree.get("message").textValue() }));
        } else if (statusCode == HttpStatus.SC_CONFLICT) {
            throw new BrianClientException(String.format("triggerKey (%s/%s) is already exist",
                    new Object[] { trigger.getGroup(), trigger.getName() }));
        } else if (statusCode >= 400) {
            throw new BrianClientException(String.format("status = %d; message = %s",
                    new Object[] { statusCode, tree.get("message").textValue() }));
        } else {
            throw new Error(String.format("status = %d; message = %s",
                    new Object[] { statusCode, tree.get("message").textValue() }));
        }
    } catch (JsonProcessingException e) {
        throw new BrianServerException(e);
    } catch (URISyntaxException e) {
        throw new IllegalStateException(e);
    } catch (IOException e) {
        throw new BrianServerException(e);
    } catch (IllegalStateException e) {
        throw new Error(e);
    } finally {
        if (httpResponse != null) {
            EntityUtils.consumeQuietly(httpResponse.getEntity());
        }
    }
}

From source file:org.apache.olingo.server.example.TripPinServiceTest.java

@Test
public void testReadMedia() throws Exception {
    HttpResponse response = httpGET(baseURL + "/Photos(1)/$value", 200);
    EntityUtils.consumeQuietly(response.getEntity());
}

From source file:org.fcrepo.test.api.TestRESTAPI.java

protected void verifyDELETEStatusOnly(URI url, int expected, boolean authenticate) throws Exception {
    HttpDelete get = new HttpDelete(url);
    HttpResponse response = getOrDelete(get, authenticate, false);
    int status = response.getStatusLine().getStatusCode();
    EntityUtils.consumeQuietly(response.getEntity());
    assertEquals(expected, status);//from   www .ja v a  2s.  co  m
}

From source file:org.eclipse.aether.transport.http.HttpTransporter.java

private void mkdirs(URI uri, SharingHttpContext context) {
    List<URI> dirs = UriUtils.getDirectories(baseUri, uri);
    int index = 0;
    for (; index < dirs.size(); index++) {
        try {//from  w w w .  ja  v a  2s  . co  m
            HttpResponse response = client.execute(server, commonHeaders(new HttpMkCol(dirs.get(index))),
                    context);
            try {
                int status = response.getStatusLine().getStatusCode();
                if (status < 300 || status == HttpStatus.SC_METHOD_NOT_ALLOWED) {
                    break;
                } else if (status == HttpStatus.SC_CONFLICT) {
                    continue;
                }
                handleStatus(response);
            } finally {
                EntityUtils.consumeQuietly(response.getEntity());
            }
        } catch (IOException e) {
            LOGGER.debug("Failed to create parent directory {}", dirs.get(index), e);
            return;
        }
    }
    for (index--; index >= 0; index--) {
        try {
            HttpResponse response = client.execute(server, commonHeaders(new HttpMkCol(dirs.get(index))),
                    context);
            try {
                handleStatus(response);
            } finally {
                EntityUtils.consumeQuietly(response.getEntity());
            }
        } catch (IOException e) {
            LOGGER.debug("Failed to create parent directory {}", dirs.get(index), e);
            return;
        }
    }
}

From source file:org.apache.olingo.server.example.TripPinServiceTest.java

@Test
public void testCreateMedia() throws Exception {
    // treating update and create as same for now, as there is details about
    // how entity payload and media payload can be sent at same time in request's body
    String editUrl = baseURL + "/Photos(1)/$value";
    HttpPut request = new HttpPut(editUrl);
    request.setEntity(new ByteArrayEntity("bytecontents".getBytes(), ContentType.APPLICATION_OCTET_STREAM));
    HttpResponse response = httpSend(request, 204);
    EntityUtils.consumeQuietly(response.getEntity());
}

From source file:org.jenkinsci.plugins.fod.FoDAPI.java

/**
 * Given a URL, request, and HTTP client, authenticates with FoD API. 
 * This is just a utility method which uses none of the class member fields.
 * /*  w w  w  .ja va2s.  c  o m*/
 * @param baseUrl URL for FoD
 * @param request request to authenticate
 * @param client HTTP client object
 * @return
 */
private AuthTokenResponse authorize(String baseUrl, AuthTokenRequest request) {
    final String METHOD_NAME = CLASS_NAME + ".authorize";
    PrintStream out = FodBuilder.getLogger();

    AuthTokenResponse response = new AuthTokenResponse();
    try {
        String endpoint = baseUrl + "/oauth/token";
        HttpPost httppost = new HttpPost(endpoint);

        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_TIMEOUT)
                .setConnectTimeout(CONNECTION_TIMEOUT).setSocketTimeout(CONNECTION_TIMEOUT).build();

        httppost.setConfig(requestConfig);

        List<NameValuePair> formparams = new ArrayList<NameValuePair>();

        if (AuthCredentialType.CLIENT_CREDENTIALS.getName().equals(request.getGrantType())) {
            AuthApiKey cred = (AuthApiKey) request.getPrincipal();
            formparams.add(new BasicNameValuePair("scope", FOD_SCOPE_TENANT));
            formparams.add(new BasicNameValuePair("grant_type", request.getGrantType()));
            formparams.add(new BasicNameValuePair("client_id", cred.getClientId()));
            formparams.add(new BasicNameValuePair("client_secret", cred.getClientSecret()));
        } else {
            out.println(METHOD_NAME + ": unrecognized grant type");
        }

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, UTF_8);
        httppost.setEntity(entity);
        HttpResponse postResponse = getHttpClient().execute(httppost);
        StatusLine sl = postResponse.getStatusLine();
        Integer statusCode = Integer.valueOf(sl.getStatusCode());

        if (statusCode.toString().startsWith("2")) {
            InputStream is = null;

            try {
                HttpEntity respopnseEntity = postResponse.getEntity();
                is = respopnseEntity.getContent();
                StringBuffer content = collectInputStream(is);
                String x = content.toString();
                JsonParser parser = new JsonParser();
                JsonElement jsonElement = parser.parse(x);
                JsonObject jsonObject = jsonElement.getAsJsonObject();
                JsonElement tokenElement = jsonObject.getAsJsonPrimitive("access_token");
                if (null != tokenElement && !tokenElement.isJsonNull() && tokenElement.isJsonPrimitive()) {

                    response.setAccessToken(tokenElement.getAsString());

                }
                JsonElement expiresIn = jsonObject.getAsJsonPrimitive("expires_in");
                Integer expiresInInt = expiresIn.getAsInt();
                response.setExpiresIn(expiresInInt);
                //TODO handle remaining two fields in response
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {

                    }
                }
                EntityUtils.consumeQuietly(postResponse.getEntity());
                httppost.releaseConnection();
            }
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return response;
}