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.erudika.para.i18n.OXRCurrencyConverter.java

@SuppressWarnings("unchecked")
private Sysprop fetchFxRatesJSON() {
    Map<String, Object> map = new HashMap<String, Object>();
    Sysprop s = new Sysprop();
    ObjectReader reader = ParaObjectUtils.getJsonReader(Map.class);

    try {/*from  w ww .j  a v a2 s .com*/
        CloseableHttpClient http = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(SERVICE_URL);
        HttpResponse res = http.execute(httpGet);
        HttpEntity entity = res.getEntity();

        if (entity != null && Utils.isJsonType(entity.getContentType().getValue())) {
            JsonNode jsonNode = reader.readTree(entity.getContent());
            if (jsonNode != null) {
                JsonNode rates = jsonNode.get("rates");
                if (rates != null) {
                    map = reader.treeToValue(rates, Map.class);
                    s.setId(FXRATES_KEY);
                    s.setProperties(map);
                    //                  s.addProperty("fetched", Utils.formatDate("dd MM yyyy HH:mm", Locale.UK));
                    dao.create(s);
                }
            }
            EntityUtils.consume(entity);
        }
        logger.debug("Fetched rates from OpenExchange for {}.", new Date().toString());
    } catch (Exception e) {
        logger.error("TimerTask failed: {}", e);
    }
    return s;
}

From source file:org.aksw.dice.eaglet.uri.impl.WikipidiaUriChecker.java

public String queryRedirect(String domain, String title) {
    StringBuilder urlBuilder = new StringBuilder(150);
    urlBuilder.append(URL_PROTOCOL_PART);
    urlBuilder.append(domain);/* ww w .  jav a 2 s. com*/
    urlBuilder.append(URL_QUERY_PART);
    urlBuilder.append(TITLE_ESCAPER.escape(title));

    HttpGet request = null;
    try {
        request = createGetRequest(urlBuilder.toString());
    } catch (IllegalArgumentException e) {
        LOGGER.error("Got an exception while creating a request querying the wiki api of \"" + domain
                + "\". Returning null.", e);
        return null;
    }
    CloseableHttpResponse response = null;
    HttpEntity entity = null;
    try {
        response = sendRequest(request);
        entity = response.getEntity();
        return IOUtils.toString(entity.getContent(), charset);
    } catch (Exception e) {
        LOGGER.error("Got an exception while querying the wiki api of \"" + domain + "\". Returning null.", e);
        return null;
    } finally {
        if (entity != null) {
            try {
                EntityUtils.consume(entity);
            } catch (IOException e1) {
            }
        }
        IOUtils.closeQuietly(response);
        closeRequest(request);
    }
}

From source file:org.sakaiproject.contentreview.urkund.util.UrkundAPIUtil.java

public static String getFileInfo(String baseUrl, String externalId, String receiverAddress,
        String urkundUsername, String urkundPassword, int timeout) {
    String ret = null;/*from  w  w  w.j  a va 2s  . com*/
    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(timeout);
    requestBuilder = requestBuilder.setConnectionRequestTimeout(timeout);

    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultRequestConfig(requestBuilder.build());
    try (CloseableHttpClient httpClient = builder.build()) {
        HttpGet httpget = new HttpGet(baseUrl + "submissions/" + receiverAddress + "/" + externalId);

        //------------------------------------------------------------
        if (StringUtils.isNotBlank(urkundUsername) && StringUtils.isNotBlank(urkundPassword)) {
            addAuthorization(httpget, urkundUsername, urkundPassword);
        }
        //------------------------------------------------------------
        httpget.addHeader("Accept", "application/json");
        //------------------------------------------------------------

        HttpResponse response = httpClient.execute(httpget);
        HttpEntity resEntity = response.getEntity();

        if (resEntity != null) {
            ret = EntityUtils.toString(resEntity);
            EntityUtils.consume(resEntity);
        }

    } catch (IOException e) {
        log.error("ERROR getting File Info : ", e);
    }
    return ret;
}

