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.eclipse.rdf4j.http.client.SPARQLProtocolSession.java

protected HttpResponse execute(HttpUriRequest method) throws IOException, RDF4JException {
    boolean consume = true;
    if (params != null) {
        method.setParams(params);/*from ww w.j av a 2  s  .c o m*/
    }
    HttpResponse response = httpClient.execute(method, httpContext);

    try {
        int httpCode = response.getStatusLine().getStatusCode();
        if (httpCode >= 200 && httpCode < 300 || httpCode == HttpURLConnection.HTTP_NOT_FOUND) {
            consume = false;
            return response; // everything OK, control flow can continue
        } else {
            switch (httpCode) {
            case HttpURLConnection.HTTP_UNAUTHORIZED: // 401
                throw new UnauthorizedException();
            case HttpURLConnection.HTTP_UNAVAILABLE: // 503
                throw new QueryInterruptedException();
            default:
                ErrorInfo errInfo = getErrorInfo(response);
                // Throw appropriate exception
                if (errInfo.getErrorType() == ErrorType.MALFORMED_DATA) {
                    throw new RDFParseException(errInfo.getErrorMessage());
                } else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_FILE_FORMAT) {
                    throw new UnsupportedRDFormatException(errInfo.getErrorMessage());
                } else if (errInfo.getErrorType() == ErrorType.MALFORMED_QUERY) {
                    throw new MalformedQueryException(errInfo.getErrorMessage());
                } else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_QUERY_LANGUAGE) {
                    throw new UnsupportedQueryLanguageException(errInfo.getErrorMessage());
                } else if (errInfo.toString().length() > 0) {
                    throw new RepositoryException(errInfo.toString());
                } else {
                    throw new RepositoryException(response.getStatusLine().getReasonPhrase());
                }
            }
        }
    } finally {
        if (consume) {
            EntityUtils.consumeQuietly(response.getEntity());
        }
    }
}

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

@Test
//KEYCLOAK-4020//from  w  w  w . j av a2  s .c o m
public void testBooleanAttribute() throws Exception {
    AuthnRequestType req = SamlClient.createLoginRequestDocument("http://localhost:8081/employee2/",
            getAppServerSamlEndpoint(employee2ServletPage).toString(),
            getAuthServerSamlEndpoint(SAMLSERVLETDEMO));
    Document doc = SAML2Request.convert(req);

    SAMLDocumentHolder res = login(bburkeUser, getAuthServerSamlEndpoint(SAMLSERVLETDEMO), doc, null,
            SamlClient.Binding.POST, SamlClient.Binding.POST);
    Document responseDoc = res.getSamlDocument();

    Element attribute = responseDoc.createElement("saml:Attribute");
    attribute.setAttribute("Name", "boolean-attribute");
    attribute.setAttribute("NameFormat", "urn:oasis:names:tc:SAML:2.0:attrname-format:basic");

    Element attributeValue = responseDoc.createElement("saml:AttributeValue");
    attributeValue.setAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema");
    attributeValue.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    attributeValue.setAttribute("xsi:type", "xs:boolean");
    attributeValue.setTextContent("true");

    attribute.appendChild(attributeValue);
    IOUtil.appendChildInDocument(responseDoc, "samlp:Response/saml:Assertion/saml:AttributeStatement",
            attribute);

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

        HttpUriRequest post = SamlClient.Binding.POST
                .createSamlUnsignedResponse(getAppServerSamlEndpoint(employee2ServletPage), null, responseDoc);
        response = client.execute(post, context);
        assertThat(response, statusCodeIsHC(Response.Status.FOUND));
        response.close();

        HttpGet get = new HttpGet(employee2ServletPage.toString() + "/getAttributes");
        response = client.execute(get);
        assertThat(response, statusCodeIsHC(Response.Status.OK));
        assertThat(response, bodyHC(containsString("boolean-attribute: true")));
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        if (response != null) {
            EntityUtils.consumeQuietly(response.getEntity());
            try {
                response.close();
            } catch (IOException ex) {
            }
        }
    }
}

