List of usage examples for org.apache.http.util EntityUtils consume
public static void consume(HttpEntity httpEntity) throws IOException
From source file:com.rackspacecloud.blueflood.outputs.handlers.HttpMultiRollupsQueryHandlerIntegrationTest.java
@Test public void testHttpMultiRollupsQueryHandler() throws Exception { // ingest and rollup metrics and verify CF points and elastic search indexes String postfix = getPostfix(); // post multi metrics for ingestion and verify HttpResponse response = postMetric(tenant_id, postAggregatedPath, "sample_payload.json", postfix); assertEquals("Should get status 200 from ingestion server for POST", 200, response.getStatusLine().getStatusCode()); EntityUtils.consume(response.getEntity()); JsonObject responseObject = getMultiMetricRetry(tenant_id, start, end, "200", "FULL", "", "['3333333.G1s" + postfix + "','3333333.G10s" + postfix + "']", 2); assertNotNull("No values for metrics found", responseObject); JsonArray metrics = responseObject.getAsJsonArray("metrics"); assertEquals(2, metrics.size());// ww w . j a v a2 s. c o m Map<String, JsonObject> metricMap = new HashMap<String, JsonObject>(); JsonObject metric0 = metrics.get(0).getAsJsonObject(); metricMap.put(metric0.get("metric").getAsString(), metric0); JsonObject metric1 = metrics.get(1).getAsJsonObject(); metricMap.put(metric1.get("metric").getAsString(), metric1); JsonObject metricCheck1 = metricMap.get("3333333.G1s" + postfix); assertNotNull(metricCheck1); assertEquals("unknown", metricCheck1.get("unit").getAsString()); assertEquals("number", metricCheck1.get("type").getAsString()); JsonArray data0 = metricCheck1.getAsJsonArray("data"); assertEquals(1, data0.size()); JsonObject data0a = data0.get(0).getAsJsonObject(); assertTrue(data0a.has("timestamp")); assertEquals(1, data0a.get("numPoints").getAsInt()); assertEquals(397, data0a.get("latest").getAsInt()); JsonObject metricCheck2 = metricMap.get("3333333.G10s" + postfix); assertNotNull(metricCheck2); assertEquals("unknown", metricCheck2.get("unit").getAsString()); assertEquals("number", metricCheck2.get("type").getAsString()); JsonArray data1 = metricCheck2.getAsJsonArray("data"); assertEquals(1, data1.size()); JsonObject data1a = data1.get(0).getAsJsonObject(); assertTrue(data1a.has("timestamp")); assertEquals(1, data1a.get("numPoints").getAsInt()); assertEquals(56, data1a.get("latest").getAsInt()); assertResponseHeaderAllowOrigin(response); }
From source file:com.comcast.cim.rest.client.xhtml.XhtmlResponseHandler.java
public XhtmlApplicationState handleResponse(HttpResponse resp) throws ClientProtocolException, IOException { SAXBuilder builder = getBuilder();/*from ww w .j a va2 s .co m*/ HttpEntity entity = null; try { entity = resp.getEntity(); Document doc = null; if (entity != null) { doc = builder.build(entity.getContent()); EntityUtils.consume(entity); } return new XhtmlApplicationState(context, resp, doc); } catch (JDOMException e) { logger.warn("unparseable XML response", e); EntityUtils.consume(entity); return new XhtmlApplicationState(context, resp, null); } }
From source file:com.ibm.ra.remy.web.utils.BusinessRulesUtils.java
/** * Invoke Business Rules with JSON content * * @param content The payload of itineraries to send to Business Rules. * @return A JSON string representing the output of Business Rules. *//*from ww w. j a v a 2 s. c o m*/ public static String invokeRulesService(String json) throws Exception { PropertiesReader constants = PropertiesReader.getInstance(); String username = constants.getStringProperty(USERNAME_KEY); String password = constants.getStringProperty(PASSWORD_KEY); String endpoint = constants.getStringProperty(EXECUTION_REST_URL_KEY) + constants.getStringProperty(RULE_APP_PATH_KEY); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); CloseableHttpClient httpClient = HttpClientBuilder.create() .setDefaultCredentialsProvider(credentialsProvider).build(); String responseString = ""; try { HttpPost httpPost = new HttpPost(endpoint); httpPost.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); StringEntity jsonEntity = new StringEntity(json, MessageUtils.ENCODING); httpPost.setEntity(jsonEntity); CloseableHttpResponse response = httpClient.execute(httpPost); try { HttpEntity entity = response.getEntity(); responseString = EntityUtils.toString(entity, MessageUtils.ENCODING); EntityUtils.consume(entity); } finally { response.close(); } } finally { httpClient.close(); } return responseString; }
From source file:com.github.restdriver.clientdriver.integration.BodyMatchersTest.java
@Test public void canUseStringMatcherWhenMatchingRequestBody() throws Exception { clientDriver.addExpectation(/*from w w w .java2 s . c o m*/ onRequestTo("/foo").withMethod(Method.POST).withBody(containsString("str"), "text/plain"), giveEmptyResponse().withStatus(201)); clientDriver.addExpectation( onRequestTo("/foo").withMethod(Method.POST).withBody(not(containsString("str")), "text/plain"), giveEmptyResponse().withStatus(202)); HttpClient client = new DefaultHttpClient(); HttpPost correctPost = new HttpPost(clientDriver.getBaseUrl() + "/foo"); correctPost.setEntity(new StringEntity("a string containing my substring of 'str'")); HttpResponse correctResponse = client.execute(correctPost); EntityUtils.consume(correctResponse.getEntity()); assertThat(correctResponse.getStatusLine().getStatusCode(), is(201)); HttpPost incorrectPost = new HttpPost(clientDriver.getBaseUrl() + "/foo"); incorrectPost.setEntity(new StringEntity("something containing my subst... WAIT, no, it doesn't")); HttpResponse incorrectResponse = client.execute(incorrectPost); EntityUtils.consume(incorrectResponse.getEntity()); assertThat(incorrectResponse.getStatusLine().getStatusCode(), is(202)); }
From source file:xworker.app.model.tree.http.HttpExtjsJsonTreeModelActions.java
/** * ????/*from w w w . j a v a 2 s . c o m*/ * * @param url * @param self * @param actionContext * @return * @throws IOException */ @SuppressWarnings("unchecked") public static Object getTreeDatas(String prefixUrl, String url, Thing self, ActionContext actionContext) throws IOException { HttpClient httpClient = getHttpClient(self, actionContext); if (httpClient != null) { HttpGet httpGet = new HttpGet(url); HttpEntity entity = null; try { HttpResponse response = httpClient.execute(httpGet); entity = response.getEntity(); String content = EntityUtils.toString(entity); Object datas = JsonFormator.parse(content, actionContext); URI uri = null; if (prefixUrl != null && !"".equals(prefixUrl)) { //prefixUrl uri = new URI(prefixUrl); } else { uri = new URI(url); } if (datas instanceof List) { checkImageUrl((List<Map<String, Object>>) datas, uri); } else { checkImageUrl((Map<String, Object>) datas, uri); } return datas; } catch (Exception e) { logger.error("Get tree content error", e); } finally { if (entity != null) { EntityUtils.consume(entity); } } } return null; }
From source file:uk.codingbadgers.bootstrap.download.Sha1Download.java
@Override public void download() { CloseableHttpClient client = HttpClients.createDefault(); String hash = null;//from w ww. j a v a 2 s .c om // Get sha1 hash from repo try { HttpGet request = new HttpGet(remote + ".sha1"); HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); if (status.getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); hash = EntityUtils.toString(entity); EntityUtils.consume(entity); } } catch (IOException ex) { throw new BootstrapException(ex); } if (local.exists()) { String localHash = ChecksumGenerator.createSha1(local); if (hash != null && hash.equalsIgnoreCase(localHash)) { System.out.println("File " + local.getName() + " is up to date with remote, no need to download"); return; } } if (!local.getParentFile().exists()) { local.getParentFile().mkdirs(); } // Download library from remote try { HttpGet request = new HttpGet(remote); HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); if (status.getStatusCode() == HttpStatus.SC_OK) { System.err.println("Downloading " + local.getName()); HttpEntity entity = response.getEntity(); ReadableByteChannel rbc = Channels.newChannel(entity.getContent()); FileOutputStream fos = new FileOutputStream(local); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); EntityUtils.consume(entity); String localHash = ChecksumGenerator.createSha1(local); if (hash != null && !localHash.equalsIgnoreCase(hash)) { throw new BootstrapException("Error downloading file (" + local.getName() + ")\n[expected hash: " + localHash + " but got " + hash + "]"); } System.out.println("Downloaded " + local.getName()); } else { throw new BootstrapException("Error download update for " + local.getName() + ", Error: " + status.getStatusCode() + status.getReasonPhrase()); } } catch (IOException ex) { throw new BootstrapException(ex); } }
From source file:com.ibm.CloudResourceBundle.java
private static Rows getServerResponse(CloudDataConnection connect) throws Exception { Rows rows = null;//from w w w.j a va2s.co m CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope("provide.castiron.com", 443), new UsernamePasswordCredentials(connect.getUserid(), connect.getPassword())); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); try { // Call the service and get all the strings for all the languages HttpGet httpget = new HttpGet(connect.getURL()); httpget.addHeader("API_SECRET", connect.getSecret()); CloseableHttpResponse response = httpclient.execute(httpget); try { InputStream in = response.getEntity().getContent(); ObjectMapper mapper = new ObjectMapper(); rows = mapper.readValue(new InputStreamReader(in, "UTF-8"), Rows.class); EntityUtils.consume(response.getEntity()); } finally { response.close(); } } finally { httpclient.close(); } return rows; }
From source file:eu.prestoprime.p4gui.connection.AccessConnection.java
public static DIP getDIP(P4Service service, String id) { try {//ww w. ja v a 2 s .c o m String path = service.getURL() + "/access/dip/" + id; P4HttpClient client = new P4HttpClient(service.getUserID()); HttpRequestBase request = new HttpGet(path); HttpResponse response = client.executeRequest(request); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream is = entity.getContent(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Node dom = dbf.newDocumentBuilder().parse(is); is.close(); return new DIP(id, dom); } EntityUtils.consume(entity); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:org.jboss.arquillian.ce.httpclient.HttpClientImpl.java
public HttpResponse execute(HttpRequest request, HttpClientExecuteOptions options) throws IOException { IOException exception = null; HttpUriRequest r = HttpRequestImpl.class.cast(request).unwrap(); CloseableHttpResponse rawResponse = null; HttpResponse response = null;// ww w . ja v a 2 s .c o m for (int i = 0; i < options.getTries(); i++) { try { if (rawResponse != null) { EntityUtils.consume(rawResponse.getEntity()); } rawResponse = client.execute(r); response = new HttpResponseImpl(rawResponse); if (options.getDesiredStatusCode() == -1 || response.getResponseCode() == options.getDesiredStatusCode()) { return response; } System.err.println(String.format("Response error [URL:%s]: Got code %d, expected %d.", r.getURI(), response.getResponseCode(), options.getDesiredStatusCode())); } catch (IOException e) { exception = e; System.err.println(String.format("Execute error [URL:%s]: %s.", r.getURI(), e)); } if (i + 1 < options.getTries()) { System.err.println(String.format("Trying again in %d seconds.", options.getDelay())); try { Thread.sleep(options.getDelay() * 1000); } catch (InterruptedException e) { exception = new IOException(e); break; } } else { System.err.println( String.format("Giving up trying URL:%s after %d tries", r.getURI(), options.getTries())); } } if (exception != null) { throw exception; } return response; }
From source file:ADP_Streamline.CURL2.java
public String uploadFiles(File file, String siteId, String containerId, String uploadDirectory) { String json = null;//from w ww . j ava2 s . c o m DefaultHttpClient httpclient = new DefaultHttpClient(); HttpHost targetHost = new HttpHost("localhost", 8080, "http"); try { HttpPost httppost = new HttpPost("/alfresco/service/api/upload?alf_ticket=" + this.ticket); FileBody bin = new FileBody(file); StringBody siteid = new StringBody(siteId); StringBody containerid = new StringBody(containerId); StringBody uploaddirectory = new StringBody(uploadDirectory); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("filedata", bin); reqEntity.addPart("siteid", siteid); reqEntity.addPart("containerid", containerid); reqEntity.addPart("uploaddirectory", uploaddirectory); httppost.setEntity(reqEntity); //log.debug("executing request:" + httppost.getRequestLine()); HttpResponse response = httpclient.execute(targetHost, httppost); HttpEntity resEntity = response.getEntity(); //log.debug("response status:" + response.getStatusLine()); if (resEntity != null) { //log.debug("response content length:" + resEntity.getContentLength()); json = EntityUtils.toString(resEntity); //log.debug("response content:" + json); } EntityUtils.consume(resEntity); } catch (Exception e) { throw new RuntimeException(e); } finally { httpclient.getConnectionManager().shutdown(); } return json; }