List of usage examples for org.apache.http.util EntityUtils consumeQuietly
public static void consumeQuietly(HttpEntity httpEntity)
From source file:org.scassandra.http.client.PrimingClient.java
private void httpDelete(String url) { HttpDelete delete = new HttpDelete(url); CloseableHttpResponse httpResponse = null; try {/* w w w . j a v a2 s . c om*/ httpResponse = httpClient.execute(delete); EntityUtils.consumeQuietly(httpResponse.getEntity()); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != 200) { String errorMessage = String.format("Clearing of primes failed with http status %s", statusCode); LOGGER.info(errorMessage); throw new PrimeFailedException(errorMessage); } } catch (IOException e) { LOGGER.info(DELETING_OF_PRIMES_FAILED, e); throw new PrimeFailedException(DELETING_OF_PRIMES_FAILED, e); } finally { if (httpResponse != null) { EntityUtils.consumeQuietly(httpResponse.getEntity()); } } }
From source file:com.cloudbees.tomcat.valves.PrivateAppValveIntegratedTest.java
private void authentication_scenario(PrivateAppValve.AuthenticationEntryPoint authenticationEntryPoint) throws Exception { privateAppValve.setAuthenticationEntryPoint(authenticationEntryPoint); {//from w ww.j a v a2 s. co m // AUTHENTICATION REQUEST HttpRequest request; switch (authenticationEntryPoint) { case BASIC_AUTH: request = new HttpGet("/"); request.addHeader("Authorization", buildBasicAuthHeader()); break; case HTTP_PARAM_AUTH: URI uri = new URIBuilder("/") .addParameter(privateAppValve.getAuthenticationParameterName(), secretKey).build(); request = new HttpGet(uri); break; case HTTP_HEADER_AUTH: request = new HttpGet("/"); request.addHeader(privateAppValve.getAuthenticationHeaderName(), secretKey); break; default: throw new IllegalStateException(); } 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()); } { // 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.supermap.desktop.icloud.online.AuthenticatorImpl.java
private RequestContent buildRequestContent(CloseableHttpResponse response) throws AuthenticationException, ParseException, IOException { RequestContent content = new RequestContent(); HttpEntity httpEntity = response.getEntity(); int code = response.getStatusLine().getStatusCode(); if (httpEntity == null) { throw new AuthenticationException("login failed.code:" + code); }//from w ww. j ava 2s.c om String responseInfo = EntityUtils.toString(httpEntity, StandardCharsets.UTF_8); if (200 == response.getStatusLine().getStatusCode()) { try { content = JSON.parseObject(responseInfo, RequestContent.class); content.jsessionid = getJSessionIdFromResponse(response); } catch (JSONException e) { throw new AuthenticationException("invalid response:" + responseInfo); } finally { EntityUtils.consumeQuietly(httpEntity); } } else { throw new AuthenticationException("login failed.code:" + response.getStatusLine().getStatusCode() + ".response:" + getEntityText(response)); } return content; }
From source file:org.ops4j.pax.web.itest.base.HttpTestClient.java
public String testAsyncWebPath(String path, String expectedContent, int httpRC, boolean authenticate, BasicHttpContext basicHttpContext) throws Exception { int count = 0; while (!checkServer(path) && count++ < 5) { if (count > 5) { break; }/*w ww.j a v a 2 s. c om*/ } HttpResponse response = null; response = getHttpResponse(path, authenticate, basicHttpContext, true); assertEquals("HttpResponseCode", httpRC, response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() == 403) { EntityUtils.consumeQuietly(response.getEntity()); return null; } String responseBodyAsString = EntityUtils.toString(response.getEntity()); if (expectedContent != null) { assertTrue("Content: " + responseBodyAsString, responseBodyAsString.contains(expectedContent)); } return responseBodyAsString; }
From source file:com.hp.octane.integrations.services.rest.OctaneRestClientImpl.java
private OctaneResponse executeRequest(OctaneRequest request, OctaneConfiguration configuration) throws IOException { OctaneResponse result;// w w w .j a v a 2 s .c o m HttpClientContext context; HttpUriRequest uriRequest = null; HttpResponse httpResponse = null; OctaneResponse loginResponse; if (LWSSO_TOKEN == null) { logger.info("initial login"); loginResponse = login(configuration); if (loginResponse.getStatus() != 200) { logger.error("failed on initial login, status " + loginResponse.getStatus()); return loginResponse; } } try { // we are running this loop either once or twice: once - regular flow, twice - when retrying after re-login attempt for (int i = 0; i < 2; i++) { uriRequest = createHttpRequest(request); context = createHttpContext(request.getUrl(), false); synchronized (REQUESTS_LIST_LOCK) { ongoingRequests.add(uriRequest); } httpResponse = httpClient.execute(uriRequest, context); synchronized (REQUESTS_LIST_LOCK) { ongoingRequests.remove(uriRequest); } if (AUTHENTICATION_ERROR_CODES.contains(httpResponse.getStatusLine().getStatusCode())) { logger.info("doing RE-LOGIN due to status " + httpResponse.getStatusLine().getStatusCode() + " received while calling " + request.getUrl()); EntityUtils.consumeQuietly(httpResponse.getEntity()); HttpClientUtils.closeQuietly(httpResponse); loginResponse = login(configuration); if (loginResponse.getStatus() != 200) { logger.error("failed to RE-LOGIN with status " + loginResponse.getStatus() + ", won't attempt the original request anymore"); return loginResponse; } else { logger.info("re-attempting the original request (" + request.getUrl() + ") having successful RE-LOGIN"); } } else { refreshSecurityToken(context, false); break; } } result = createNGAResponse(httpResponse); } catch (IOException ioe) { logger.debug("failed executing " + request, ioe); throw ioe; } finally { if (uriRequest != null && ongoingRequests.contains(uriRequest)) { synchronized (REQUESTS_LIST_LOCK) { ongoingRequests.remove(uriRequest); } } if (httpResponse != null) { EntityUtils.consumeQuietly(httpResponse.getEntity()); HttpClientUtils.closeQuietly(httpResponse); } } return result; }
From source file:org.alfresco.test.util.AlfrescoHttpClient.java
/** * Parses http response stream into a {@link JSONObject}. * // w ww . j a v a2 s .c om * @param entity Http response entity * @return {@link JSONObject} response */ public JSONObject readStream(final HttpEntity entity) { String rsp = null; try { rsp = EntityUtils.toString(entity, UTF_8_ENCODING); } catch (Throwable ex) { throw new RuntimeException("Failed to read HTTP entity stream.", ex); } finally { EntityUtils.consumeQuietly(entity); } try { JSONParser parser = new JSONParser(); JSONObject result = (JSONObject) parser.parse(rsp); return result; } catch (Throwable e) { throw new RuntimeException("Failed to convert response to JSON: \n" + " Response: \r\n" + rsp, e); } }
From source file:com.meltmedia.cadmium.cli.DeployCommand.java
/** * Checks via an http options request that the endpoint exists to check for deployment state. * @param warName//from w w w . j a v a 2 s .c o m * @param url * @param client * @return */ public boolean canCheckWar(String warName, String url, HttpClient client) { HttpOptions opt = new HttpOptions(url + "/" + warName); try { HttpResponse response = client.execute(opt); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { Header allowHeader[] = response.getHeaders("Allow"); for (Header allow : allowHeader) { List<String> values = Arrays.asList(allow.getValue().toUpperCase().split(",")); if (values.contains("GET")) { return true; } } } EntityUtils.consumeQuietly(response.getEntity()); } catch (Exception e) { log.warn("Failed to check if endpoint exists.", e); } finally { opt.releaseConnection(); } return false; }
From source file:com.vmware.photon.controller.model.adapters.vsphere.ovf.OvfRetriever.java
/** * If ovaOrOvfUri points to a OVA it will be download locally and extracted. The uri is considered OVA if it is * in tar format and there is at least one .ovf inside. * * @param ovaOrOvfUri//from w w w . j a v a 2 s .c o m * @return the first .ovf file from the extracted tar of the input parameter if it's a local file or not a * tar archive */ public URI downloadIfOva(URI ovaOrOvfUri) throws IOException { if (ovaOrOvfUri.getScheme().equals("file")) { // local files are assumed to be ovfs return ovaOrOvfUri; } HttpGet get = new HttpGet(ovaOrOvfUri); HttpResponse check = null; logger.debug("Downloading ovf/ova from {}", ovaOrOvfUri); try { check = this.client.execute(get); byte[] buffer = new byte[TAR_MAGIC_OFFSET + TAR_MAGIC.length]; int read = IOUtils.read(check.getEntity().getContent(), buffer); if (read != buffer.length) { // not a tar file, probably OVF, lets caller decide further return ovaOrOvfUri; } for (int i = 0; i < TAR_MAGIC.length; i++) { byte b = buffer[TAR_MAGIC_OFFSET + i]; if (b != TAR_MAGIC[i] && b != TAR_MAGIC2[i]) { // magic numbers don't match logger.info("{} is not a tar file, assuming OVF", ovaOrOvfUri); return ovaOrOvfUri; } } } finally { get.abort(); if (check != null) { EntityUtils.consumeQuietly(check.getEntity()); } } // it's an OVA (at least a tar file), download to a local folder String folderName = hash(ovaOrOvfUri); File destination = new File(getBaseOvaExtractionDir(), folderName); if (new File(destination, MARKER_FILE).isFile()) { // marker file exists so the archive is already downloaded logger.info("Marker file for {} exists in {}, not downloading again", ovaOrOvfUri, destination); return findFirstOvfInFolder(destination); } destination.mkdirs(); logger.info("Downloading OVA to {}", destination); get = new HttpGet(ovaOrOvfUri); HttpResponse response = null; try { response = this.client.execute(get); TarArchiveInputStream tarStream = new TarArchiveInputStream(response.getEntity().getContent()); TarArchiveEntry entry; while ((entry = tarStream.getNextTarEntry()) != null) { extractEntry(tarStream, destination, entry); } } finally { if (response != null) { EntityUtils.consumeQuietly(response.getEntity()); } } // store download progress writeMarkerFile(destination, ovaOrOvfUri); return findFirstOvfInFolder(destination); }