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.apache.marmotta.platform.core.services.http.HttpClientServiceImpl.java

@Override
public void cleanupResponse(HttpResponse response) {
    if (response == null)
        throw new IllegalArgumentException("Response must not be null");
    EntityUtils.consumeQuietly(response.getEntity());
}

From source file:org.ops4j.pax.web.itest.base.HttpTestClient.java

public String testWebPath(String path, String expectedContent, int httpRC, boolean authenticate,
        BasicHttpContext basicHttpContext) throws Exception {

    int count = 0;
    while (!checkServer(path) && count++ < 5) {
        if (count > 5) {
            break;
        }/*from w ww . ja v a 2s.c  om*/
    }

    HttpResponse response = null;
    response = getHttpResponse(path, authenticate, basicHttpContext, false);

    assertEquals("HttpResponseCode", httpRC, response.getStatusLine().getStatusCode());

    if (response.getStatusLine().getStatusCode() == 403) {
        EntityUtils.consumeQuietly(response.getEntity());
        return null;
    }

    String responseBodyAsString = EntityUtils.toString(response.getEntity());
    if (expectedContent != null) {
        assertTrue("Content: " + responseBodyAsString, responseBodyAsString.contains(expectedContent));
    }

    return responseBodyAsString;
}

From source file:org.codelibs.empros.agent.operation.rest.RestApiOperation.java

@Override
public void excute(final List<Event> eventList) {
    if (!apiAvailable.get()) {
        callbackResultError(eventList);//from   ww  w.j a v  a2s.  c  om
        return;
    }

    boolean isSuccess = false;
    int start = 0;
    int retryCount = 0;
    while (true) {
        int end;
        if (start + eventCapacity < eventList.size()) {
            end = start + eventCapacity;
        } else {
            end = eventList.size();
        }

        HttpPost httpPost = null;
        HttpEntity httpEntity = null;
        try {
            httpPost = getHttpPost(eventList.subList(start, end));

            final HttpResponse response = httpClient.execute(httpPost);
            httpEntity = response.getEntity();
            final int status = response.getStatusLine().getStatusCode();
            if (logger.isDebugEnabled()) {
                logger.debug("response: " + response.toString());
            }

            if (status == HttpStatus.SC_OK) {
                if (end < eventList.size()) {
                    start = end;
                    retryCount = 0;
                } else {
                    // finished
                    isSuccess = true;
                    break;
                }
            } else {
                final String content = getContentAsString(httpEntity);
                logger.warn("HTTPRequest error. status code:" + status + " retry:" + retryCount + " url:" + url
                        + ", content: " + content);

                if (retryCount < maxRetryCount) {
                    retryCount++;
                } else {
                    // finished by an error
                    break;
                }
            }
        } catch (final Exception e) {
            logger.warn("Could not access: " + url + " retry: " + retryCount, e);
            if (retryCount < maxRetryCount) {
                retryCount++;
            } else {
                // finished by an error
                break;
            }
            if (httpPost != null) {
                httpPost.abort();
            }
        } finally {
            EntityUtils.consumeQuietly(httpEntity);
        }

        sleep();
    }

    if (isSuccess) {
        callbackResultSuccess(eventList);
    } else {
        callbackResultError(eventList);
    }
}

From source file:com.cloudera.oryx.contrib.flume.OryxEventSink.java

/**
 * Sends the given {@code batch} to Oryx in a HTTP POST request.
 * @param batch the batch of records to send to Oryx
 *///from  w ww  .j ava 2s.co  m
private void processBatch(Collection<String> batch) {
    if (log.isDebugEnabled()) {
        log.debug("Sending batch of {} records to Oryx at {}", batch.size(), oryxUri);
    }

    StringBuilder sb = new StringBuilder();
    for (String record : batch) {
        sb.append(record).append('\n');
    }

    HttpPost post = new HttpPost(oryxUri);
    HttpEntity entity = new StringEntity(sb.toString(), ContentType.TEXT_PLAIN);
    post.setEntity(entity);

    try {
        HttpResponse response = client.execute(post);
        if (log.isDebugEnabled()) {
            log.debug("HTTP response from Oryx: '{}'", response.getStatusLine());
        }
        EntityUtils.consumeQuietly(response.getEntity());
    } catch (IOException e) {
        log.error("Unable to POST batch to Oryx", e);
    }
}

