List of usage examples for org.apache.http.client.utils HttpClientUtils closeQuietly
public static void closeQuietly(final HttpClient httpClient)
From source file:com.github.technosf.posterer.modules.commons.transport.CommonsResponseModelTaskImpl.java
/** * {@inheritDoc}//from w w w. j av a2 s . co m * * @see com.github.technosf.posterer.models.impl.base.AbstractResponseModelTask#closeClient() */ @Override protected void closeClient() { HttpClientUtils.closeQuietly(getValue()); }
From source file:com.mirth.connect.client.core.ConnectServiceUtil.java
public static List<Notification> getNotifications(String serverId, String mirthVersion, Map<String, String> extensionVersions, String[] protocols, String[] cipherSuites) throws Exception { CloseableHttpClient client = null;/*from ww w. j av a 2s.c o m*/ HttpPost post = new HttpPost(); CloseableHttpResponse response = null; List<Notification> allNotifications = new ArrayList<Notification>(); try { ObjectMapper mapper = new ObjectMapper(); String extensionVersionsJson = mapper.writeValueAsString(extensionVersions); NameValuePair[] params = { new BasicNameValuePair("op", NOTIFICATION_GET), new BasicNameValuePair("serverId", serverId), new BasicNameValuePair("version", mirthVersion), new BasicNameValuePair("extensionVersions", extensionVersionsJson) }; RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT) .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build(); post.setURI(URI.create(URL_CONNECT_SERVER + URL_NOTIFICATION_SERVLET)); post.setEntity(new UrlEncodedFormEntity(Arrays.asList(params), Charset.forName("UTF-8"))); HttpClientContext postContext = HttpClientContext.create(); postContext.setRequestConfig(requestConfig); client = getClient(protocols, cipherSuites); response = client.execute(post, postContext); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if ((statusCode == HttpStatus.SC_OK)) { HttpEntity responseEntity = response.getEntity(); Charset responseCharset = null; try { responseCharset = ContentType.getOrDefault(responseEntity).getCharset(); } catch (Exception e) { responseCharset = ContentType.TEXT_PLAIN.getCharset(); } String responseContent = IOUtils.toString(responseEntity.getContent(), responseCharset).trim(); JsonNode rootNode = mapper.readTree(responseContent); for (JsonNode childNode : rootNode) { Notification notification = new Notification(); notification.setId(childNode.get("id").asInt()); notification.setName(childNode.get("name").asText()); notification.setDate(childNode.get("date").asText()); notification.setContent(childNode.get("content").asText()); allNotifications.add(notification); } } else { throw new ClientException("Status code: " + statusCode); } } catch (Exception e) { throw e; } finally { HttpClientUtils.closeQuietly(response); HttpClientUtils.closeQuietly(client); } return allNotifications; }
From source file:com.hp.mqm.client.TestSupportClient.java
private JSONObject postEntity(String uri, Long workspace, JSONObject entityObject) throws IOException { URI requestURI;//from w ww. j a va2 s . c o m if (workspace != null) { requestURI = createWorkspaceApiUri(uri, workspace); } else { requestURI = createSharedSpaceApiUri(uri); } HttpPost request = new HttpPost(requestURI); JSONArray data = new JSONArray(); data.add(entityObject); JSONObject body = new JSONObject(); body.put("data", data); request.setEntity(new StringEntity(body.toString(), ContentType.APPLICATION_JSON)); HttpResponse response = null; try { response = execute(request); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) { String payload = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); throw new IOException("Posting failed with status code " + response.getStatusLine().getStatusCode() + ", reason " + response.getStatusLine().getReasonPhrase() + " and payload: " + payload); } ByteArrayOutputStream result = new ByteArrayOutputStream(); response.getEntity().writeTo(result); JSONObject jsonObject = JSONObject.fromObject(new String(result.toByteArray(), "UTF-8")); return jsonObject.getJSONArray("data").getJSONObject(0); } finally { HttpClientUtils.closeQuietly(response); } }
From source file:com.google.cloud.tools.intellij.stats.GoogleUsageTracker.java
private void sendPing(@NotNull final List<? extends NameValuePair> postData) { ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { public void run() { CloseableHttpClient client = HttpClientBuilder.create().setUserAgent(userAgent).build(); HttpPost request = new HttpPost(ANALYTICS_URL); try { request.setEntity(new UrlEncodedFormEntity(postData)); CloseableHttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); if (status.getStatusCode() >= 300) { logger.debug("Non 200 status code : " + status.getStatusCode() + " - " + status.getReasonPhrase()); }/*from www. j a v a2 s . c o m*/ } catch (IOException ex) { logger.debug("IOException during Analytics Ping", ex.getMessage()); } finally { HttpClientUtils.closeQuietly(client); } } }); }
From source file:com.jivesoftware.os.routing.bird.http.client.ApacheHttpClient441BackedHttpClient.java
private HttpStreamResponse executeStream(HttpRequestBase requestBase) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, IOException { applyHeadersCommonToAllRequests(requestBase); activeCount.incrementAndGet();//from ww w. j a v a 2 s . com CloseableHttpResponse response = client.execute(requestBase); StatusLine statusLine = response.getStatusLine(); int status = statusLine.getStatusCode(); LOG.debug("Got status: {} {}", status, statusLine.getReasonPhrase()); if (status < 200 || status >= 300) { activeCount.decrementAndGet(); HttpClientUtils.closeQuietly(response); requestBase.reset(); throw new IOException("Bad status : " + statusLine); } return new HttpStreamResponse(statusLine.getStatusCode(), statusLine.getReasonPhrase(), response, response.getEntity().getContent(), requestBase, activeCount); }
From source file:com.hp.mqm.clt.TestSupportClient.java
protected <E> PagedList<E> getEntities(URI uri, int offset, EntityFactory<E> factory) { HttpGet request = new HttpGet(uri); CloseableHttpResponse response = null; try {/* www . j av a 2s .c om*/ response = execute(request); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new RuntimeException("Entity retrieval failed"); } String entitiesJson = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); JSONObject entities = JSONObject.fromObject(entitiesJson); LinkedList<E> items = new LinkedList<E>(); for (JSONObject entityObject : getJSONObjectCollection(entities, "data")) { items.add(factory.create(entityObject.toString())); } return new PagedList<E>(items, offset, entities.getInt("total_count")); } catch (IOException e) { throw new RuntimeException("Cannot retrieve entities from MQM.", e); } finally { HttpClientUtils.closeQuietly(response); } }
From source file:org.jboss.quickstarts.wfk.travelagent.travelplan.TravelPlanService.java
private Long bookTaxi(TravelSketch travelSketch) throws Exception { URI uri = new URIBuilder().setScheme("http").setHost("jbosscontactsangularjs-110060653.rhcloud.com") .setPath("/rest/bookings").build(); HttpPost req = new HttpPost(uri); StringEntity params = new StringEntity("{\"customerId\":\"" + travelAgentTaxi.toString() + "\",\"taxiId\":\"" + travelSketch.getTaxiId().toString() + "\",\"bookingDate\":\"" + travelSketch.getBookingDate() + "\"}"); req.addHeader("Content-Type", "application/json"); req.setEntity(params);/*from w w w. j a v a 2 s.c o m*/ CloseableHttpResponse response = httpClient.execute(req); if (response.getStatusLine().getStatusCode() != 201) { throw new Exception("Failed to create a flight booking"); } String responseBody = EntityUtils.toString(response.getEntity()); JSONObject responseJson = new JSONObject(responseBody); long rtn = responseJson.getLong("id"); HttpClientUtils.closeQuietly(response); return rtn; }
From source file:org.jboss.additional.testsuite.jdkall.present.clustering.cluster.web.ClusteredWebSimpleTestCase.java
@Test @OperateOnDeployment(DEPLOYMENT_2) // For change, operate on the 2nd deployment first public void testSessionReplication( @ArquillianResource(SimpleServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1, @ArquillianResource(SimpleServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2) throws IOException, URISyntaxException { URI url1 = SimpleServlet.createURI(baseURL1); URI url2 = SimpleServlet.createURI(baseURL2); try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) { HttpResponse response = client.execute(new HttpGet(url1)); try {//from w w w . j a v a2 s . c o m Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(1, Integer.parseInt(response.getFirstHeader("value").getValue())); } finally { HttpClientUtils.closeQuietly(response); } // Lets do this twice to have more debug info if failover is slow. response = client.execute(new HttpGet(url1)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(2, Integer.parseInt(response.getFirstHeader("value").getValue())); } finally { HttpClientUtils.closeQuietly(response); } // Lets wait for the session to replicate waitForReplication(GRACE_TIME_TO_REPLICATE); // Now check on the 2nd server response = client.execute(new HttpGet(url2)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(3, Integer.parseInt(response.getFirstHeader("value").getValue())); } finally { HttpClientUtils.closeQuietly(response); } // Lets do one more check. response = client.execute(new HttpGet(url2)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(4, Integer.parseInt(response.getFirstHeader("value").getValue())); } finally { HttpClientUtils.closeQuietly(response); } } }