From source file:com.globalsight.connector.mindtouch.util.MindTouchHelper.java

private void consumeQuietly(HttpResponse httpResponse) {
    if (httpResponse != null) {
        try {//from w  w w .  ja  v  a2  s . c  o  m
            EntityUtils.consumeQuietly(httpResponse.getEntity());
        } catch (Exception ignore) {

        }
    }
}

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

@Test
public void testEmptyKeyInfoElement() {
    samlidpInitiatedLoginPage.setAuthRealm(SAMLSERVLETDEMO);
    samlidpInitiatedLoginPage.setUrlName("sales-post-sig-email");
    System.out.println(samlidpInitiatedLoginPage.toString());
    URI idpInitiatedLoginPage = URI.create(samlidpInitiatedLoginPage.toString());

    log.debug("Log in using idp initiated login");
    SAMLDocumentHolder documentHolder = idpInitiatedLogin(bburkeUser, idpInitiatedLoginPage,
            SamlClient.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()));
        assertThat(response, statusCodeIsHC(Response.Status.FOUND));
        response.close();//from w ww. j a v  a 2  s  . c om

        HttpGet get = new HttpGet(salesPostSigEmailServletPage.toString());
        response = client.execute(get);
        assertThat(response, statusCodeIsHC(Response.Status.OK));
        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

