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.juneau.rest.client.RestCall.java

/** Use close() */
@Deprecated
public void consumeResponse() {
    if (response != null)
        EntityUtils.consumeQuietly(response.getEntity());
}

From source file:org.apache.juneau.rest.client.RestCall.java

/**
 * Cleans up this HTTP call.//from  ww  w .j  a  v  a 2 s.c o m
 *
 * @return This object (for method chaining).
 * @throws RestCallException Can be thrown by one of the {@link RestCallInterceptor#onClose(RestCall)} calls.
 */
public RestCall close() throws RestCallException {
    if (response != null)
        EntityUtils.consumeQuietly(response.getEntity());
    isClosed = true;
    if (!isFailed)
        for (RestCallInterceptor r : interceptors)
            r.onClose(this);
    return this;
}

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

@Test
public void testDisseminationContentLengthWhenKnown() throws Exception {
    URI url = getURI("/objects/demo:14/methods/demo:12/getDocument");
    HttpGet get = new HttpGet(url);
    HttpResponse response;/*from   w  w w . jav a 2  s  .c o  m*/
    verifyNoAuthFailOnAPIAAuth(url);
    // default to validated response
    response = getOrDelete(get, getAuthAccess(), true);
    int status = response.getStatusLine().getStatusCode();
    String cLen = (response.containsHeader(HttpHeaders.CONTENT_LENGTH))
            ? response.getFirstHeader(HttpHeaders.CONTENT_LENGTH).getValue()
            : null;
    EntityUtils.consumeQuietly(response.getEntity());
    get.releaseConnection();
    assertEquals(SC_OK, status);
    assertEquals("19498", cLen);
}

From source file:org.keycloak.testsuite.adapter.servlet.SAMLServletAdapterTest.java

@Test
public void testEmptyKeyInfoElement() {
    log.debug("Log in using idp initiated login");
    SAMLDocumentHolder documentHolder = new SamlClientBuilder()
            .idpInitiatedLogin(getAuthServerSamlEndpoint(SAMLSERVLETDEMO), "sales-post-sig-email").build()
            .login().user(bburkeUser).build().getSamlResponse(Binding.POST);

    log.debug("Removing KeyInfo from Keycloak response");
    Document responseDoc = documentHolder.getSamlDocument();
    IOUtil.removeElementFromDoc(responseDoc, "samlp:Response/dsig:Signature/dsig:KeyInfo");

    CloseableHttpResponse response = null;
    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        HttpClientContext context = HttpClientContext.create();

        log.debug("Sending response to SP");
        HttpUriRequest post = SamlClient.Binding.POST.createSamlUnsignedResponse(
                getAppServerSamlEndpoint(salesPostSigEmailServletPage), null, responseDoc);
        response = client.execute(post, context);
        System.out.println(EntityUtils.toString(response.getEntity()));
        Assert.assertThat(response, statusCodeIsHC(Response.Status.FOUND));
        response.close();//w w  w . j a v  a  2 s. c  o  m

        HttpGet get = new HttpGet(salesPostSigEmailServletPage.toString());
        response = client.execute(get);
        Assert.assertThat(response, statusCodeIsHC(Response.Status.OK));
        Assert.assertThat(response, bodyHC(containsString("principal=bburke")));
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        if (response != null) {
            EntityUtils.consumeQuietly(response.getEntity());
            try {
                response.close();
            } catch (IOException ex) {
            }
        }
    }
}

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

@Deprecated
protected HttpResponse put(URI url, File requestContent, boolean authenticate) throws Exception {
    HttpPut method = new HttpPut(url);
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("param_name", new StringBody("value"));
    entity.addPart(((File) requestContent).getName(), new FileBody((File) requestContent));
    HttpResponse response = putOrPost(method, entity, authenticate);
    int status = response.getStatusLine().getStatusCode();
    if (status == SC_MOVED_TEMPORARILY) {
        String original = url.toString();
        url = URI.create(response.getFirstHeader(HttpHeaders.LOCATION).getValue());
        if (!original.equals(url.toString())) {
            EntityUtils.consumeQuietly(response.getEntity());
            method = new HttpPut(url);
            entity = new MultipartEntity();
            entity.addPart("param_name", new StringBody("value"));
            entity.addPart(((File) requestContent).getName(), new FileBody((File) requestContent));
            response = putOrPost(method, entity, true);
        }//from www  .j a v a 2  s  .  c o m
    }

    return response;
}

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

