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.fcrepo.test.api.TestRESTAPI.java

protected void verifyGETStatusOnly(URI url, int expected, boolean authenticate, boolean validate)
        throws Exception {
    HttpGet get = new HttpGet(url);
    HttpResponse response = getOrDelete(get, authenticate, validate);
    int status = response.getStatusLine().getStatusCode();
    EntityUtils.consumeQuietly(response.getEntity());
    assertEquals(expected, status);//from ww w. j ava2 s.  c  o m
}

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

@Test
public void testDeleteMedia() 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";
    HttpDelete request = new HttpDelete(editUrl);
    HttpResponse response = httpSend(request, 204);
    EntityUtils.consumeQuietly(response.getEntity());
}

From source file:fi.csc.shibboleth.mobileauth.impl.authn.AuthenticateMobile.java

/** {@inheritDoc} */
protected Event doExecute(@Nonnull final RequestContext springRequestContext,
        @Nonnull final ProfileRequestContext profileRequestContext) {
    log.debug("{} Entering - doExecute", getLogPrefix());

    final MobileContext mobCtx = profileRequestContext.getSubcontext(AuthenticationContext.class)
            .getSubcontext(MobileContext.class);
    final String mobileNumber = StringSupport.trimOrNull(mobCtx.getMobileNumber());
    final String spamCode = StringSupport.trimOrNull(mobCtx.getSpamCode());

    final CloseableHttpClient httpClient;
    try {//  w  ww.java 2  s  . c  o m
        log.debug("{} Trying to create httpClient", getLogPrefix());
        httpClient = createHttpClient();
    } catch (KeyStoreException | RuntimeException e) {
        log.error("{} Cannot create httpClient", getLogPrefix(), e);
        return Events.failure.event(this);
    }

    // TODO: entity initialization
    HttpEntity entity = null;
    try {
        final URIBuilder builder = new URIBuilder();
        // TODO: remove hard-codings
        builder.setScheme("https").setHost(authServer).setPort(authPort).setPath(authPath)
                .setParameter(REST_PARAM_MOBILENUMBER, mobileNumber);
        if (spamCode != null) {
            builder.setParameter(REST_PARAM_NO_SPAM_CODE, spamCode);
        }

        final URI url = builder.build();

        final HttpGet httpGet = new HttpGet(url);
        final Gson gson = new GsonBuilder().create();

        final CloseableHttpResponse response = httpClient.execute(httpGet);
        log.debug("{} Response: {}", getLogPrefix(), response);

        int statusCode = response.getStatusLine().getStatusCode();
        log.debug("{}HTTPStatusCode {}", getLogPrefix(), statusCode);

        entity = response.getEntity();

        final String json = EntityUtils.toString(entity, "UTF-8");

        final StatusResponse status = gson.fromJson(json, StatusResponse.class);

        if (status.getErrorMessage() != null) {
            log.debug("{} Setting error message", getLogPrefix());
            mobCtx.setErrorMessage(status.getErrorMessage());
        }

        response.close();

        if (statusCode == HttpStatus.SC_OK) {

            log.debug("{} Gson commKey: {}", getLogPrefix(), status.getCommunicationDataKey());
            log.debug("{} Gson EventID: {}", getLogPrefix(), status.getEventId());
            log.debug("{} Gson ErrorMessage: {}", getLogPrefix(), status.getErrorMessage());

            mobCtx.setProcessState(ProcessState.IN_PROCESS);
            mobCtx.setConversationKey(status.getCommunicationDataKey());
            mobCtx.setEventId(status.getEventId());
            mobCtx.setErrorMessage(status.getErrorMessage());
        } else if (statusCode == HttpStatus.SC_METHOD_NOT_ALLOWED) {
            mobCtx.setProcessState(ProcessState.ERROR);
            // TODO: multilingual error message
            log.warn("{} 405 - Status code {} from REST gateway", getLogPrefix(), statusCode);
            return Events.failure.event(this);
        } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            mobCtx.setProcessState(ProcessState.ERROR);
            // TODO: multilingual error message
            log.error("{} 401 - Status code {} from REST gateway - Invalid client configuration?",
                    getLogPrefix(), statusCode);
            return Events.failure.event(this);
        } else {
            mobCtx.setProcessState(ProcessState.ERROR);
            // TODO: multilingual error message
            log.warn("{} Status code {} from REST gateway", getLogPrefix(), statusCode);
            return Events.gatewayError.event(this);
        }

    } catch (Exception e) {
        // TODO: better exception handling
        log.error("Exception: {}", e);
        ActionSupport.buildEvent(profileRequestContext, AuthnEventIds.AUTHN_EXCEPTION);
        return Events.failure.event(this);
    } finally {
        EntityUtils.consumeQuietly(entity);
    }

    return Events.success.event(this);
}

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

