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.helm.notation2.wsadapter.NucleotideWSLoader.java

/**
 * Loads the nucleotide store using the URL configured in {@code MonomerStoreConfiguration}.
 * /*from   w w w  .jav a2s  .  com*/
 * @return Map containing nucleotides
 * 
 * @throws IOException
 * @throws URISyntaxException
 */
public Map<String, String> loadNucleotideStore() throws IOException, URISyntaxException {

    Map<String, String> nucleotides = new HashMap<String, String>();
    LOG.debug("Loading nucleotide store by Webservice Loader");
    LOG.debug(MonomerStoreConfiguration.getInstance().toString());
    CloseableHttpResponse response = null;
    try {
        response = WSAdapterUtils
                .getResource(MonomerStoreConfiguration.getInstance().getWebserviceNucleotidesFullURL());
        LOG.debug(response.getStatusLine().toString());

        JsonFactory jsonf = new JsonFactory();
        InputStream instream = response.getEntity().getContent();

        JsonParser jsonParser = jsonf.createJsonParser(instream);
        nucleotides = deserializeNucleotideStore(jsonParser);
        LOG.debug(nucleotides.size() + " nucleotides loaded");

        EntityUtils.consume(response.getEntity());

    } catch (ClientProtocolException e) {

        /* read file */
        JsonFactory jsonf = new JsonFactory();
        InputStream instream = new FileInputStream(
                new File(MonomerStoreConfiguration.getInstance().getWebserviceNucleotidesFullURL()));

        JsonParser jsonParser = jsonf.createJsonParser(instream);
        nucleotides = deserializeNucleotideStore(jsonParser);
        LOG.debug(nucleotides.size() + " nucleotides loaded");

    } finally {

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

    return nucleotides;
}

From source file:org.metaeffekt.dcc.shell.RemoteAgentTest.java

private Set<String> getStates(HttpResponse response) throws IOException {

    Set<String> states = new HashSet<>();

    try (ZipInputStream zipStream = new ZipInputStream(response.getEntity().getContent());) {

        ZipEntry zipEntry = zipStream.getNextEntry();

        while (zipEntry != null) {
            String name = zipEntry.getName();
            name = name.substring(0, name.lastIndexOf("."));
            states.add(name);/*from  w ww . ja  va 2  s  .  c o m*/
            if (zipStream.available() > 0) {
                zipEntry = zipStream.getNextEntry();
            }
        }
    } finally {
        EntityUtils.consume(response.getEntity());
    }

    return states;
}

From source file:org.knoxcraft.http.client.ClientMultipartFormPost.java

public static void upload(String url, String playerName, File jsonfile, File sourcefile)
        throws ClientProtocolException, IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//from  w w  w  .  j  a va 2s.c  o  m
        HttpPost httppost = new HttpPost(url);

        FileBody json = new FileBody(jsonfile);
        FileBody source = new FileBody(sourcefile);
        String jsontext = readFromFile(jsonfile);

        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("playerName", new StringBody(playerName, ContentType.TEXT_PLAIN))
                .addPart("jsonfile", json).addPart("sourcefile", source)
                .addPart("language", new StringBody("java", ContentType.TEXT_PLAIN))
                .addPart("jsontext", new StringBody(jsontext, ContentType.TEXT_PLAIN)).addPart("sourcetext",
                        new StringBody("public class Foo {\n  int x=5\n}", ContentType.TEXT_PLAIN))
                .build();

        httppost.setEntity(reqEntity);

        System.out.println("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            //System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                //System.out.println("Response content length: " + resEntity.getContentLength());
                Scanner sc = new Scanner(resEntity.getContent());
                while (sc.hasNext()) {
                    System.out.println(sc.nextLine());
                }
                sc.close();
                EntityUtils.consume(resEntity);
            }
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.sonatype.nexus.perftest.maven.ArtifactDeployer.java

private void deploy0(HttpEntity entity, String groupId, String artifactId, String version, String extension)
        throws IOException {
    StringBuilder path = new StringBuilder();

    path.append(groupId.replace('.', '/')).append('/');
    path.append(artifactId).append('/');
    path.append(version).append('/');
    path.append(artifactId).append('-').append(version).append(extension);

    HttpPut httpPut = new HttpPut(repoUrl + path);
    httpPut.setEntity(entity);/*  www  .  j a v a  2s . c om*/

    HttpResponse response;
    try {
        response = httpclient.execute(httpPut);

        try {
            EntityUtils.consume(response.getEntity());
        } finally {
            httpPut.releaseConnection();
        }
    } catch (IOException e) {
        throw new IOException("IOException executing " + httpPut.toString(), e);
    }

    if (response.getStatusLine().getStatusCode() < 200 || response.getStatusLine().getStatusCode() > 299) {
        throw new IOException(httpPut.toString() + " : " + response.getStatusLine().toString());
    }
}

From source file:com.vaushell.superpipes.tools.http.ImageExtractor.java

/**
 * Return the biggest image URI of this webpage.
 *
 * @param rootURI Webpage URI/* w  w  w . j a va2  s . c o  m*/
 * @return Biggest image
 * @throws IOException
 */
public BufferedImage extractBiggest(final URI rootURI) throws IOException {
    final List<URI> imagesURIs = new ArrayList<>();
    HttpEntity responseEntity = null;
    try {
        // Exec request
        final HttpGet get = new HttpGet(rootURI);

        try (final CloseableHttpResponse response = client.execute(get)) {
            final StatusLine sl = response.getStatusLine();
            if (sl.getStatusCode() != 200) {
                throw new IOException(sl.getReasonPhrase());
            }

            responseEntity = response.getEntity();

            try (final InputStream is = responseEntity.getContent()) {
                final Document doc = Jsoup.parse(is, "UTF-8", rootURI.toString());

                final Elements elts = doc.select("img");
                if (elts != null) {
                    for (final Element elt : elts) {
                        final String src = elt.attr("src");
                        if (src != null && !src.isEmpty()) {
                            try {
                                imagesURIs.add(rootURI.resolve(src));
                            } catch (final IllegalArgumentException ex) {
                                // Ignore wrong encoded URI
                            }
                        }
                    }
                }
            }
        }
    } finally {
        if (responseEntity != null) {
            EntityUtils.consume(responseEntity);
        }
    }

    final BufferedImage[] images = new BufferedImage[imagesURIs.size()];
    final ExecutorService service = Executors.newCachedThreadPool();
    for (int i = 0; i < imagesURIs.size(); ++i) {
        final int num = i;

        service.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    images[num] = HTTPhelper.loadPicture(client, imagesURIs.get(num));
                } catch (final IOException ex) {
                    images[num] = null;
                }
            }
        });
    }

    service.shutdown();

    try {
        service.awaitTermination(1L, TimeUnit.DAYS);
    } catch (final InterruptedException ex) {
        // Ignore
    }

    BufferedImage biggest = null;
    int biggestSize = Integer.MIN_VALUE;
    for (int i = 0; i < imagesURIs.size(); ++i) {
        if (images[i] != null) {
            final int actualSize = images[i].getWidth() * images[i].getHeight();
            if (actualSize > biggestSize) {
                biggest = images[i];

                biggestSize = actualSize;
            }
        }
    }

    return biggest;
}