@Deprecated
protected HttpResponse post(URI url, File requestContent, boolean authenticate) throws Exception {
    HttpPost method = new HttpPost(url);
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("param_name", new StringBody("value"));
    entity.addPart(((File) requestContent).getName(), new FileBody((File) requestContent));
    HttpResponse response = putOrPost(method, entity, authenticate);
    int status = response.getStatusLine().getStatusCode();
    if (status == SC_MOVED_TEMPORARILY) {
        String original = url.toString();
        url = URI.create(response.getFirstHeader(HttpHeaders.LOCATION).getValue());
        if (!original.equals(url.toString())) {
            EntityUtils.consumeQuietly(response.getEntity());
            method = new HttpPost(url);
            entity = new MultipartEntity();
            entity.addPart("param_name", new StringBody("value"));
            entity.addPart(((File) requestContent).getName(), new FileBody((File) requestContent));
            response = putOrPost(method, entity, true);
        }/*from   ww  w .j  av a  2 s.c o m*/
    }

    return response;
}

From source file:org.alfresco.json.JSONUtil.java

/**
 * Parses http response stream into a {@link JSONObject}.
 * /*from w ww.  j a va  2  s . c om*/
 * @param stream Http response entity
 * @return {@link JSONObject} response
 */
public static JSONObject readStream(final HttpEntity entity) {
    String rsp = null;
    try {
        rsp = EntityUtils.toString(entity, "UTF-8");
    } catch (Throwable ex) {
        throw new RuntimeException("Failed to read HTTP entity stream.", ex);
    } finally {
        EntityUtils.consumeQuietly(entity);
    }
    try {
        JSONParser parser = new JSONParser();
        JSONObject result = (JSONObject) parser.parse(rsp);
        return result;
    } catch (Throwable e) {
        throw new RuntimeException("Failed to convert response to JSON: \n" + "   Response: \r\n" + rsp, e);
    }
}

From source file:org.apache.http.impl.client.cache.CachingHttpAsyncClient.java

void negotiateResponseFromVariants(final BasicFuture<HttpResponse> future, final HttpHost target,
        final HttpRequestWrapper request, final HttpCacheContext clientContext,
        final Map<String, Variant> variants) {
    final HttpRequest conditionalRequest = this.conditionalRequestBuilder
            .buildConditionalRequestFromVariants(request, variants);

    final Date requestDate = getCurrentDate();

    final ChainedFutureCallback<HttpResponse> chainedFutureCallback = new ChainedFutureCallback<HttpResponse>(
            future) {//  w ww  . j  a v a 2s.  c  o  m

        @Override
        public void completed(final HttpResponse httpResponse) {
            final Date responseDate = getCurrentDate();

            httpResponse.addHeader(HeaderConstants.VIA, generateViaHeader(httpResponse));

            if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_NOT_MODIFIED) {
                try {
                    future.completed(handleBackendResponse(target, request, requestDate, responseDate,
                            Proxies.enhanceResponse(httpResponse)));
                    return;
                } catch (final IOException e) {
                    future.failed(e);
                    return;
                }
            }

            final Header resultEtagHeader = httpResponse.getFirstHeader(HeaderConstants.ETAG);
            if (resultEtagHeader == null) {
                CachingHttpAsyncClient.this.log.warn("304 response did not contain ETag");
                callBackend(future, target, request, clientContext);
                return;
            }

            final String resultEtag = resultEtagHeader.getValue();
            final Variant matchingVariant = variants.get(resultEtag);
            if (matchingVariant == null) {
                CachingHttpAsyncClient.this.log
                        .debug("304 response did not contain ETag matching one sent in If-None-Match");
                callBackend(future, target, request, clientContext);
            }

            final HttpCacheEntry matchedEntry = matchingVariant.getEntry();

            if (revalidationResponseIsTooOld(httpResponse, matchedEntry)) {
                EntityUtils.consumeQuietly(httpResponse.getEntity());
                retryRequestUnconditionally(future, target, request, clientContext, matchedEntry);
                return;
            }

            recordCacheUpdate(clientContext);

            final HttpCacheEntry responseEntry = getUpdatedVariantEntry(target, conditionalRequest, requestDate,
                    responseDate, httpResponse, matchingVariant, matchedEntry);

            final HttpResponse resp = CachingHttpAsyncClient.this.responseGenerator.generateResponse(request,
                    responseEntry);
            tryToUpdateVariantMap(target, request, matchingVariant);

            if (shouldSendNotModifiedResponse(request, responseEntry)) {
                future.completed(CachingHttpAsyncClient.this.responseGenerator
                        .generateNotModifiedResponse(responseEntry));
                return;
            }

            future.completed(resp);
        }

    };

    this.backend.execute(target, conditionalRequest, clientContext, chainedFutureCallback);
}