From source file:org.wuspba.ctams.ws.ITBandResultController.java

@Test
public void testListContest() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
            .setParameter("contest", TestFixture.INSTANCE.bandContest.getId()).build();

    HttpGet httpGet = new HttpGet(uri);

    try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
        assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING);

        HttpEntity entity = response.getEntity();

        CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity);

        assertEquals(doc.getBandContestResults().size(), 1);
        testEquality(doc.getBandContestResults().get(0), TestFixture.INSTANCE.bandResult);

        EntityUtils.consume(entity);
    }/*from w ww .j  av a 2 s. c o m*/

    uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
            .setParameter("contest", TestFixture.INSTANCE.bandNonContest.getId()).build();

    httpGet = new HttpGet(uri);

    try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
        assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING);

        HttpEntity entity = response.getEntity();

        CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity);

        assertEquals(doc.getBandContestResults().size(), 0);

        EntityUtils.consume(entity);
    }
}

From source file:org.jcommon.com.facebook.utils.FacebookRequest.java

public void run() {
    HttpClient httpclient = new DefaultHttpClient();
    try {//from  w  w  w. j a v a2 s  .co m
        logger.info(Integer.valueOf("file size:" + this.in != null ? this.in.available() : 0));
        HttpPost httppost = new HttpPost(this.url_);
        MultipartEntity reqEntity = new MultipartEntity();

        FormBodyPart stream_part = new FormBodyPart(this.stream_name,
                new InputStreamBody(this.in, this.file_name));

        reqEntity.addPart(stream_part);
        for (int i = 0; i < this.keys.length; i++) {
            reqEntity.addPart(this.keys[i], new StringBody(this.values[i]));
        }

        httppost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        StatusLine status_line = response.getStatusLine();
        int responseCode = status_line.getStatusCode();

        BufferedReader http_reader = null;
        if (responseCode == 200) {
            http_reader = new BufferedReader(new InputStreamReader(resEntity.getContent(), "utf-8"));
            String line = null;
            while ((line = http_reader.readLine()) != null) {
                this.sResult.append(line);
            }
            if (this.listener_ != null)
                this.listener_.onSuccessful(this, this.sResult);
        } else if (responseCode >= 400) {
            http_reader = new BufferedReader(new InputStreamReader(resEntity.getContent(), "utf-8"));
            String line = null;
            while ((line = http_reader.readLine()) != null) {
                this.sResult.append(line);
            }
            logger.info("[URL][response][failure]" + this.sResult);
            if (this.listener_ != null)
                this.listener_.onFailure(this, this.sResult);
        } else {
            this.sResult.append("[URL][response][failure][code : " + responseCode + " ]");
            if (this.listener_ != null)
                this.listener_.onFailure(this, this.sResult);
            logger.info("[URL][response][failure][code : " + responseCode + " ]");
        }
        EntityUtils.consume(resEntity);
    } catch (UnsupportedEncodingException e) {
        logger.warn("[HttpReqeust] error:" + this.url_ + "\n" + e);
        if (this.listener_ != null)
            this.listener_.onException(this, e);
    } catch (ClientProtocolException e) {
        logger.warn("[HttpReqeust] error:" + this.url_ + "\n" + e);
        if (this.listener_ != null)
            this.listener_.onException(this, e);
    } catch (IOException e) {
        logger.warn("[HttpReqeust] error:" + this.url_ + "\n" + e);
        if (this.listener_ != null)
            this.listener_.onException(this, e);
    } finally {
        try {
            httpclient.getConnectionManager().shutdown();
        } catch (Exception ignore) {
        }
    }
}

From source file:com.sumologic.log4j.SumoLogicAppender.java

