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

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

Introduction

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

Prototype

public static void consume(HttpEntity httpEntity) throws IOException 

Source Link

Usage

From source file:com.zazuko.wikidata.municipalities.SparqlClient.java

List<Map<String, RDFTerm>> queryResultSet(final String query) throws IOException, URISyntaxException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    URIBuilder builder = new URIBuilder(endpoint);
    builder.addParameter("query", query);
    HttpGet httpGet = new HttpGet(builder.build());
    /*List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("query", query));
    httpGet.setEntity(new UrlEncodedFormEntity(nvps));*/
    CloseableHttpResponse response2 = httpclient.execute(httpGet);

    try {/*w ww.  j  a  va  2  s  . c o  m*/
        HttpEntity entity2 = response2.getEntity();
        InputStream in = entity2.getContent();
        if (debug) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            for (int ch = in.read(); ch != -1; ch = in.read()) {
                System.out.print((char) ch);
                baos.write(ch);
            }
            in = new ByteArrayInputStream(baos.toByteArray());
        }
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        SAXParser saxParser = spf.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        final SparqlsResultsHandler sparqlsResultsHandler = new SparqlsResultsHandler();
        xmlReader.setContentHandler(sparqlsResultsHandler);
        xmlReader.parse(new InputSource(in));
        /*
         for (int ch = in.read(); ch != -1; ch = in.read()) {
         System.out.print((char)ch);
         }
         */
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity2);
        return sparqlsResultsHandler.getResults();
    } catch (ParserConfigurationException ex) {
        throw new RuntimeException(ex);
    } catch (SAXException ex) {
        throw new RuntimeException(ex);
    } finally {
        response2.close();
    }

}

From source file:org.wso2.carbon.appfactory.apiManager.integration.APIManagerIntegrationService.java

/**
 * Method to login API Manager. Login is done using given {@code httpClient}
 * so it gets authenticated./*from  ww w  . jav  a  2  s .  c  o  m*/
 * Use the same client for further processing.
 * Otherwise Authentication failure will occur.
 * 
 * @param endpoint
 * @param httpClient
 * @throws AppFactoryException
 */
private void login(String endpoint, HttpClient httpClient, String samlToken) throws AppFactoryException {

    // We expect an encoded saml token.
    if (samlToken == null || samlToken.equals("")) {
        String msg = "Unable to get the SAML token";
        log.error(msg);
        throw new AppFactoryException(msg);
    }

    URL apiManagerUrl = getApiManagerURL();

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

    parameters.add(new BasicNameValuePair(ACTION, "loginWithSAMLToken"));
    parameters.add(new BasicNameValuePair("samlToken", samlToken));

    HttpPost postMethod = createHttpPostRequest(apiManagerUrl, parameters, endpoint);
    HttpResponse response = executeHttpMethod(httpClient, postMethod);

    try {
        EntityUtils.consume(response.getEntity());
    } catch (IOException e) {
        String msg = "Failed to consume http response";
        log.error(msg, e);
        throw new AppFactoryException(msg, e);
    }
}

From source file:com.bigdata.rdf.sail.webapp.client.BackgroundTupleResult.java

@Override
public void run() {
    synchronized (closeLock) {
        if (closed) {
            // Result was closed before it was run.
            // Need to unblock latch
            bindingNamesReady.countDown();
            return;
        }/* w  ww.  ja v a  2  s . c  o m*/
        parserThread = Thread.currentThread();
    }
    boolean completed = false;
    try {
        parser.setTupleQueryResultHandler(this);
        parser.parse(in);
        // release connection back into pool if all results have been read
        EntityUtils.consume(entity);
        completed = true;
    } catch (TupleQueryResultHandlerException e) {
        // parsing cancelled or interrupted
    } catch (QueryResultParseException e) {
        queue.toss(e);
    } catch (IOException e) {
        queue.toss(e);
    } finally {
        synchronized (closeLock) {
            parserThread = null;
        }
        queue.done();
        bindingNamesReady.countDown();
        if (!completed) {
            try {
                EntityUtils.consume(entity);
            } catch (IOException ex) {
            }
        }
    }
}

From source file:org.apache.camel.component.http4.HttpPollingConsumer.java

protected Exchange doReceive(int timeout) {
    Exchange exchange = endpoint.createExchange();
    HttpRequestBase method = createMethod(exchange);

    // set optional timeout in millis
    if (timeout > 0) {
        HttpConnectionParams.setSoTimeout(method.getParams(), timeout);
    }/*from  w w w .j av a2 s . c  o  m*/

    HttpEntity responeEntity = null;
    try {
        // execute request
        HttpResponse response = httpClient.execute(method);
        int responseCode = response.getStatusLine().getStatusCode();
        responeEntity = response.getEntity();
        Object body = HttpHelper.readResponseBodyFromInputStream(responeEntity.getContent(), exchange);

        // lets store the result in the output message.
        Message message = exchange.getOut();
        message.setBody(body);

        // lets set the headers
        Header[] headers = response.getAllHeaders();
        HeaderFilterStrategy strategy = endpoint.getHeaderFilterStrategy();
        for (Header header : headers) {
            String name = header.getName();
            // mapping the content-type
            if (name.toLowerCase().equals("content-type")) {
                name = Exchange.CONTENT_TYPE;
            }
            String value = header.getValue();
            if (strategy != null && !strategy.applyFilterToExternalHeaders(name, value, exchange)) {
                message.setHeader(name, value);
            }
        }
        message.setHeader(Exchange.HTTP_RESPONSE_CODE, responseCode);

        return exchange;
    } catch (IOException e) {
        throw new RuntimeCamelException(e);
    } finally {
        if (responeEntity != null) {
            try {
                EntityUtils.consume(responeEntity);
            } catch (IOException e) {
                // nothing what we can do
            }
        }
    }
}