From source file:org.apache.sentry.tests.e2e.solr.AbstractSolrSentryTestBase.java

/**
 * Make a raw http request to specific cluster node.  Node is of the format
 * host:port/context, i.e. "localhost:8983/solr"
 *//*from   w w  w. ja v a 2s .  c  om*/
protected String makeHttpRequest(CloudSolrServer server, String node, String httpMethod, String path,
        byte[] content, String contentType) throws Exception {
    HttpClient httpClient = server.getLbServer().getHttpClient();
    URI uri = new URI("http://" + node + path);
    HttpRequestBase method = null;
    if ("GET".equals(httpMethod)) {
        method = new HttpGet(uri);
    } else if ("HEAD".equals(httpMethod)) {
        method = new HttpHead(uri);
    } else if ("POST".equals(httpMethod)) {
        method = new HttpPost(uri);
    } else if ("PUT".equals(httpMethod)) {
        method = new HttpPut(uri);
    } else {
        throw new IOException("Unsupported method: " + method);
    }

    if (method instanceof HttpEntityEnclosingRequestBase) {
        HttpEntityEnclosingRequestBase entityEnclosing = (HttpEntityEnclosingRequestBase) method;
        ByteArrayEntity entityRequest = new ByteArrayEntity(content);
        entityRequest.setContentType(contentType);
        entityEnclosing.setEntity(entityRequest);
    }

    HttpEntity httpEntity = null;
    boolean success = false;
    String retValue = "";
    try {
        final HttpResponse response = httpClient.execute(method);
        int httpStatus = response.getStatusLine().getStatusCode();
        httpEntity = response.getEntity();

        if (httpEntity != null) {
            InputStream is = httpEntity.getContent();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            try {
                IOUtils.copyLarge(is, os);
                os.flush();
            } finally {
                IOUtils.closeQuietly(os);
                IOUtils.closeQuietly(is);
            }
            retValue = os.toString();
        }
        success = true;
    } finally {
        if (!success) {
            EntityUtils.consumeQuietly(httpEntity);
            method.abort();
        }
    }
    return retValue;
}

From source file:org.apache.sentry.tests.e2e.solr.AbstractSolrSentryTestCase.java

/**
 * Make a raw http request to specific cluster node.  Node is of the format
 * host:port/context, i.e. "localhost:8983/solr"
 *///from  w ww  .  j av a  2 s. c  o  m
protected String makeHttpRequest(CloudSolrClient client, String node, String httpMethod, String path,
        byte[] content, String contentType, int expectedStatusCode) throws Exception {
    HttpClient httpClient = client.getLbClient().getHttpClient();
    URI uri = new URI("http://" + node + path);
    HttpRequestBase method = null;
    if ("GET".equals(httpMethod)) {
        method = new HttpGet(uri);
    } else if ("HEAD".equals(httpMethod)) {
        method = new HttpHead(uri);
    } else if ("POST".equals(httpMethod)) {
        method = new HttpPost(uri);
    } else if ("PUT".equals(httpMethod)) {
        method = new HttpPut(uri);
    } else {
        throw new IOException("Unsupported method: " + method);
    }

    if (method instanceof HttpEntityEnclosingRequestBase) {
        HttpEntityEnclosingRequestBase entityEnclosing = (HttpEntityEnclosingRequestBase) method;
        ByteArrayEntity entityRequest = new ByteArrayEntity(content);
        entityRequest.setContentType(contentType);
        entityEnclosing.setEntity(entityRequest);
    }

    HttpEntity httpEntity = null;
    boolean success = false;
    String retValue = "";
    try {
        final HttpResponse response = httpClient.execute(method);
        httpEntity = response.getEntity();

        assertEquals(expectedStatusCode, response.getStatusLine().getStatusCode());

        if (httpEntity != null) {
            InputStream is = httpEntity.getContent();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            try {
                IOUtils.copyLarge(is, os);
                os.flush();
            } finally {
                IOUtils.closeQuietly(os);
                IOUtils.closeQuietly(is);
            }
            retValue = os.toString();
        }
        success = true;
    } finally {
        if (!success) {
            EntityUtils.consumeQuietly(httpEntity);
            method.abort();
        }
    }
    return retValue;
}