/**
 * Forces the user with Connection <code>connectionId</code> to leave the
 * session. OpenVidu Browser will trigger the proper events on the client-side
 * (<code>streamDestroyed</code>, <code>connectionDestroyed</code>,
 * <code>sessionDisconnected</code>) with reason set to
 * "forceDisconnectByServer" <br>/*from  w w  w .  ja  v a 2 s .co m*/
 * 
 * You can get <code>connectionId</code> parameter with
 * {@link io.openvidu.java.client.Session#fetch()} (use
 * {@link io.openvidu.java.client.Connection#getConnectionId()} to get the
 * `connectionId` you want)
 * 
 * @throws OpenViduJavaClientException
 * @throws OpenViduHttpException
 */
public void forceDisconnect(String connectionId) throws OpenViduJavaClientException, OpenViduHttpException {
    HttpDelete request = new HttpDelete(OpenVidu.urlOpenViduServer + OpenVidu.API_SESSIONS + "/"
            + this.sessionId + "/connection/" + connectionId);
    request.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");

    HttpResponse response = null;
    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)) {
            // Remove connection from activeConnections map
            Connection connectionClosed = this.activeConnections.remove(connectionId);
            // Remove every Publisher of the closed connection from every subscriber list of
            // other connections
            if (connectionClosed != null) {
                for (Publisher publisher : connectionClosed.getPublishers()) {
                    String streamId = publisher.getStreamId();
                    for (Connection connection : this.activeConnections.values()) {
                        connection.setSubscribers(connection.getSubscribers().stream()
                                .filter(subscriber -> !streamId.equals(subscriber))
                                .collect(Collectors.toList()));
                    }
                }
            } else {
                log.warn(
                        "The closed connection wasn't fetched in OpenVidu Java Client. No changes in the collection of active connections of the Session");
            }
            log.info("Connection {} closed", connectionId);
        } else {
            throw new OpenViduHttpException(statusCode);
        }
    } finally

    {
        EntityUtils.consumeQuietly(response.getEntity());
    }
}

From source file:fi.csc.shibboleth.mobileauth.impl.authn.ResolveAuthenticationStatus.java

/**
 * Fetch status update from the backend//from  www .j  a  va 2s .c om
 * 
 * @param conversationKey
 * @param profileCtx
 * @param mobCtx
 */