private void sendToSumo(String log) {
    HttpPost post = null;/*w w w .j a  v  a  2  s .  c  om*/
    try {
        post = new HttpPost(url);
        post.setEntity(new StringEntity(log, HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8));
        HttpResponse response = httpClient.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            LogLog.warn(String.format("Received HTTP error from Sumo Service: %d", statusCode));
        }
        //need to consume the body if you want to re-use the connection.
        EntityUtils.consume(response.getEntity());
    } catch (IOException e) {
        LogLog.warn("Could not send log to Sumo Logic", e);
        try {
            post.abort();
        } catch (Exception ignore) {
        }
    }
}

From source file:org.eclipse.lyo.testsuite.server.util.OSLCUtils.java

public static int checkOslcVersion(String url, Credentials creds, String acceptTypes)
        throws ClientProtocolException, IOException {
    getHttpClient(creds);/*  w  w w.ja  va 2  s  . c o m*/

    HttpGet httpget = new HttpGet(url);
    //Get the response and return it, accept only service provider catalogs & description documents
    httpget.setHeader("Accept", acceptTypes);
    httpget.setHeader("OSLC-Core-Version", "2.0");
    HttpResponse response = httpclient.execute(httpget);
    EntityUtils.consume(response.getEntity());

    if (response.containsHeader("OSLC-Core-Version")
            && response.getFirstHeader("OSLC-Core-Version").getValue().equals("2.0")) {
        return 2;
    }
    return 1;
}

From source file:org.jboss.as.test.integration.jaxrs.validator.BeanValidationIntegrationTestCase.java

@Test
public void testInvalidRequestsAreAcceptedDependingOnValidationConfiguration() throws Exception {
    DefaultHttpClient client = new DefaultHttpClient(new PoolingClientConnectionManager());

    HttpGet get = new HttpGet(url + "myjaxrs/yet-another-validate/3/disabled");
    HttpResponse result = client.execute(get);

    Assert.assertEquals("No constraint violated", 200, result.getStatusLine().getStatusCode());
    EntityUtils.consume(result.getEntity());

    get = new HttpGet(url + "myjaxrs/yet-another-validate/3/enabled");
    result = client.execute(get);/*from w w  w  .j  a va  2 s  .c  o  m*/

    Assert.assertEquals("Parameter constraint violated", 400, result.getStatusLine().getStatusCode());
}

From source file:org.jboss.as.test.integration.web.security.jaspi.WebSecurityJaspiWithFailingAuthModuleTestCase.java

protected void makeCall(String user, String pass, int expectedStatusCode) throws Exception {
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()),
            new UsernamePasswordCredentials(user, pass));

    try (CloseableHttpClient httpclient = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(credentialsProvider).build()) {
        HttpGet httpget = new HttpGet(url.toExternalForm() + "secured/");

        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        StatusLine statusLine = response.getStatusLine();
        assertEquals(expectedStatusCode, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    }//from w  w w.  ja  v a  2s. c  o m
}

From source file:su.fmi.photoshareclient.remote.ImageHandler.java

public static void uploadImage(File img) {

    try {//w w w. ja  v  a2  s.c  om
        HttpClient httpclient = HttpClientBuilder.create().build();

        ProjectProperties props = new ProjectProperties();
        String endpoint = "http://" + props.get("socket") + props.get("restEndpoint") + "/image/create";
        HttpPost httppost = new HttpPost(endpoint);

        MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create();
        ContentBody cbFile = new FileBody(img, ContentType.MULTIPART_FORM_DATA, img.getName());
        mpEntity.addTextBody("fileName", img.getName());
        mpEntity.addTextBody("description", "File uploaded via Photoshare Desktop Cliend on "
                + new SimpleDateFormat("HH:mm dd/MM/yyyy").format(Calendar.getInstance().getTime()));

        mpEntity.addPart("fileUpload", cbFile);

        httppost.setHeader("Authorization", "Basic " + LoginHandler.getAuthStringEncripted());

        httppost.setEntity(mpEntity.build());
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        if (resEntity != null) {
            System.out.println(EntityUtils.toString(resEntity));
        }
        if (resEntity != null) {
            EntityUtils.consume(resEntity);
        }

        httppost.releaseConnection();
    } catch (IOException ex) {
        Logger.getLogger(ImageHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
}