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:org.eclipse.lyo.testsuite.server.oslcv1tests.ServiceProviderCatalogTests.java

public static Collection<Object[]> getReferencedCatalogUrls(String base)
        throws IOException, ParserConfigurationException, SAXException, XPathException {
    Properties setupProps = SetupProperties.setup(null);
    String userId = setupProps.getProperty("userId");
    String pw = setupProps.getProperty("pw");

    HttpResponse resp = OSLCUtils.getResponseFromUrl(base, base, new UsernamePasswordCredentials(userId, pw),
            OSLCConstants.CT_DISC_CAT_XML);
    //If we're not looking at a catalog, return empty list.
    if (!resp.getEntity().getContentType().getValue().contains(OSLCConstants.CT_DISC_CAT_XML)) {
        System.out.println("The url: " + base + " does not refer to a ServiceProviderCatalog.");
        System.out.println(/* w ww. ja  v a2s.c  om*/
                "The content-type of a ServiceProviderCatalog should be " + OSLCConstants.CT_DISC_CAT_XML);
        System.out.println("The content-type returned was " + resp.getEntity().getContentType());
        EntityUtils.consume(resp.getEntity());
        return new ArrayList<Object[]>();
    }
    Document baseDoc = OSLCUtils.createXMLDocFromResponseBody(EntityUtils.toString(resp.getEntity()));

    //ArrayList to contain the urls from all SPCs
    Collection<Object[]> data = new ArrayList<Object[]>();
    data.add(new Object[] { base });

    //Get all ServiceProviderCatalog urls from the base document in order to test them as well,
    //recursively checking them for other ServiceProviderCatalogs further down.
    NodeList spcs = (NodeList) OSLCUtils.getXPath().evaluate(
            "//oslc_disc:entry/oslc_disc:ServiceProviderCatalog/@rdf:about", baseDoc, XPathConstants.NODESET);
    for (int i = 0; i < spcs.getLength(); i++) {
        String uri = spcs.item(i).getNodeValue();
        uri = OSLCUtils.absoluteUrlFromRelative(base, uri);
        if (!uri.equals(base)) {
            Collection<Object[]> subCollection = getReferencedCatalogUrls(uri);
            Iterator<Object[]> iter = subCollection.iterator();
            while (iter.hasNext()) {
                data.add(iter.next());
            }
        }
    }
    return data;
}

From source file:org.mahasen.client.Delete.java

/**
 * @param fileName/*from  ww  w.ja  v  a  2  s . co  m*/
 * @param hostIP
 * @throws IOException
 */
public void delete(String fileName, String hostIP)
        throws IOException, AuthenticationExceptionException, URISyntaxException, MahasenClientException {
    httpclient = new DefaultHttpClient();
    clientLogin = new ClientLogin();
    ClientConfiguration clientConfiguration = ClientConfiguration.getInstance();

    try {
        System.setProperty("javax.net.ssl.trustStore", clientConfiguration.getTrustStorePath());
        System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
        System.setProperty("javax.net.ssl.trustStoreType", "JKS");

        String userName = clientConfiguration.getUserName();
        String passWord = clientConfiguration.getPassWord();
        String hostAndPort = hostIP + ":" + clientConfiguration.getPort();
        ClientLoginData loginData = clientLogin.remoteLogin(hostAndPort, userName, passWord);
        String logincookie = loginData.getCookie();
        Boolean isLogged = loginData.isLoggedIn();
        System.out.println("Login Cookie : " + logincookie + " Is Logged : " + isLogged);

        if (isLogged == true) {
            httpclient = WebClientSSLWrapper.wrapClient(httpclient);

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

            qparams.add(new BasicNameValuePair("fileName", fileName));

            URI uri = URIUtils.createURI("https", hostAndPort, -1, "/mahasen/delete_ajaxprocessor.jsp",
                    URLEncodedUtils.format(qparams, "UTF-8"), null);

            HttpPost httppost = new HttpPost(uri);

            System.out.println("executing request " + httppost.getRequestLine());
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity resEntity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());

            EntityUtils.consume(resEntity);

            if (response.getStatusLine().getStatusCode() == 900) {
                throw new MahasenClientException(String.valueOf(response.getStatusLine()));
            }
        } else {
            System.out.println("User has to be logged in to perform this function");
        }
    } finally

    {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

}

From source file:com.github.brandtg.switchboard.TestFileLogServer.java