private void getStatusUpdate(String conversationKey, ProfileRequestContext profileCtx, MobileContext mobCtx) {
    log.debug("{} Getting statusUpdate for convKey {}", getLogPrefix(), conversationKey);

    final CloseableHttpClient httpClient;
    try {
        log.debug("{} Trying to create httpClient", getLogPrefix());
        httpClient = createHttpClient();
    } catch (KeyStoreException | RuntimeException e) {
        log.error("{} Cannot create httpClient", getLogPrefix(), e);
        ActionSupport.buildEvent(profileCtx, EventIds.RUNTIME_EXCEPTION);
        return;
    }

    HttpEntity entity = null;

    try {
        final URIBuilder builder = new URIBuilder();
        builder.setScheme("https").setHost(authServer).setPort(authPort).setPath(statusPath)
                .setParameter("communicationDataKey", conversationKey);

        final URI url = builder.build();
        log.debug("{} getStatus URL: {}", getLogPrefix(), url.toURL());

        final HttpGet httpGet = new HttpGet(url);
        final Gson gson = new GsonBuilder().create();

        final CloseableHttpResponse response = httpClient.execute(httpGet);
        log.debug("{} Response: {}", getLogPrefix(), response);

        int statusCode = response.getStatusLine().getStatusCode();
        log.debug("{}HTTPStatusCode {}", getLogPrefix(), statusCode);

        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            log.error("{} Authentication failed for {} with error [{}]", getLogPrefix(),
                    mobCtx.getMobileNumber(), statusCode);
            mobCtx.setProcessState(ProcessState.ERROR);
            ActionSupport.buildEvent(profileCtx, EventIds.RUNTIME_EXCEPTION);
            return;
        }

        if (statusCode == HttpStatus.SC_OK) {

            entity = response.getEntity();
            final String json = EntityUtils.toString(entity, "UTF-8");

            final StatusResponse status = gson.fromJson(json, StatusResponse.class);

            log.debug("{} Gson commKey: {}", getLogPrefix(), status.getCommunicationDataKey());
            log.debug("{} Gson EventID: {}", getLogPrefix(), status.getEventId());
            log.debug("{} Gson ErrorMessage: {}", getLogPrefix(), status.getErrorMessage());

            response.close();

            final Map<String, String> attributes = status.getAttributes();

            if (status.getErrorMessage() == null && !MapUtils.isEmpty(attributes)) {

                log.info("{} Authentication completed for {}", getLogPrefix(), mobCtx.getMobileNumber());
                mobCtx.setProcessState(ProcessState.COMPLETE);
                mobCtx.setAttributes(status.getAttributes());

                if (log.isDebugEnabled()) {
                    for (Map.Entry<String, String> attr : status.getAttributes().entrySet()) {
                        log.debug("Attr: {} - Value: {}", attr.getKey(), attr.getValue());
                    }
                }

            } else if (status.getErrorMessage() != null) {
                log.info("{} Authentication failed for {} with error [{}]", getLogPrefix(),
                        mobCtx.getMobileNumber(), status.getErrorMessage());
                mobCtx.setProcessState(ProcessState.ERROR);
                mobCtx.setErrorMessage(status.getErrorMessage());
            } else {
                log.info("{} Authentication in process for {}", getLogPrefix(), mobCtx.getMobileNumber());
                mobCtx.setProcessState(ProcessState.IN_PROCESS);
            }

        } else {
            mobCtx.setProcessState(ProcessState.ERROR);
            log.error("{} Unexpected status code {} from REST gateway", getLogPrefix(), statusCode);
            ActionSupport.buildEvent(profileCtx, EVENTID_GATEWAY_ERROR);
            return;
        }

    } catch (Exception e) {
        log.error("Exception: {}", e);
        ActionSupport.buildEvent(profileCtx, EventIds.RUNTIME_EXCEPTION);
        return;
    } finally {
        EntityUtils.consumeQuietly(entity);
    }

}

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

@Test
public void testCreateStream() 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 + "/Airlines('AA')/Picture";
    HttpPost request = new HttpPost(editUrl);
    request.setEntity(new ByteArrayEntity("bytecontents".getBytes(), ContentType.APPLICATION_OCTET_STREAM));
    // method not allowed
    HttpResponse response = httpSend(request, 405);
    EntityUtils.consumeQuietly(response.getEntity());
}

From source file:sachin.spider.WebSpider.java

