List of usage examples for org.apache.http.util EntityUtils consumeQuietly
public static void consumeQuietly(HttpEntity httpEntity)
From source file:org.jasig.cas.util.http.SimpleHttpClient.java
@Override public boolean isValidEndPoint(final URL url) { Assert.notNull(this.httpClient); HttpEntity entity = null;/*from ww w . j a va 2 s . c o m*/ try (final CloseableHttpResponse response = this.httpClient.execute(new HttpGet(url.toURI()))) { final int responseCode = response.getStatusLine().getStatusCode(); for (final int acceptableCode : this.acceptableCodes) { if (responseCode == acceptableCode) { LOGGER.debug("Response code from server matched {}.", responseCode); return true; } } LOGGER.debug("Response code did not match any of the acceptable response codes. Code returned was {}", responseCode); if (responseCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) { final String value = response.getStatusLine().getReasonPhrase(); LOGGER.error("There was an error contacting the endpoint: {}; The error was:\n{}", url.toExternalForm(), value); } entity = response.getEntity(); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } finally { EntityUtils.consumeQuietly(entity); } return false; }
From source file:com.brsanthu.googleanalytics.GoogleAnalytics.java
@SuppressWarnings({ "rawtypes" }) public GoogleAnalyticsResponse post(GoogleAnalyticsRequest request) { GoogleAnalyticsResponse response = new GoogleAnalyticsResponse(); if (!config.isEnabled()) { return response; }/*from ww w.j av a 2 s .c om*/ CloseableHttpResponse httpResponse = null; try { List<NameValuePair> postParms = new ArrayList<NameValuePair>(); //MatterOverdrive.log.debug("Processing " + request); //Process the parameters processParameters(request, postParms); //Process custom dimensions processCustomDimensionParameters(request, postParms); //Process custom metrics processCustomMetricParameters(request, postParms); //MatterOverdrive.log.debug("Processed all parameters and sending the request " + postParms); HttpPost httpPost = new HttpPost(config.getUrl()); httpPost.setEntity(new UrlEncodedFormEntity(postParms, UTF8)); httpResponse = (CloseableHttpResponse) httpClient.execute(httpPost); response.setStatusCode(httpResponse.getStatusLine().getStatusCode()); response.setPostedParms(postParms); EntityUtils.consumeQuietly(httpResponse.getEntity()); if (config.isGatherStats()) { gatherStats(request); } } catch (Exception e) { if (e instanceof UnknownHostException) { MatterOverdrive.log.warn( "Coudln't connect to Google Analytics. Internet may not be available. " + e.toString()); } else { MatterOverdrive.log.warn("Exception while sending the Google Analytics tracker request " + request, e); } } finally { try { httpResponse.close(); } catch (Exception e2) { //ignore } } return response; }
From source file:co.cask.tigon.sql.internal.HealthAndMetricsTest.java
@Test public void testPing() throws InterruptedException { final String pingURL = "http://" + discoveryServer.getHubAddress().getAddress().getHostAddress() + ":" + discoveryServer.getHubAddress().getPort(); LOG.info("Discovery Server URL : " + pingURL); //Code to emulate pings after every second class MockPing implements Runnable { @Override/* w w w . j a v a2 s.com*/ public void run() { HttpClient httpClient = new DefaultHttpClient(); for (int i = 0; i < PING_COUNT; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } JsonObject bodyJson = new JsonObject(); bodyJson.addProperty("name", "test"); bodyJson.addProperty("ftaid", "IronMan"); JsonObject metrics = new JsonObject(); metrics.addProperty("awesomeCounter", i); bodyJson.add("metrics", metrics); HttpPost httpPost = new HttpPost(pingURL + "/v1/log-metrics"); StringEntity params = null; try { params = new StringEntity(bodyJson.toString()); httpPost.addHeader("Content-Type", "application/json"); httpPost.setEntity(params); EntityUtils.consumeQuietly(httpClient.execute(httpPost).getEntity()); } catch (IOException e) { Throwables.propagate(e); } LOG.info("Pinged with Metrics {}", bodyJson.toString()); } } } inspector.startAndWait(); LOG.info("Started monitoring..."); TimeUnit.SECONDS.sleep(Constants.INITIALIZATION_TIMEOUT - 3); register("IronMan", "RobertDowneyJr", pingURL); LOG.info("IronMan Registered"); Assert.assertTrue(!failureLatch.await(0, TimeUnit.SECONDS)); LOG.info("No failure detected"); //Initiate PING_COUNT mock pings, 1 per second new Thread(new MockPing()).start(); LOG.info("Initiated {} mock pings", PING_COUNT); //Check state 250ms after the first mock ping Assert.assertTrue(!failureLatch.await(250, TimeUnit.MILLISECONDS)); LOG.info("No failure Detected"); LOG.info("Expecting heartbeat detection failure"); pingLatch.await(30, TimeUnit.SECONDS); //Check state after the last mock ping (timeout > HEARTBEAT_FREQUENCY) Assert.assertTrue(failureLatch.await(30, TimeUnit.SECONDS)); //Check value of awesomeCounter at the end Assert.assertTrue(SharedMetrics.getCounter("RobertDowneyJr.awesomeCounter") .equals((PING_COUNT - 1) * PING_COUNT / 2)); }
From source file:org.apache.olingo.fit.CXFOAuth2HttpClientFactory.java
@Override protected void init() throws OAuth2Exception { final URI authURI = OAuthClientUtils.getAuthorizationURI(oauth2GrantServiceURI.toASCIIString(), OAuth2Provider.CLIENT_ID, OAuth2Provider.REDIRECT_URI, null, null); // Disable automatic redirects handling final HttpParams params = new BasicHttpParams(); params.setParameter(ClientPNames.HANDLE_REDIRECTS, false); final DefaultHttpClient httpClient = new DefaultHttpClient(params); JsonNode oAuthAuthorizationData = null; String authenticityCookie = null; try {//from ww w.j a va 2 s . c o m // 1. Need to (basic) authenticate against the OAuth2 service final HttpGet method = new HttpGet(authURI); method.addHeader("Authorization", "Basic " + Base64.encodeBase64String("odatajclient:odatajclient".getBytes())); final HttpResponse response = httpClient.execute(method); // 2. Pull out OAuth2 authorization data and "authenticity" cookie (CXF specific) oAuthAuthorizationData = new XmlMapper().readTree(EntityUtils.toString(response.getEntity())); final Header setCookieHeader = response.getFirstHeader("Set-Cookie"); if (setCookieHeader == null) { throw new IllegalStateException("OAuth flow is broken"); } authenticityCookie = setCookieHeader.getValue(); } catch (Exception e) { throw new OAuth2Exception(e); } String code = null; try { // 3. Submit the HTTP form for allowing access to the application final URI location = new URIBuilder(oAuthAuthorizationData.get("replyTo").asText()) .addParameter("session_authenticity_token", oAuthAuthorizationData.get("authenticityToken").asText()) .addParameter("client_id", oAuthAuthorizationData.get("clientId").asText()) .addParameter("redirect_uri", oAuthAuthorizationData.get("redirectUri").asText()) .addParameter("oauthDecision", "allow").build(); final HttpGet method = new HttpGet(location); method.addHeader("Authorization", "Basic " + Base64.encodeBase64String("odatajclient:odatajclient".getBytes())); method.addHeader("Cookie", authenticityCookie); final HttpResponse response = httpClient.execute(method); final Header locationHeader = response.getFirstHeader("Location"); if (response.getStatusLine().getStatusCode() != 303 || locationHeader == null) { throw new IllegalStateException("OAuth flow is broken"); } // 4. Get the authorization code value out of this last redirect code = StringUtils.substringAfterLast(locationHeader.getValue(), "="); EntityUtils.consumeQuietly(response.getEntity()); } catch (Exception e) { throw new OAuth2Exception(e); } // 5. Obtain the access token try { accessToken = OAuthClientUtils.getAccessToken(getAccessTokenService(), OAUTH2_CONSUMER, new AuthorizationCodeGrant(code)); } catch (OAuthServiceException e) { throw new OAuth2Exception(e); } if (accessToken == null) { throw new OAuth2Exception("No OAuth2 access token"); } }
From source file:org.callimachusproject.server.helpers.Exchange.java
private void consume(HttpResponse response) { HttpEntity entity = response.getEntity(); if (entity != null) { EntityUtils.consumeQuietly(entity); } }
From source file:jp.classmethod.aws.brian.BrianClient.java
@Override public boolean isAvailable() { logger.debug("is available?"); HttpResponse httpResponse = null;/* ww w .j a va 2s.c o m*/ try { URI uri = new URI(scheme, null, hostname, port, "/", null, null); HttpUriRequest httpRequest = RequestBuilder.get().setUri(uri).build(); httpResponse = httpClientExecute(httpRequest); int statusCode = httpResponse.getStatusLine().getStatusCode(); logger.debug("statusCode: {}", statusCode); return statusCode == HttpStatus.SC_OK; } catch (Exception e) { logger.warn("{}: {}", e.getClass().getName(), e.getMessage()); } finally { if (httpResponse != null) { EntityUtils.consumeQuietly(httpResponse.getEntity()); } } return false; }
From source file:AIR.Common.Web.HttpWebHelper.java
public void sendXml(String url, IXmlSerializable inputData, OutputStream outputData) { ByteArrayOutputStream out = new ByteArrayOutputStream(); HttpPost post = new HttpPost(url); post.setHeader("Content-Type", "text/xml"); HttpResponse response = null;// w w w . ja v a2 s. c om try { XMLOutputFactory output = TdsXmlOutputFactory.newInstance(); XMLStreamWriter writer = output.createXMLStreamWriter(out); inputData.writeXML(writer); ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray()); post.setEntity(entity); response = _client.execute(post, _contextPool.get()); } catch (IOException | XMLStreamException e) { try { outputData.write(String.format("HTTP client through exception: %s", e.getMessage()).getBytes()); } catch (IOException e1) { // Our IOExceptioin through an IOException--bad news!!! _logger.error("Output stream encountered an error while attempting to process an error message", e1); _logger.error(String.format("Original drror message was \"\"", e.getMessage())); } } if (response != null) { HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { String responseString = ""; try { responseString = EntityUtils.toString(responseEntity); outputData.write(responseString.getBytes()); } catch (IOException e) { // Our IOExceptioin through an IOException--bad news!!! _logger.error("Output stream encountered an error while attempting to process a reply", e); _logger.error(String.format("Original reply content was \"\"", responseString)); } EntityUtils.consumeQuietly(responseEntity); } } }
From source file:pl.psnc.synat.wrdz.mdz.integrity.IntegrityProcessorBean.java
@Override @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public IntegrityProcessingResult processOne() { DigitalObject object = getNextObject(); if (object == null) { return IntegrityProcessingResult.FINISHED; }//w ww.j a v a 2 s. c o m HttpClient client = httpsClientHelper.getHttpsClient(WrdzModule.MDZ); HttpGet get = new HttpGet(configuration.getZmdObjectUrl(object.getIdentifier())); HttpResponse response = null; try { synchronized (this) { response = client.execute(get); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) { waitingForIdentifier = object.getIdentifier(); return IntegrityProcessingResult.PAUSED; } } if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { boolean corrupted = false; File file = storeTemporarily(response.getEntity()); try { corrupted = integrityVerifier.isCorrupted(object.getIdentifier(), file); } finally { if (!file.delete()) { logger.warn("Could not delete temporary file: " + file.getAbsolutePath()); } } if (corrupted) { messenger.notifyObjectCorrupted(object.getIdentifier()); } object.setVerifiedOn(new Date()); object.setCorrect(!corrupted); return IntegrityProcessingResult.PROCESSED; } else { throw new WrdzRuntimeException("Unexpected response: " + response.getStatusLine()); } } catch (IOException e) { throw new WrdzRuntimeException("Could not fetch object from ZMD", e); } finally { if (response != null) { EntityUtils.consumeQuietly(response.getEntity()); } } }
From source file:com.falcon.orca.actors.Generator.java
private void makeHttpCall() { HttpResponse response = null;//from www .j a va2s .c om try { HttpUriRequest request = prepareRequest(); long startTime = System.nanoTime(); response = client.execute(request); long stopTime = System.nanoTime(); sendDataToCollector(stopTime, startTime, response.getEntity().getContentLength(), response.getStatusLine().getStatusCode()); } catch (Exception e) { System.out.println("Error in making http call " + e.getMessage()); } finally { if (response != null && response.getEntity() != null) EntityUtils.consumeQuietly(response.getEntity()); } }
From source file:com.emc.vipr.ribbon.ViPRDataServicesServerList.java
protected List<Server> pollForServers() { try {// w w w. java 2s . co m List<Server> activeNodeList = getNodeList(); int activeNodeCount = activeNodeList.size(); Server server = null; List<String> hosts = null; String path = "/?endpoint"; // we want to try a different node on failure until we try every active node (HttpClient will auto-retry // 500s and some IOEs), but we don't want to start with the same node each time. for (int i = 0; i < activeNodeCount; i++) { try { // get next server in the list (trying to distribute this call among active nodes) // note: the extra modulus logic is there just in case requestCounter wraps around to a negative value server = activeNodeList .get((requestCounter++ % activeNodeCount + activeNodeCount) % activeNodeCount); HttpGet request = new HttpGet(protocol + "://" + server + path); logger.debug("endpoint query attempt #" + (i + 1) + ": trying " + server); // format date String rfcDate; synchronized (rfc822DateFormat) { rfcDate = rfc822DateFormat.format(new Date()); } // generate signature String canonicalString = "GET\n\n\n" + rfcDate + "\n" + path; String signature = getSignature(canonicalString, secret); // add date and auth headers request.addHeader("Date", rfcDate); request.addHeader("Authorization", "AWS " + user + ":" + signature); // send request HttpResponse response = httpClient.execute(request); if (response.getStatusLine().getStatusCode() > 299) { EntityUtils.consumeQuietly(response.getEntity()); throw new RuntimeException("received error response: " + response.getStatusLine()); } logger.debug("received success response: " + response.getStatusLine()); hosts = parseResponse(response); break; } catch (Exception e) { logger.warn("error polling for endpoints on " + server, e); } } if (hosts == null) throw new RuntimeException("Exhausted all nodes; no response available"); List<Server> updatedNodeList = new ArrayList<Server>(); for (String host : hosts) { updatedNodeList.add(new Server(host, port)); } setNodeList(updatedNodeList); } catch (Exception e) { logger.warn("Unable to poll for servers", e); } return getNodeList(); }