private void pollAndCheck(HttpHost host, String uri, long count, long highWaterMark) throws Exception {
    long startTime = System.currentTimeMillis();
    long currentTime;
    do {//from w  ww.j a  va  2s .  c o m
        // Query server
        HttpGet req = new HttpGet(uri);
        HttpResponse res = httpClient.execute(host, req);
        try {
            if (res.getStatusLine().getStatusCode() == 200) {
                ObjectMapper mapper = new ObjectMapper();
                LogRegionResponse data = mapper.readValue(res.getEntity().getContent(),
                        LogRegionResponse.class);

                // Get all sorted indexes present in response
                List<Long> indexes = new ArrayList<>();
                for (LogRegion logRegion : data.getLogRegions()) {
                    indexes.add(logRegion.getIndex());
                }
                Collections.sort(indexes);

                // Check that we've have expected count and reached high watermark
                if (indexes.size() >= count && indexes.get(indexes.size() - 1) >= highWaterMark) {
                    return;
                }
            }
        } finally {
            if (res != null) {
                EntityUtils.consume(res.getEntity());
            }
        }

        // Wait until next time
        Thread.sleep(pollMillis);
        currentTime = System.currentTimeMillis();
    } while (currentTime - startTime < timeoutMillis);

    // Exited, so timed out
    throw new IllegalStateException("Timed out while waiting for " + uri);
}

From source file:com.ccc.crest.servlet.auth.CrestAuthCallback.java

private void getVerifyData(Base20ClientInfo clientInfo) throws Exception {
    Properties properties = CoreController.getController().getProperties();
    String verifyUrl = properties.getProperty(CrestController.OauthVerifyUrlKey,
            CrestController.OauthVerifyUrlDefault);
    String userAgent = properties.getProperty(CrestController.UserAgentKey, CrestController.UserAgentDefault);
    //@formatter:off
    CloseableHttpClient httpclient = HttpClients.custom().setUserAgent(userAgent).build();
    //@formatter:on

    String accessToken = ((OAuth2AccessToken) clientInfo.getAccessToken()).getAccessToken();
    HttpGet httpGet = new HttpGet(verifyUrl);
    httpGet.addHeader("Authorization", "Bearer " + accessToken);
    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    try {//  w w w .jav  a  2  s. co m
        HttpEntity entity1 = response1.getEntity();
        InputStream is = entity1.getContent();
        String json = IOUtils.toString(is, "UTF-8");
        is.close();
        ((CrestClientInfo) clientInfo).setVerifyData(OauthVerify.getOauthVerifyData(json));
        EntityUtils.consume(entity1);
    } finally {
        response1.close();
    }
}

From source file:com.autonomy.nonaci.indexing.impl.PostDataImpl.java

@Override
public void finish() throws IOException {
    EntityUtils.consume(httpEntity);
}

From source file:com.nominanuda.web.http.BaseHttpTest.java

protected boolean GETfor200(URI uri) throws ClientProtocolException, IOException {
    HttpResponse resp = GET(uri);/*from ww  w.ja  va  2 s  .  c  o m*/
    HttpEntity entity = resp.getEntity();
    try {
        return (HttpStatus.SC_OK == resp.getStatusLine().getStatusCode());
    } finally {
        EntityUtils.consume(entity);
    }
}

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

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

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
            .setParameter("judge", TestFixture.INSTANCE.judgeAndy.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.getHiredJudges().size(), 1);
        testEquality(doc.getHiredJudges().get(0), TestFixture.INSTANCE.hiredJudgeAndy);

        EntityUtils.consume(entity);
    }// w w  w .j a  v  a  2s  .c  o  m

    uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
            .setParameter("judge", "garbage").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.getHiredJudges().size(), 0);

        EntityUtils.consume(entity);
    }
}

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

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

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
            .setParameter("band", TestFixture.INSTANCE.skye.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.getBandContestEntry().size(), 1);
        testEquality(doc.getBandContestEntry().get(0), TestFixture.INSTANCE.bandContestEntry);

        EntityUtils.consume(entity);
    }//from w w w .ja  va  2  s  .co m

    uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
            .setParameter("band", "garbage").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.getBandContestEntry().size(), 0);

        EntityUtils.consume(entity);
    }
}

From source file:eu.prestoprime.p4gui.connection.AccessConnection.java

public static ArrayList<DCField> getDCFields(P4Service service, String id) {
    ArrayList<DCField> dc_fields = new ArrayList<DCField>();
    try {/*w  w w .j a va 2s.  c o m*/
        String path = service.getURL() + "/access/dip/" + id + "/info";
        P4HttpClient client = new P4HttpClient(service.getUserID());
        HttpRequestBase request = new HttpGet(path);
        HttpResponse response = client.executeRequest(request);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
            String line;
            while ((line = reader.readLine()) != null) {
                String[] fields = line.split("\\t");
                for (int i = 1; i < fields.length; i++)
                    dc_fields.add(new DCField(fields[0], fields[i]));
            }
        }
        EntityUtils.consume(entity);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return dc_fields;
}

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

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

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
            .setParameter("person", TestFixture.INSTANCE.elaine.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.getSoloContestEntry().size(), 1);
        testEquality(doc.getSoloContestEntry().get(0), TestFixture.INSTANCE.soloContestEntry);

        EntityUtils.consume(entity);
    }/*from  ww  w .j  a  va2 s. c  om*/

    uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
            .setParameter("person", "garbage").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.getSoloContestEntry().size(), 0);

        EntityUtils.consume(entity);
    }
}