List of usage examples for org.apache.http.util EntityUtils consumeQuietly
public static void consumeQuietly(HttpEntity httpEntity)
From source file:com.mode.googleanalytics.GoogleAnalytics.java
@SuppressWarnings({ "rawtypes" }) public GoogleAnalyticsResponse post(GoogleAnalyticsRequest request) { GoogleAnalyticsResponse response = new GoogleAnalyticsResponse(); if (!config.isEnabled()) { return response; }//from ww w .j a v a 2 s. c om CloseableHttpResponse httpResponse = null; try { List<NameValuePair> postParms = new ArrayList<NameValuePair>(); logger.debug("Processing " + request); //Process the parameters processParameters(request, postParms); //Process custom dimensions processCustomDimensionParameters(request, postParms); //Process custom metrics processCustomMetricParameters(request, postParms); logger.debug("Processed all parameters and sending the request " + postParms); HttpPost httpPost = new HttpPost(config.getUrl()); httpPost.setEntity(new UrlEncodedFormEntity(postParms, UTF8)); // System.out.println("config.getUrl() -> " + config.getUrl()); httpResponse = (CloseableHttpResponse) httpClient.execute(httpPost); // System.out.println("httpResponse -> " + httpResponse); response.setStatusCode(httpResponse.getStatusLine().getStatusCode()); response.setPostedParms(postParms); EntityUtils.consumeQuietly(httpResponse.getEntity()); if (config.isGatherStats()) { gatherStats(request); } } catch (Exception e) { e.printStackTrace(); if (e instanceof UnknownHostException) { logger.warn("Coudln't connect to Google Analytics. Internet may not be available. " + e.toString()); } else { logger.warn("Exception while sending the Google Analytics tracker request " + request, e); } } finally { try { if (httpResponse != null) { httpResponse.close(); } } catch (Exception e2) { e2.printStackTrace(); //ignore } } return response; }
From source file:com.cloudbees.servlet.filters.PrivateAppFilterIntegratedTest.java
@Test public void form_authentication_scenario() throws Exception { System.out.println("form_authentication_scenario"); privateAppFilter.setAuthenticationEntryPoint(PrivateAppFilter.AuthenticationEntryPoint.FORM_AUTH); {// w w w . j a v a 2 s . c o m // ANONYMOUS REQUEST RENDERS LOGIN FORM HttpGet request = new HttpGet("/"); HttpResponse response = httpClient.execute(httpHost, request); assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpServletResponse.SC_OK)); assertThat(response.containsHeader("WWW-Form-Authenticate"), is(true)); dumpHttpResponse(response); EntityUtils.consumeQuietly(response.getEntity()); } { // AUTHENTICATION REQUEST HttpPost request = new HttpPost(privateAppFilter.getAuthenticationUri()); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("username", accessKey)); nvps.add(new BasicNameValuePair("password", secretKey)); request.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); HttpResponse response = httpClient.execute(httpHost, request); assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpServletResponse.SC_MOVED_TEMPORARILY)); dumpHttpResponse(response); EntityUtils.consumeQuietly(response.getEntity()); } { // ALREADY AUTHENTICATED REQUEST HttpGet request = new HttpGet("/"); HttpResponse response = httpClient.execute(httpHost, request); assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpServletResponse.SC_OK)); assertThat(response.containsHeader("x-response"), is(true)); dumpHttpResponse(response); EntityUtils.consumeQuietly(response.getEntity()); } }
From source file:com.hp.octane.integrations.services.rest.SSCRestClientImpl.java
private AuthToken.AuthTokenData sendReqAuth(SSCProjectConfiguration sscProjectConfiguration) { //"/{SSC Server Context}/api/v1" //String url = "http://" + serverURL + "/ssc/api/v1/projects?q=id:2743&fulltextsearch=true"; String url = sscProjectConfiguration.getSSCUrl() + "/api/v1/tokens"; HttpPost request = new HttpPost(url); request.addHeader("Authorization", sscProjectConfiguration.getSSCBaseAuthToken()); request.addHeader("Accept", "application/json"); request.addHeader("Host", getNetHost(sscProjectConfiguration.getSSCUrl())); request.addHeader("Content-Type", "application/json;charset=UTF-8"); String body = "{\"type\": \"UnifiedLoginToken\"}"; CloseableHttpResponse response = null; try {/*from w w w .j a v a2 s. c o m*/ HttpEntity entity = new ByteArrayEntity(body.getBytes(StandardCharsets.UTF_8)); request.setEntity(entity); response = httpClient.execute(request); if (succeeded(response.getStatusLine().getStatusCode())) { String toString = CIPluginSDKUtils.inputStreamToUTF8String(response.getEntity().getContent()); AuthToken authToken = new ObjectMapper().readValue(toString, TypeFactory.defaultInstance().constructType(AuthToken.class)); return authToken.getData(); } else { throw new PermanentException( "Couldn't Authenticate SSC user, need to check SSC configuration in Octane plugin"); } } catch (Throwable t) { throw new PermanentException(t); } finally { if (response != null) { EntityUtils.consumeQuietly(response.getEntity()); HttpClientUtils.closeQuietly(response); } } }
From source file:org.apache.solr.common.util.Utils.java
/** * If the passed entity has content, make sure it is fully * read and closed./*from w w w . j av a2s . com*/ * * @param entity to consume or null */ public static void consumeFully(HttpEntity entity) { if (entity != null) { try { // make sure the stream is full read readFully(entity.getContent()); } catch (UnsupportedOperationException e) { // nothing to do then } catch (IOException e) { // quiet } finally { // close the stream EntityUtils.consumeQuietly(entity); } } }
From source file:com.threadswarm.imagefeedarchiver.processor.RssItemProcessor.java
private void downloadRssMediaContent(ProcessedRssItem processedItem, RssMediaContent mediaContent) { DownloadStatus downloadStatus = DownloadStatus.FAILED; HttpEntity responseEntity = null;/*w w w .j a va2s.co m*/ try { String targetUrlString = mediaContent.getUrlString(); if (forceHttps) targetUrlString = FeedUtils.rewriteUrlStringToHttps(targetUrlString); URI targetURI = FeedUtils.getUriFromUrlString(targetUrlString); boolean freshURI = processedURISet.add(targetURI); if (!freshURI) { LOGGER.warn("Skipping previously processed URI: {}", targetURI); return; //abort processing } LOGGER.info("Attempting to download {}", targetURI); HttpGet imageGet = new HttpGet(targetURI); for (Header header : headerList) imageGet.addHeader(header); HttpResponse imageResponse = httpClient.execute(imageGet); String originalFileName = StringUtils.stripStart(targetURI.toURL().getFile(), "/"); originalFileName = StringUtils.replace(originalFileName, "/", "_"); File outputFile = getOutputFile(originalFileName); long expectedContentLength = FeedUtils.calculateBestExpectedContentLength(imageResponse, mediaContent); responseEntity = imageResponse.getEntity(); BufferedInputStream bis = null; DigestOutputStream fos = null; int bytesRead = 0; try { bis = new BufferedInputStream(responseEntity.getContent()); fos = new DigestOutputStream(new FileOutputStream(outputFile), MessageDigest.getInstance("SHA")); byte[] buffer = new byte[8192]; while ((bytesRead = bis.read(buffer, 0, buffer.length)) != -1) { fos.write(buffer, 0, bytesRead); } fos.flush(); MessageDigest messageDigest = fos.getMessageDigest(); byte[] digestBytes = messageDigest.digest(); String digestString = Hex.encodeHexString(digestBytes); LOGGER.info("Downloaded - {} (SHA: {})", targetURI, digestString); processedItem.setDownloadDate(new Date()); downloadStatus = DownloadStatus.COMPLETED; processedItem.setHash(digestString); processedItem.setFilename(outputFile.toString()); } catch (ConnectionClosedException e) { LOGGER.error("An Exception was thrown while attempting to read HTTP entity content", e); } catch (NoSuchAlgorithmException e) { LOGGER.error("The SHA-1 hashing algorithm is not available on this JVM", e); } finally { IOUtils.closeQuietly(bis); IOUtils.closeQuietly(fos); EntityUtils.consumeQuietly(responseEntity); if (downloadStatus == DownloadStatus.FAILED || (outputFile.exists() && outputFile.length() != expectedContentLength)) { LOGGER.warn("Deleted partial/failed file: {}", outputFile); outputFile.delete(); processedItem.setDownloadStatus(DownloadStatus.FAILED); } } } catch (IOException e) { LOGGER.error("An Exception was thrown while attempting to download image content", e); } catch (URISyntaxException e) { LOGGER.error("The supplied URI, {}, violates syntax rules", e); } finally { EntityUtils.consumeQuietly(responseEntity); } processedItem.setDownloadStatus(downloadStatus); itemDAO.save(processedItem); }
From source file:io.openvidu.java.client.Session.java
/** * Gets a new token associated to Session object configured with * <code>tokenOptions</code>. This always translates into a new request to * OpenVidu Server/*from w ww . jav a 2 s.c om*/ * * @return The generated token * * @throws OpenViduJavaClientException * @throws OpenViduHttpException */ @SuppressWarnings("unchecked") public String generateToken(TokenOptions tokenOptions) throws OpenViduJavaClientException, OpenViduHttpException { if (!this.hasSessionId()) { this.getSessionId(); } HttpPost request = new HttpPost(OpenVidu.urlOpenViduServer + OpenVidu.API_TOKENS); JSONObject json = new JSONObject(); json.put("session", this.sessionId); json.put("role", tokenOptions.getRole().name()); json.put("data", tokenOptions.getData()); if (tokenOptions.getKurentoOptions() != null) { JSONObject kurentoOptions = new JSONObject(); if (tokenOptions.getKurentoOptions().getVideoMaxRecvBandwidth() != null) { kurentoOptions.put("videoMaxRecvBandwidth", tokenOptions.getKurentoOptions().getVideoMaxRecvBandwidth()); } if (tokenOptions.getKurentoOptions().getVideoMinRecvBandwidth() != null) { kurentoOptions.put("videoMinRecvBandwidth", tokenOptions.getKurentoOptions().getVideoMinRecvBandwidth()); } if (tokenOptions.getKurentoOptions().getVideoMaxSendBandwidth() != null) { kurentoOptions.put("videoMaxSendBandwidth", tokenOptions.getKurentoOptions().getVideoMaxSendBandwidth()); } if (tokenOptions.getKurentoOptions().getVideoMinSendBandwidth() != null) { kurentoOptions.put("videoMinSendBandwidth", tokenOptions.getKurentoOptions().getVideoMinSendBandwidth()); } if (tokenOptions.getKurentoOptions().getAllowedFilters().length > 0) { JSONArray allowedFilters = new JSONArray(); for (String filter : tokenOptions.getKurentoOptions().getAllowedFilters()) { allowedFilters.add(filter); } kurentoOptions.put("allowedFilters", allowedFilters); } json.put("kurentoOptions", kurentoOptions); } StringEntity params; try { params = new StringEntity(json.toString()); } catch (UnsupportedEncodingException e1) { throw new OpenViduJavaClientException(e1.getMessage(), e1.getCause()); } request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); request.setEntity(params); HttpResponse response; try { response = OpenVidu.httpClient.execute(request); } catch (IOException e2) { throw new OpenViduJavaClientException(e2.getMessage(), e2.getCause()); } try { int statusCode = response.getStatusLine().getStatusCode(); if ((statusCode == org.apache.http.HttpStatus.SC_OK)) { String token = (String) httpResponseToJson(response).get("id"); log.info("Returning a TOKEN: {}", token); return token; } else { throw new OpenViduHttpException(statusCode); } } finally { EntityUtils.consumeQuietly(response.getEntity()); } }
From source file:com.vmware.photon.controller.model.adapters.vsphere.ovf.OvfRetriever.java
private StoringInputStream toStream(URI ovfUri) throws IOException { SAXParser saxParser = newSaxParser(); DefaultHandler handler = new DefaultHandler(); InputStream is;/* w ww .j a va2 s . com*/ HttpResponse response = null; HttpGet request = null; if (ovfUri.getScheme().equals("file")) { is = new FileInputStream(new File(ovfUri)); } else { request = new HttpGet(ovfUri); response = this.client.execute(request); if (response.getStatusLine().getStatusCode() != 200) { throw new IOException( "Ovf descriptor not found at " + ovfUri + ". Error code " + response.getStatusLine()); } is = response.getEntity().getContent(); } StoringInputStream storingInputStream = new StoringInputStream(is); try { saxParser.parse(storingInputStream, handler); if (response != null) { EntityUtils.consumeQuietly(response.getEntity()); } } catch (SAXException e) { // not a valid ovf - abort if (request != null) { request.abort(); } EntityUtils.consumeQuietly(response.getEntity()); throw new IOException("Ovf not a valid xml: " + e.getMessage(), e); } finally { //close stream, could be file IOUtils.closeQuietly(is); } return storingInputStream; }
From source file:com.turn.ttorrent.client.tracker.HTTPTrackerClient.java
@CheckForNull public static HTTPTrackerMessage toMessage(@Nonnull HttpResponse response, @CheckForSigned long maxContentLength) throws IOException { HttpEntity entity = response.getEntity(); if (entity == null) // Usually 204-no-content, etc. return null; try {// w w w .j ava 2 s. c o m if (maxContentLength >= 0) { long contentLength = entity.getContentLength(); if (contentLength >= 0) if (contentLength > maxContentLength) throw new IllegalArgumentException( "ContentLength was too big: " + contentLength + ": " + response); } InputStream in = entity.getContent(); if (in == null) return null; try { StreamBDecoder decoder = new StreamBDecoder(in); BEValue value = decoder.bdecodeMap(); Map<String, BEValue> params = value.getMap(); // TODO: "warning message" if (params.containsKey("failure reason")) return HTTPTrackerErrorMessage.fromBEValue(params); else return HTTPAnnounceResponseMessage.fromBEValue(params); } finally { IOUtils.closeQuietly(in); } } catch (InvalidBEncodingException e) { throw new IOException("Failed to parse response " + response, e); } catch (TrackerMessage.MessageValidationException e) { throw new IOException("Failed to parse response " + response, e); } finally { EntityUtils.consumeQuietly(entity); } }
From source file:org.wrml.runtime.service.rest.RestService.java
private <M extends Model> M readResponseModel(final HttpResponse response, final Context context, final Keys keys, final Dimensions dimensions) { if (response == null) { return null; }// w ww . j av a 2 s .c om final HttpEntity entity = response.getEntity(); if (entity == null) { return null; } // TODO: Initialize this from the response content-type header? As is, null will default to the default format. final URI formatUri = null; try { final InputStream in = entity.getContent(); return context.readModel(in, keys, dimensions, formatUri); } catch (final IllegalStateException | IOException e) { throw new ServiceException("Failed to read HTTP response content.", e, this); } finally { EntityUtils.consumeQuietly(entity); } }