From source file:com.erudika.para.security.GoogleAuthFilter.java

/**
 * Calls the Google+ API to get the user profile using a given access token.
 * @param appid app identifier of the parent app, use null for root app
 * @param accessToken access token//from   w ww.ja v a2s. c o m
 * @return {@link UserAuthentication} object or null if something went wrong
 * @throws IOException ex
 */
public UserAuthentication getOrCreateUser(String appid, String accessToken) throws IOException {
    UserAuthentication userAuth = null;
    if (accessToken != null) {
        User user = new User();
        user.setAppid(appid);
        HttpGet profileGet = new HttpGet(PROFILE_URL);
        profileGet.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
        CloseableHttpResponse resp2 = httpclient.execute(profileGet);
        HttpEntity respEntity = resp2.getEntity();
        String ctype = resp2.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();

        if (respEntity != null && Utils.isJsonType(ctype)) {
            Map<String, Object> profile = jreader.readValue(resp2.getEntity().getContent());

            if (profile != null && profile.containsKey("sub")) {
                String googleSubId = (String) profile.get("sub");
                String pic = (String) profile.get("picture");
                String email = (String) profile.get("email");
                String name = (String) profile.get("name");

                user.setIdentifier(Config.GPLUS_PREFIX.concat(googleSubId));
                user = User.readUserForIdentifier(user);
                if (user == null) {
                    //user is new
                    user = new User();
                    user.setActive(true);
                    user.setEmail(StringUtils.isBlank(email) ? googleSubId + "@google.com" : email);
                    user.setName(StringUtils.isBlank(name) ? "No Name" : name);
                    user.setPassword(new UUID().toString());
                    user.setPicture(getPicture(pic));
                    user.setIdentifier(Config.GPLUS_PREFIX.concat(googleSubId));
                    String id = user.create();
                    if (id == null) {
                        throw new AuthenticationServiceException(
                                "Authentication failed: cannot create new user.");
                    }
                } else {
                    String picture = getPicture(pic);
                    if (!StringUtils.equals(user.getPicture(), picture)) {
                        user.setPicture(picture);
                        user.update();
                    }
                }
                userAuth = new UserAuthentication(new AuthenticatedUserDetails(user));
            }
            EntityUtils.consumeQuietly(resp2.getEntity());
        }
    }
    return userAuth;
}

From source file:httpfailover.FailoverHttpClient.java

/**
 * Executes a request using the default context and processes the
 * response using the given response handler.
 *
 * @param targets   the candidate target hosts for the request.
 *                  The request is executed on each hosts until one succeeds.
 * @param request   the request to execute
 * @param responseHandler the response handler
 * @param context   the context to use for the execution, or
 *                  <code>null</code> to use the default context
 *
 * @return  the response object as generated by the response handler.
 * @throws IOException in case of a problem or the connection was aborted
 * @throws ClientProtocolException in case of an http protocol error
 *//*  w  w w . j av  a 2  s  . com*/
public <T> T execute(List<HttpHost> targets, HttpRequest request, ResponseHandler<? extends T> responseHandler,
        HttpContext context) throws IOException, ClientProtocolException {

    HttpResponse response = execute(targets, request, context);
    T result;
    try {
        result = responseHandler.handleResponse(response);
    } catch (Exception t) {
        HttpEntity entity = response.getEntity();
        try {
            EntityUtils.consume(entity);
        } catch (Exception t2) {
            // Log this exception. The original exception is more
            // important and will be thrown to the caller.
            this.log.warn("Error consuming content after an exception.", t2);
        }
        if (t instanceof RuntimeException) {
            throw (RuntimeException) t;
        }
        if (t instanceof IOException) {
            throw (IOException) t;
        }
        throw new UndeclaredThrowableException(t);
    }

    // Handling the response was successful. Ensure that the content has
    // been fully consumed.
    HttpEntity entity = response.getEntity();
    EntityUtils.consumeQuietly(entity);

    return result;
}

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