@Test
public void testAddDatastream() throws Exception {
    // inline (X) datastream
    String xmlData = "<foo>bar</foo>";
    String dsPath = "/objects/" + DEMO_REST_PID + "/datastreams/FOO";
    URI url = getURI(dsPath + "?controlGroup=X&dsLabel=foo");
    StringEntity entity = getStringEntity(xmlData, TEXT_XML);
    verifyPOSTStatusOnly(url, SC_UNAUTHORIZED, entity, false);
    HttpPost post = new HttpPost(url);
    HttpResponse response = putOrPost(post, entity, true);
    String expected = readString(response);
    assertEquals(SC_CREATED, response.getStatusLine().getStatusCode());
    Header locationHeader = response.getFirstHeader(HttpHeaders.LOCATION);
    assertNotNull(locationHeader);// w  w w  .  ja  v a  2  s  .com
    assertEquals(getURI(dsPath), URI.create(locationHeader.getValue()));
    assertEquals(TEXT_XML, response.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
    url = getURI(dsPath + "?format=xml");
    String actual = verifyGETStatusString(url, SC_OK, true, true);
    assertEquals(expected, actual);

    // managed (M) datastream
    String mimeType = "text/plain";
    Datastream ds = apim.getDatastream(DEMO_REST_PID.toString(), "BAR", null);
    assertNull(ds);
    dsPath = "/objects/" + DEMO_REST_PID + "/datastreams/BAR";
    url = getURI(dsPath + "?controlGroup=M&dsLabel=bar&mimeType=" + mimeType);
    File temp = File.createTempFile("test", null);
    DataOutputStream os = new DataOutputStream(new FileOutputStream(temp));
    os.write(42);
    os.close();
    response = post(url, temp, false);
    EntityUtils.consumeQuietly(response.getEntity());
    assertEquals(SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
    response = post(url, temp, true);
    expected = readString(response);
    assertEquals(SC_CREATED, response.getStatusLine().getStatusCode());
    locationHeader = response.getFirstHeader(HttpHeaders.LOCATION);
    assertNotNull(locationHeader);
    assertEquals(getURI(dsPath), URI.create(locationHeader.getValue()));
    assertEquals(TEXT_XML, response.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
    url = getURI(dsPath + "?format=xml");
    actual = verifyGETStatusString(url, SC_OK, true, true);
    assertEquals(expected, actual);
    ds = apim.getDatastream(DEMO_REST_PID.toString(), "BAR", null);
    assertNotNull(ds);
    assertEquals(ds.getMIMEType(), mimeType);
}

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

@Test
public void testModifyDatastreamByReference() throws Exception {
    // Create BAR datastream
    URI url = getURI(String.format(
            "/objects/%s/datastreams/BAR?controlGroup=M&dsLabel=testModifyDatastreamByReference(bar)",
            DEMO_REST_PID.toString()));// w  w w  .j ava  2 s. c  om
    File temp = File.createTempFile("test", null);
    DataOutputStream os = new DataOutputStream(new FileOutputStream(temp));
    os.write(42);
    os.close();
    HttpResponse response = post(url, temp, false);
    EntityUtils.consumeQuietly(response.getEntity());
    assertEquals(SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
    response = post(url, temp, true);
    EntityUtils.consumeQuietly(response.getEntity());
    assertEquals(SC_CREATED, response.getStatusLine().getStatusCode());

    // Update the content of the BAR datastream (using PUT)
    url = getURI(String.format("/objects/%s/datastreams/BAR", DEMO_REST_PID.toString()));
    assertEquals(SC_UNAUTHORIZED, put(url, temp, false).getStatusLine().getStatusCode());
    response = put(url, temp, true);
    String expected = readString(response);
    assertEquals(SC_OK, response.getStatusLine().getStatusCode());
    assertEquals(TEXT_XML, response.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
    url = getURI(url.toString() + "?format=xml");
    String actual = verifyGETStatusString(url, SC_OK, true, true);
    assertEquals(expected, actual);

    // Ensure 404 on attempt to update BOGUS_DS via PUT
    url = getURI("/objects/" + DEMO_REST_PID + "/datastreams/BOGUS_DS");
    response = put(url, temp, true);
    EntityUtils.consumeQuietly(response.getEntity());
    assertEquals(SC_NOT_FOUND, response.getStatusLine().getStatusCode());

    // Update the content of the BAR datastream (using POST)
    url = getURI(String.format("/objects/%s/datastreams/BAR", DEMO_REST_PID.toString()));
    response = post(url, temp, true);
    expected = readString(response);
    assertEquals(SC_CREATED, response.getStatusLine().getStatusCode());
    Header locationHeader = response.getFirstHeader(HttpHeaders.LOCATION);
    assertNotNull(locationHeader);
    assertEquals(url.toString(), locationHeader.getValue());
    assertEquals(TEXT_XML, response.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
    url = getURI(url.toString() + "?format=xml");
    actual = verifyGETStatusString(url, SC_OK, true, true);
    assertEquals(expected, actual);

    // Update the label of the BAR datastream
    String newLabel = "tikibar";
    url = getURI(String.format("/objects/%s/datastreams/BAR?dsLabel=%s", DEMO_REST_PID.toString(), newLabel));
    verifyPUTStatusOnly(url, SC_UNAUTHORIZED, null, false);
    verifyPUTStatusOnly(url, SC_OK, null, true);
    assertEquals(newLabel, apim.getDatastream(DEMO_REST_PID.toString(), "BAR", null).getLabel());

    // Update the location of the EXTDS datastream (E type datastream)
    String newLocation = "http://" + getHost() + ":" + getPort() + "/" + getFedoraAppServerContext()
            + "/get/demo:REST/DC";
    url = getURI(String.format("/objects/%s/datastreams/EXTDS?dsLocation=%s", DEMO_REST_PID.toString(),
            newLocation));
    verifyPUTStatusOnly(url, SC_UNAUTHORIZED, null, false);
    verifyPUTStatusOnly(url, SC_OK, null, true);

    assertEquals(newLocation, apim.getDatastream(DEMO_REST_PID.toString(), "EXTDS", null).getLocation());
    String dcDS = new String(TypeUtility.convertDataHandlerToBytes(
            apia.getDatastreamDissemination(DEMO_REST_PID.toString(), "DC", null).getStream()));
    String extDS = new String(TypeUtility.convertDataHandlerToBytes(
            apia.getDatastreamDissemination(DEMO_REST_PID.toString(), "EXTDS", null).getStream()));
    assertEquals(dcDS, extDS);

    // Update DS1 by reference (X type datastream)
    // Error expected because attempting to access internal DS with API-A auth on
    if (getAuthAccess()) {
        // only ConfigB has API-A auth on
        url = getURI(String.format("/objects/%s/datastreams/DS1?dsLocation=%s", DEMO_REST_PID.toString(),
                newLocation));
        verifyPUTStatusOnly(url, SC_UNAUTHORIZED, null, false);
        verifyPUTStatusOnly(url, SC_INTERNAL_SERVER_ERROR, null, true);
    }

    // Update DS1 by reference (X type datastream) - Success expected
    newLocation = getBaseURL() + "/ri/index.xsl";
    url = getURI(
            String.format("/objects/%s/datastreams/DS1?dsLocation=%s", DEMO_REST_PID.toString(), newLocation));
    verifyPUTStatusOnly(url, SC_UNAUTHORIZED, null, false);
    verifyPUTStatusOnly(url, SC_OK, null, true);
}

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

/**
 * Connects to the REST resource.//from  w w  w .  j a  v  a2s  .c  o  m
 * <p>
 * If this is a <code>PUT</code> or <code>POST</code>, also sends the input to the remote resource.<br>
 * <p>
 * Typically, you would only call this method if you're not interested in retrieving the body of the HTTP response.
 * Otherwise, you're better off just calling one of the {@link #getReader()}/{@link #getResponse(Class)}/{@link #pipeTo(Writer)}
 *    methods directly which automatically call this method already.
 *
 * @return This object (for method chaining).
 * @throws RestCallException If an exception or <code>400+</code> HTTP status code occurred during the connection attempt.
 */
public RestCall connect() throws RestCallException {

    if (isConnected)
        return this;
    isConnected = true;

    try {

        request.setURI(uriBuilder.build());

        if (hasInput || formData != null) {

            if (hasInput && formData != null)
                throw new RestCallException("Both input and form data found on same request.");

            if (!(request instanceof HttpEntityEnclosingRequestBase))
                throw new RestCallException(0, "Method does not support content entity.", request.getMethod(),
                        request.getURI(), null);

            HttpEntity entity = null;
            if (formData != null)
                entity = new UrlEncodedFormEntity(formData);
            else if (input instanceof NameValuePairs)
                entity = new UrlEncodedFormEntity((NameValuePairs) input);
            else if (input instanceof HttpEntity)
                entity = (HttpEntity) input;
            else
                entity = new RestRequestEntity(input, getSerializer());

            if (retries > 1 && !entity.isRepeatable())
                throw new RestCallException("Rest call set to retryable, but entity is not repeatable.");

            ((HttpEntityEnclosingRequestBase) request).setEntity(entity);
        }

        int sc = 0;
        while (retries > 0) {
            retries--;
            Exception ex = null;
            try {
                response = client.execute(request);
                sc = (response == null || response.getStatusLine() == null) ? -1
                        : response.getStatusLine().getStatusCode();
            } catch (Exception e) {
                ex = e;
                sc = -1;
                if (response != null)
                    EntityUtils.consumeQuietly(response.getEntity());
            }
            if (!retryOn.onResponse(response))
                retries = 0;
            if (retries > 0) {
                for (RestCallInterceptor rci : interceptors)
                    rci.onRetry(this, sc, request, response, ex);
                request.reset();
                long w = retryInterval;
                synchronized (this) {
                    wait(w);
                }
            } else if (ex != null) {
                throw ex;
            }
        }
        for (RestCallInterceptor rci : interceptors)
            rci.onConnect(this, sc, request, response);
        if (response == null)
            throw new RestCallException("HttpClient returned a null response");
        StatusLine sl = response.getStatusLine();
        String method = request.getMethod();
        sc = sl.getStatusCode(); // Read it again in case it was changed by one of the interceptors.
        if (sc >= 400 && !ignoreErrors)
            throw new RestCallException(sc, sl.getReasonPhrase(), method, request.getURI(),
                    getResponseAsString())
                            .setServerException(response.getFirstHeader("Exception-Name"),
                                    response.getFirstHeader("Exception-Message"),
                                    response.getFirstHeader("Exception-Trace"))
                            .setHttpResponse(response);
        if ((sc == 307 || sc == 302) && allowRedirectsOnPosts && method.equalsIgnoreCase("POST")) {
            if (redirectOnPostsTries-- < 1)
                throw new RestCallException(sc,
                        "Maximum number of redirects occurred.  Location header: "
                                + response.getFirstHeader("Location"),
                        method, request.getURI(), getResponseAsString());
            Header h = response.getFirstHeader("Location");
            if (h != null) {
                reset();
                request.setURI(URI.create(h.getValue()));
                retries++; // Redirects should affect retries.
                connect();
            }
        }

    } catch (RestCallException e) {
        isFailed = true;
        try {
            close();
        } catch (RestCallException e2) {
            /* Ignore */ }
        throw e;
    } catch (Exception e) {
        isFailed = true;
        close();
        throw new RestCallException(e).setHttpResponse(response);
    }

    return this;
}

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

private void reset() {
    if (response != null)
        EntityUtils.consumeQuietly(response.getEntity());
    request.reset();/*ww w  .  j a  v  a2  s  . c o m*/
    isConnected = false;
    isClosed = false;
    isFailed = false;
    if (capturedResponseWriter != null)
        capturedResponseWriter.getBuffer().setLength(0);
}

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

@Test
public void testDatastreamDisseminationContentDispositionFromRels() throws Exception {

    // filename from RELS-INT, no lookup of extension; no download
    URI url = getURI("/objects/demo:REST/datastreams/DS1/content");
    HttpGet get = new HttpGet(url);
    HttpResponse response = getOrDelete(get, getAuthAccess(), false);
    EntityUtils.consumeQuietly(response.getEntity());
    assertEquals(SC_OK, response.getStatusLine().getStatusCode());
    CheckCDHeader(response, "inline", TestRESTAPI.DS1RelsFilename);
    // again with download
    url = getURI(url.toString() + "?download=true");
    get = new HttpGet(url);
    response = getOrDelete(get, getAuthAccess(), false);
    EntityUtils.consumeQuietly(response.getEntity());
    assertEquals(SC_OK, response.getStatusLine().getStatusCode());
    CheckCDHeader(response, "attachment", TestRESTAPI.DS1RelsFilename);
}

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

@Test
public void testDatastreamDisseminationContentDispositionFromLabel() throws Exception {

    HttpGet get;/*from w  w w  .  ja v  a 2s  .  c o  m*/
    HttpResponse response;
    int status = 0;
    // filename from label, known MIMETYPE
    URI url = getURI("/objects/demo:REST/datastreams/DS2/content?download=true");
    get = new HttpGet(url);
    response = getOrDelete(get, getAuthAccess(), false);
    status = response.getStatusLine().getStatusCode();
    EntityUtils.consumeQuietly(response.getEntity());
    assertEquals(SC_OK, status);
    CheckCDHeader(response, "attachment", TestRESTAPI.DS2LabelFilename + ".jpg"); // jpg should be from MIMETYPE mapping

    // filename from label, unknown MIMETYPE
    url = getURI("/objects/demo:REST/datastreams/DS3/content?download=true");
    get = new HttpGet(url);
    response = getOrDelete(get, getAuthAccess(), false);
    status = response.getStatusLine().getStatusCode();
    EntityUtils.consumeQuietly(response.getEntity());
    assertEquals(SC_OK, status);
    CheckCDHeader(response, "attachment", TestRESTAPI.DS3LabelFilename + ".bin"); // default extension from config

    // filename from label with illegal characters, known MIMETYPE
    url = getURI("/objects/demo:REST/datastreams/DS4/content?download=true");
    get = new HttpGet(url);
    response = getOrDelete(get, getAuthAccess(), false);
    status = response.getStatusLine().getStatusCode();
    EntityUtils.consumeQuietly(response.getEntity());
    assertEquals(SC_OK, status);
    CheckCDHeader(response, "attachment", TestRESTAPI.DS4LabelFilename + ".xml"); // xml from mimetype mapping
}