From source file:com.github.jrrdev.mantisbtsync.core.common.auth.PortalAuthManager.java

/**
 * Close the http connection.// ww  w .  j  a v  a 2s .  c  o  m
 *
 * @throws IOException
 */
public void close() throws IOException {
    authCookie = null;

    if (lastResponse != null) {
        final HttpEntity entity = lastResponse.getEntity();
        EntityUtils.consume(entity);

        lastResponse.close();
        lastResponse = null;
    }

    if (client != null) {
        client.close();
        client = null;
    }
}

From source file:com.rackspacecloud.blueflood.inputs.handlers.HttpHandlerIntegrationTest.java

@Test
public void testHttpIngestionHappyCase() throws Exception {

    String postfix = getPostfix();

    long start = System.currentTimeMillis() - TIME_DIFF_MS;
    long end = System.currentTimeMillis() + TIME_DIFF_MS;

    HttpResponse response = postGenMetric(TENANT_ID, postfix, postPath);
    MetricsRW metricsRW = IOContainer.fromConfig().getBasicMetricsRW();

    try {/*from w  w w.  ja  v a  2  s  . c o  m*/
        assertEquals(200, response.getStatusLine().getStatusCode());
        verify(context, atLeastOnce()).update(anyLong(), anyInt());
        // assert that the update method on the ScheduleContext object was called and completed successfully
        // Now read the metrics back from cass and check (relies on generareJSONMetricsData from JSONMetricsContainerTest)
        final Locator locator = Locator.createLocatorFromPathComponents("acTEST", "mzord.duration" + postfix);
        Points<SimpleNumber> points = metricsRW.getDataToRollup(locator, RollupType.BF_BASIC,
                new Range(start, end), CassandraModel.getBasicColumnFamilyName(Granularity.FULL));
        assertEquals(1, points.getPoints().size());
    } finally {
        EntityUtils.consume(response.getEntity()); // Releases connection apparently
    }
}

From source file:org.wso2.carbon.bpmn.extensions.rest.SyncInvokeTask.java

private void executeGet(DelegateExecution execution) {
    HttpGet httpGet = null;//w w w .  j  a v a  2  s.  c o  m
    CloseableHttpResponse response = null;
    try {
        httpGet = new HttpGet(serviceURL.getValue(execution).toString());

        response = client.execute(httpGet);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        String outVarName = vout.getValue(execution).toString();
        String output = result.toString();
        execution.setVariable(outVarName, output);

        EntityUtils.consume(response.getEntity());

    } catch (Exception e) {
        log.error("Failed to execute GET " + serviceURL.getValue(execution).toString(), e);
    } finally {
        try {
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            log.error("Failed to close HTTP response after invoking: GET "
                    + serviceURL.getValue(execution).toString(), e);
        }

        if (httpGet != null) {
            httpGet.releaseConnection();
        }
    }
}

From source file:org.wso2.apim.billing.clients.APIRESTClient.java

public ArrayList<String> getApplications() throws Exception {
    response = sendGetRequest(appListUrl + "?action=getApplications");
    String res = getResponseBody(response);
    EntityUtils.consume(response.getEntity());
    JSONObject resObj = new JSONObject(res);
    JSONArray appArr = resObj.getJSONArray("applications");
    ArrayList<String> list = new ArrayList<String>();

    for (int i = 0; i < appArr.length(); i++) {
        list.add(appArr.getJSONObject(i).getString("name"));
    }/*from w w w .j  a v a2  s  .  co  m*/
    return list;
}

From source file:org.jets3t.service.impl.rest.httpclient.HttpMethodReleaseInputStream.java

/**
 * Forces the release of an HttpMethod's connection in a way that will perform all the necessary
 * cleanup through the correct use of HttpClient methods.
 *
 * @throws IOException//from  w  w w .  ja  v  a2s  .c om
 */
protected void releaseConnection() throws IOException {
    if (!alreadyReleased) {
        if (!underlyingStreamConsumed) {
            // Underlying input stream has not been consumed,
            // trigger connection close and clean-up.
            EntityUtils.consume(httpResponse.getEntity());
        }
        alreadyReleased = true;
    }
}

From source file:org.greencheek.spring.rest.SSLCachingHttpComponentsClientHttpResponse.java

public void close() {
    HttpEntity entity = this.httpResponse.getEntity();
    if (entity != null) {
        try {//from w  w  w .java 2  s.  c o  m
            // Release underlying connection back to the connection manager
            EntityUtils.consume(entity);
        } catch (IOException e) {
            // ignore
        }
    }
}