private void handleRedirectedLink(WebURL curUrl) {
    String url = curUrl.getUrl();
    HttpGet httpget = new HttpGet(url);
    RequestConfig requestConfig = getRequestConfigWithRedirectEnabled();
    httpget.setConfig(requestConfig);//from w ww  . java 2 s  . c o m
    try {
        HttpClientContext context = HttpClientContext.create();
        long startingTime = System.currentTimeMillis();
        try (CloseableHttpResponse response = httpclient.execute(httpget, context)) {
            long endingTime = System.currentTimeMillis();
            HttpHost target = context.getTargetHost();
            List<URI> redirectLocations = context.getRedirectLocations();
            URI location = URIUtils.resolve(httpget.getURI(), target, redirectLocations);
            String redirectUrl = location.toString();
            curUrl.setRedirectTo(redirectUrl);
            curUrl.setResposneTime(((int) (endingTime - startingTime)) / 1000);
            redirectUrl = URLCanonicalizer.getCanonicalURL(redirectUrl);
            WebURL weburl = new WebURL(redirectUrl);
            weburl.addParent(curUrl);
            if (!config.links.contains(weburl)) {
                config.links.add(weburl);
            }
            try {
                if (redirectLocations != null) {
                    for (URI s : redirectLocations) {
                        String urls = URLCanonicalizer.getCanonicalURL(s.toString());
                        WebURL url1 = new WebURL(urls);
                        if (!config.links.contains(url1)) {
                            config.links.add(url1);
                        }
                    }
                }
            } catch (Exception ex) {
                Logger.getLogger(WebSpider.class.getName()).log(Level.SEVERE, null, ex);
            }
            EntityUtils.consumeQuietly(response.getEntity());
            HttpClientUtils.closeQuietly(response);
        }
    } catch (IOException | URISyntaxException ex) {
        System.out.println(curUrl.getUrl());
        curUrl.setErrorMsg(ex.toString());
        Logger.getLogger(WebSpider.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        System.out.println(curUrl.getUrl());
        curUrl.setErrorMsg(ex.toString());
        Logger.getLogger(WebSpider.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        httpget.releaseConnection();
    }
}

From source file:com.github.pascalgn.jiracli.web.HttpClient.java

private <T> T doExecute(HttpUriRequest request, boolean retry, Function<HttpEntity, T> function) {
    LOGGER.debug("Calling URL: {} [{}]", request.getURI(), request.getMethod());

    // disable XSRF check:
    if (!request.containsHeader("X-Atlassian-Token")) {
        request.addHeader("X-Atlassian-Token", "nocheck");
    }/*from  ww w.  j  a va 2 s  .  c  o  m*/

    HttpResponse response;
    try {
        response = httpClient.execute(request, httpClientContext);
    } catch (IOException e) {
        if (Thread.interrupted()) {
            LOGGER.trace("Could not call URL: {}", request.getURI(), e);
            throw new InterruptedError();
        } else {
            throw new IllegalStateException("Could not call URL: " + request.getURI(), e);
        }
    }

    LOGGER.debug("Response received ({})", response.getStatusLine().toString().trim());

    HttpEntity entity = response.getEntity();
    try {
        if (Thread.interrupted()) {
            throw new InterruptedError();
        }

        int statusCode = response.getStatusLine().getStatusCode();
        if (isSuccess(statusCode)) {
            T result;
            try {
                result = function.apply(entity, Hint.none());
            } catch (NotAuthenticatedException e) {
                if (retry) {
                    resetAuthentication();
                    setCredentials();
                    return doExecute(request, false, function);
                } else {
                    throw e.getCause();
                }
            } catch (RuntimeException e) {
                if (Thread.interrupted()) {
                    LOGGER.trace("Could not call URL: {}", request.getURI(), e);
                    throw new InterruptedError();
                } else {
                    throw e;
                }
            }

            if (Thread.interrupted()) {
                throw new InterruptedError();
            }

            return result;
        } else {
            if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
                resetAuthentication();
                if (retry) {
                    setCredentials();
                    return doExecute(request, false, function);
                } else {
                    String error = readErrorResponse(request.getURI(), entity);
                    LOGGER.debug("Unauthorized [401]: {}", error);
                    throw new AccessControlException("Unauthorized [401]: " + request.getURI());
                }
            } else if (statusCode == HttpURLConnection.HTTP_FORBIDDEN) {
                resetAuthentication();
                checkAccountLocked(response);
                if (retry) {
                    setCredentials();
                    return doExecute(request, false, function);
                } else {
                    throw new AccessControlException("Forbidden [403]: " + request.getURI());
                }
            } else {
                String status = response.getStatusLine().toString().trim();
                String message;
                if (entity == null) {
                    message = status;
                } else {
                    String error = readErrorResponse(request.getURI(), entity);
                    message = status + (error.isEmpty() ? "" : ": " + error);
                }

                if (Thread.interrupted()) {
                    throw new InterruptedError();
                }

                if (statusCode == HttpURLConnection.HTTP_NOT_FOUND) {
                    throw new NoSuchElementException(message);
                } else {
                    throw new IllegalStateException(message);
                }
            }
        }
    } finally {
        EntityUtils.consumeQuietly(entity);
    }
}

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

@Test
public void testCreateStream2() 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 + "/Airlines('AA')/Picture";
    HttpPut request = new HttpPut(editUrl);
    request.setEntity(new ByteArrayEntity("bytecontents".getBytes(), ContentType.APPLICATION_OCTET_STREAM));
    HttpResponse response = httpSend(request, 204);
    EntityUtils.consumeQuietly(response.getEntity());
}