@Override
public List<String> listTriggerGroups() throws BrianClientException, BrianServerException {
    logger.debug("list trigger groups: {}");
    HttpResponse httpResponse = null;//from  w w w .  j a  v  a  2 s .  c  o  m
    try {
        URI uri = new URI(scheme, null, hostname, port, "/triggers", null, null);
        HttpUriRequest httpRequest = RequestBuilder.get().setUri(uri).build();
        httpResponse = httpClientExecute(httpRequest);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        logger.debug("statusCode: {}", statusCode);
        if (statusCode == HttpStatus.SC_OK) {
            JsonNode tree = mapper.readTree(httpResponse.getEntity().getContent());
            return StreamSupport.stream(tree.spliterator(), false).map(item -> item.textValue())
                    .collect(Collectors.toList());
        } else if (statusCode >= 500) {
            throw new BrianServerException("status = " + statusCode);
        } else if (statusCode >= 400) {
            throw new BrianClientException("status = " + statusCode);
        } else {
            throw new Error("status = " + statusCode);
        }
    } 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:com.erudika.para.security.GitHubAuthFilter.java

/**
 * Calls the GitHub API to get the user profile using a given access token.
 * @param appid app identifier of the parent app, use null for root app
 * @param accessToken access token/* ww  w . j  a  v  a2  s.com*/
 * @return {@link UserAuthentication} object or null if something went wrong
 * @throws IOException ex
 */
public UserAuthentication getOrCreateUser(String appid, String accessToken) throws IOException {
    UserAuthentication userAuth = null;
    if (accessToken != null) {
        User user = new User();
        user.setAppid(appid);
        HttpGet profileGet = new HttpGet(PROFILE_URL);
        profileGet.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
        profileGet.setHeader(HttpHeaders.ACCEPT, "application/json");
        CloseableHttpResponse resp2 = httpclient.execute(profileGet);
        HttpEntity respEntity = resp2.getEntity();
        String ctype = resp2.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();

        if (respEntity != null && Utils.isJsonType(ctype)) {
            Map<String, Object> profile = jreader.readValue(resp2.getEntity().getContent());

            if (profile != null && profile.containsKey("id")) {
                Integer githubId = (Integer) profile.get("id");
                String pic = (String) profile.get("avatar_url");
                String email = (String) profile.get("email");
                String name = (String) profile.get("name");

                user.setIdentifier(Config.GITHUB_PREFIX + githubId);
                user = User.readUserForIdentifier(user);
                if (user == null) {
                    //user is new
                    user = new User();
                    user.setActive(true);
                    user.setEmail(StringUtils.isBlank(email) ? githubId + "@github.com" : email);
                    user.setName(StringUtils.isBlank(name) ? "No Name" : name);
                    user.setPassword(new UUID().toString());
                    user.setPicture(getPicture(pic));
                    user.setIdentifier(Config.GITHUB_PREFIX + githubId);
                    String id = user.create();
                    if (id == null) {
                        throw new AuthenticationServiceException(
                                "Authentication failed: cannot create new user.");
                    }
                } else {
                    String picture = getPicture(pic);
                    if (!StringUtils.equals(user.getPicture(), picture)) {
                        user.setPicture(picture);
                        user.update();
                    }
                }
                userAuth = new UserAuthentication(new AuthenticatedUserDetails(user));
            }
            EntityUtils.consumeQuietly(resp2.getEntity());
        }
    }
    return userAuth;
}

From source file:io.openvidu.java.client.Session.java

/**
 * Gracefully closes the Session: unpublishes all streams and evicts every
 * participant/*from w  w  w. ja  va2s .co m*/
 * 
 * @throws OpenViduJavaClientException
 * @throws OpenViduHttpException
 */
public void close() throws OpenViduJavaClientException, OpenViduHttpException {
    HttpDelete request = new HttpDelete(
            OpenVidu.urlOpenViduServer + OpenVidu.API_SESSIONS + "/" + this.sessionId);
    request.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");

    HttpResponse response;
    try {
        response = OpenVidu.httpClient.execute(request);
    } catch (IOException e) {
        throw new OpenViduJavaClientException(e.getMessage(), e.getCause());
    }

    try {
        int statusCode = response.getStatusLine().getStatusCode();
        if ((statusCode == org.apache.http.HttpStatus.SC_NO_CONTENT)) {
            OpenVidu.activeSessions.remove(this.sessionId);
            log.info("Session {} closed", this.sessionId);
        } else {
            throw new OpenViduHttpException(statusCode);
        }
    } finally {
        EntityUtils.consumeQuietly(response.getEntity());
    }
}