List of usage examples for org.apache.http.client.utils HttpClientUtils closeQuietly
public static void closeQuietly(final HttpClient httpClient)
From source file:com.elastic.support.diagnostics.RestModule.java
public String submitRequest(String url) { HttpResponse response = null;/*from ww w. j a v a2 s . c om*/ String result = ""; try { HttpGet httpget = new HttpGet(url); response = client.execute(httpget); try { org.apache.http.HttpEntity entity = response.getEntity(); if (entity != null) { checkResponseCode(url, response); result = EntityUtils.toString(entity); } } catch (Exception e) { logger.error("Error handling response for " + url, e); } finally { HttpClientUtils.closeQuietly(response); } } catch (HttpHostConnectException e) { throw new RuntimeException("Error connecting to host " + url, e); } catch (Exception e) { if (e.getMessage().contains("401 Unauthorized")) { logger.error("Auth failure", e); throw new RuntimeException("Authentication failure: invalid login credentials.", e); } else { logger.error("Diagnostic query: " + url + "failed.", e); } } return result; }
From source file:com.mirth.connect.util.HttpUtil.java
public static void closeVeryQuietly(CloseableHttpResponse response) { try {//from w ww. j a v a 2 s . c om HttpClientUtils.closeQuietly(response); } catch (Throwable ignore) { } }
From source file:org.jboss.jdf.stacks.StacksFactory.java
public static Stacks create(final StacksConfiguration stacksConfig) throws IOException { InputStream inputStream = null; HttpResponse response = null;//from w ww . j av a 2 s . co m DefaultHttpClient client = null; final URL url = stacksConfig.getUrl(); try { if (url.getProtocol().startsWith("file")) { inputStream = new FileInputStream(new File(url.toURI())); } else { client = new DefaultHttpClient(); configureProxy(client, stacksConfig); final HttpGet method = new HttpGet(url.toURI()); response = client.execute(method); final HttpEntity entity = response.getEntity(); if (entity != null) { inputStream = entity.getContent(); } } return new Parser().parse(inputStream); } catch (URISyntaxException e) { // TODO cleanup throw new IllegalStateException(e); } finally { HttpClientUtils.closeQuietly(response); HttpClientUtils.closeQuietly(client); Parser.safeClose(inputStream); } }
From source file:org.apache.sling.tooling.lc.jira.IssueFinder.java
public List<Issue> findIssues(List<String> issueKeys) throws IOException { HttpClient client = new DefaultHttpClient(); HttpGet get;/*from w w w .j av a 2s .c o m*/ try { URIBuilder builder = new URIBuilder("https://issues.apache.org/jira/rest/api/2/search") .addParameter("jql", "key in (" + String.join(",", issueKeys) + ")") .addParameter("fields", "key,summary"); get = new HttpGet(builder.build()); } catch (URISyntaxException e) { // never happens throw new RuntimeException(e); } HttpResponse response = client.execute(get); try { if (response.getStatusLine().getStatusCode() != 200) { throw new IOException("Search call returned status " + response.getStatusLine().getStatusCode()); } try (Reader reader = new InputStreamReader(response.getEntity().getContent(), "UTF-8")) { Response apiResponse = new Gson().fromJson(reader, Response.class); List<Issue> issues = apiResponse.getIssues(); Collections.sort(issues); return issues; } } finally { HttpClientUtils.closeQuietly(client); } }
From source file:org.alfresco.selenium.FetchCSS.java
/** * Extract additional content found in css. * @param source css //from w w w . j a va 2s . co m * @return collection of files to get * @throws IOException if error */ public static void getCSSFiles(File file, WebDriver driver) throws IOException { if (file == null) { throw new IllegalArgumentException("CSS source is required"); } String source = FileUtils.readFileToString(file); source = source.replaceAll("}", "}\n"); String domain = getHost(driver); CloseableHttpClient client = FetchHttpClient.getHttpClient(driver); StringBuffer sb = new StringBuffer(); try { //Extract all source files Matcher matchSrc = CSS_BACKGOUND_IMG_PATTERN.matcher(source); while (matchSrc.find()) { //Change extracted source file to absolute urls String fileSourceOri = matchSrc.group(0); String fileSource = fileSourceOri.replaceAll("\"", ""); if (!fileSource.startsWith("data:image")) { if (fileSource.startsWith("//")) { fileSource = fileSource.replace("//", "http://"); } else if (fileSource.startsWith("/")) { fileSource = fileSource.replaceFirst("/", domain + "/"); } //Add to collection of paths for downloading getCssFile(fileSource, fileSourceOri, client); } //Amend path to point to file in the same directory if (!fileSourceOri.startsWith("//") || fileSourceOri.startsWith("\"/")) { String t = fileSourceOri.replaceFirst("\"/", "\""); matchSrc.appendReplacement(sb, t); } else { matchSrc.appendReplacement(sb, fileSourceOri); } } if (sb.length() < 1) { FileUtils.writeStringToFile(file, source); } else { FileUtils.writeStringToFile(file, sb.toString()); } } finally { HttpClientUtils.closeQuietly(client); } }
From source file:org.openrdf.http.client.SesameClientImpl.java
public synchronized void shutDown() { if (executor != null) { executor.shutdown();// w w w . j av a 2 s . com executor = null; } if (httpClient != null) { HttpClientUtils.closeQuietly(httpClient); httpClient = null; } }
From source file:com.elastic.support.diagnostics.RestModule.java
public void submitRequest(String url, String queryName, String destination) { HttpResponse response = null;/* w w w . j av a2 s.c o m*/ InputStream responseStream = null; try { FileOutputStream fos = new FileOutputStream(destination); HttpGet httpget = new HttpGet(url); response = client.execute(httpget); try { org.apache.http.HttpEntity entity = response.getEntity(); if (entity != null) { checkResponseCode(queryName, response); responseStream = entity.getContent(); IOUtils.copy(responseStream, fos); } else { Files.write(Paths.get(destination), ("No results for:" + queryName).getBytes()); } } catch (Exception e) { logger.error("Error writing response for " + queryName + " to disk.", e); } finally { HttpClientUtils.closeQuietly(response); Thread.sleep(2000); } } catch (Exception e) { if (url.contains("_license")) { logger.info("There were no licenses installed"); } else if (e.getMessage().contains("401 Unauthorized")) { logger.error("Auth failure", e); throw new RuntimeException("Authentication failure: invalid login credentials.", e); } else { logger.error("Diagnostic query: " + queryName + "failed.", e); } } logger.info("Diagnostic query: " + queryName + " was retrieved and saved to disk."); }
From source file:com.elastic.support.util.RestExec.java
public String execBasic(String url) { HttpResponse response = null;//from w w w . j a v a2 s . c o m String responseString = ""; boolean completed = false; String message = "An error occurred during REST call: " + url + " Check logs for more information. "; try { response = exec(url); int status = response.getStatusLine().getStatusCode(); if (status != 200) { if (status == 401) { message = message + " Invalid authentication credentials provided."; } else if (status == 403) { message = message + " Insufficient authority to execute query."; } logger.log(SystemProperties.DIAG, "{} could not be retrieved. Status:{}", url, status); logger.log(SystemProperties.DIAG, "{}", getResponseString(response)); } else { completed = true; responseString = getResponseString(response); } } catch (Exception e) { logger.log(SystemProperties.DIAG, "Exception during REST call", e); message = message + e.getMessage(); } finally { HttpClientUtils.closeQuietly(response); } if (!completed) { throw new RuntimeException(message); } return responseString; }
From source file:org.jboss.quickstarts.wfk.travelagent.flight.FlightService.java
/** * <p>Returns a List of all persisted {@link Contact} objects, sorted alphabetically by last name.<p/> * /*from w w w . j a va2s. c om*/ * @return List of Contact objects */ JSONArray findAllOrderedByName() { try { URI uri = new URIBuilder().setScheme("http").setHost("jbosscontactsangularjs-110336260.rhcloud.com") .setPath("/rest/flights").build(); HttpGet req = new HttpGet(uri); CloseableHttpResponse response = httpClient.execute(req); String responseBody = EntityUtils.toString(response.getEntity()); JSONArray responseJson = new JSONArray(responseBody); HttpClientUtils.closeQuietly(response); return responseJson; } catch (Exception e) { log.info(e.toString()); return null; } }
From source file:com.flipkart.flux.client.runtime.FluxRuntimeConnectorHttpImpl.java
public FluxRuntimeConnectorHttpImpl(Long connectionTimeout, Long socketTimeout, String fluxEndpoint) { objectMapper = new ObjectMapper(); this.fluxEndpoint = fluxEndpoint; RequestConfig clientConfig = RequestConfig.custom().setConnectTimeout((connectionTimeout).intValue()) .setSocketTimeout((socketTimeout).intValue()) .setConnectionRequestTimeout((socketTimeout).intValue()).build(); PoolingHttpClientConnectionManager syncConnectionManager = new PoolingHttpClientConnectionManager(); syncConnectionManager.setMaxTotal(MAX_TOTAL); syncConnectionManager.setDefaultMaxPerRoute(MAX_PER_ROUTE); closeableHttpClient = HttpClientBuilder.create().setDefaultRequestConfig(clientConfig) .setConnectionManager(syncConnectionManager).build(); Runtime.getRuntime().addShutdownHook(new Thread(() -> { HttpClientUtils.closeQuietly(closeableHttpClient); }));//from ww w . j a va 2s .co m }