From source file:com.github.tomakehurst.wiremock.BindAddressTest.java

private int getStatusViaHttps(String host) throws Exception {
    HttpResponse localhostResponse = client.execute(
            RequestBuilder.get("https://" + host + ":" + wireMockServer.httpsPort() + "/bind-test").build());

    int status = localhostResponse.getStatusLine().getStatusCode();
    EntityUtils.consume(localhostResponse.getEntity());
    return status;
}

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

protected void makeCall(String user, String pass, int expectedStatusCode) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/* w  ww  .j  av a2 s.  c  o  m*/
        httpclient.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8080),
                new UsernamePasswordCredentials(user, pass));

        HttpGet httpget = new HttpGet(URL);

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

        System.out.println("----------------------------------------");
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine);
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        assertEquals(expectedStatusCode, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    } 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:org.elasticsearch.river.solr.support.SolrIndexer.java

public void clearDocuments() throws IOException {
    HttpPost httpPost = new HttpPost(solrUrl + "?commit=true");
    httpPost.setHeader("Content-type", "application/xml");
    httpPost.setEntity(new StringEntity("<delete><query>*:*</query></delete>"));

    CloseableHttpResponse response = httpClient.execute(httpPost);
    try {//from  ww  w  . ja va2s  .  co m
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("documents were not properly cleared");
        }
    } finally {
        EntityUtils.consume(response.getEntity());
        response.close();
    }
}

From source file:org.aksw.simba.cetus.fox.FoxBasedTypeSearcher.java

@Override
public TypedNamedEntity getAllTypes(Document document, NamedEntity ne,
        List<ExtendedTypedNamedEntity> surfaceForms) {
    TypedNamedEntity tne = new TypedNamedEntity(ne.getStartPosition(), ne.getLength(), ne.getUris(),
            new HashSet<String>());
    for (ExtendedTypedNamedEntity surfaceForm : surfaceForms) {
        tne.getTypes().addAll(surfaceForm.getUris());
    }// w  ww.  j a v  a 2s  .  c o  m

    try {
        // request FOX
        Response response = Request.Post(FOX_SERVICE).addHeader("Content-type", "application/json")
                .addHeader("Accept-Charset", "UTF-8")
                .body(new StringEntity(new JSONObject().put("input", document.getText()).put("type", "text")
                        .put("task", "ner").put("output", "JSON-LD").toString(), ContentType.APPLICATION_JSON))
                .execute();

        HttpResponse httpResponse = response.returnResponse();
        HttpEntity entry = httpResponse.getEntity();

        String content = IOUtils.toString(entry.getContent(), "UTF-8");
        EntityUtils.consume(entry);

        // parse results
        JSONObject outObj = new JSONObject(content);
        if (outObj.has("@graph")) {

            JSONArray graph = outObj.getJSONArray("@graph");
            for (int i = 0; i < graph.length(); i++) {
                parseType(graph.getJSONObject(i), tne, surfaceForms);
            }
        } else {
            parseType(outObj, tne, surfaceForms);
        }
    } catch (Exception e) {
        LOGGER.error("Got an exception while communicating with the FOX web service.", e);
    }
    return tne;
}

From source file:com.intel.cosbench.client.keystone.handler.HttpAuthHandler.java

private void clearResponse(HttpEntity entity) {
    try {/*from  w w  w. j  a va  2 s  .  c o  m*/
        EntityUtils.consume(entity);
    } catch (IOException ioe) {
        String e = "error consuming response from keystone";
        throw new KeystoneServerException(e, ioe);
    }
}