List of usage examples for org.apache.http.client.utils HttpClientUtils closeQuietly
public static void closeQuietly(final HttpClient httpClient)
From source file:com.hp.mqm.clt.TestSupportClient.java
private JSONObject postEntity(String uri, JSONObject entityObject) throws IOException { URI requestURI = createWorkspaceApiUri(uri); HttpPost request = new HttpPost(requestURI); JSONArray data = new JSONArray(); data.add(entityObject);/*from w ww . j a v a 2 s . co m*/ JSONObject body = new JSONObject(); body.put("data", data); request.setEntity(new StringEntity(body.toString(), ContentType.APPLICATION_JSON)); CloseableHttpResponse 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:org.sonatype.security.realms.kenai.KenaiRealm.java
private boolean authenticateViaUrl(final UsernamePasswordToken usernamePasswordToken) { final HttpClient client = hc4Provider.createHttpClient(); try {/* w w w . ja v a 2s . c o m*/ final String url = kenaiRealmConfiguration.getConfiguration().getBaseUrl() + "api/login/authenticate.json"; final List<NameValuePair> nameValuePairs = Lists.newArrayListWithCapacity(2); nameValuePairs.add(new BasicNameValuePair("username", usernamePasswordToken.getUsername())); nameValuePairs.add(new BasicNameValuePair("password", new String(usernamePasswordToken.getPassword()))); final HttpPost post = new HttpPost(url); post.setEntity(new UrlEncodedFormEntity(nameValuePairs, Consts.UTF_8)); final HttpResponse response = client.execute(post); try { logger.debug("Kenai Realm user \"{}\" validated against URL={} as {}", usernamePasswordToken.getUsername(), url, response.getStatusLine()); final boolean success = response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() <= 299; return success; } finally { HttpClientUtils.closeQuietly(response); } } catch (IOException e) { logger.info("Kenai Realm was unable to perform authentication", e); return false; } }
From source file:com.mirth.connect.plugins.httpauth.oauth2.OAuth2Authenticator.java
@Override public AuthenticationResult authenticate(RequestInfo request) throws Exception { OAuth2HttpAuthProperties properties = getReplacedProperties(request); CloseableHttpClient client = null;/*from w w w . j ava 2 s.c o m*/ CloseableHttpResponse response = null; try { // Create and configure the client and context RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()); ConnectorPluginProperties pluginProperties = null; if (CollectionUtils.isNotEmpty(properties.getConnectorPluginProperties())) { pluginProperties = properties.getConnectorPluginProperties().iterator().next(); } provider.getHttpConfiguration().configureSocketFactoryRegistry(pluginProperties, socketFactoryRegistry); BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager( socketFactoryRegistry.build()); httpClientConnectionManager.setSocketConfig(SocketConfig.custom().setSoTimeout(SOCKET_TIMEOUT).build()); HttpClientBuilder clientBuilder = HttpClients.custom() .setConnectionManager(httpClientConnectionManager); HttpUtil.configureClientBuilder(clientBuilder); client = clientBuilder.build(); HttpClientContext context = HttpClientContext.create(); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(SOCKET_TIMEOUT) .setSocketTimeout(SOCKET_TIMEOUT).setStaleConnectionCheckEnabled(true).build(); context.setRequestConfig(requestConfig); URIBuilder uriBuilder = new URIBuilder(properties.getVerificationURL()); // Add query parameters if (properties.getTokenLocation() == TokenLocation.QUERY) { List<String> paramList = request.getQueryParameters().get(properties.getLocationKey()); if (CollectionUtils.isNotEmpty(paramList)) { for (String value : paramList) { uriBuilder.addParameter(properties.getLocationKey(), value); } } } // Build the final URI and create a GET request HttpGet httpGet = new HttpGet(uriBuilder.build()); // Add headers if (properties.getTokenLocation() == TokenLocation.HEADER) { List<String> headerList = request.getHeaders().get(properties.getLocationKey()); if (CollectionUtils.isNotEmpty(headerList)) { for (String value : headerList) { httpGet.addHeader(properties.getLocationKey(), value); } } } // Execute the request response = client.execute(httpGet, context); // Determine authentication from the status code if (response.getStatusLine().getStatusCode() < 400) { return AuthenticationResult.Success(); } else { return AuthenticationResult.Failure(); } } finally { HttpClientUtils.closeQuietly(response); HttpClientUtils.closeQuietly(client); } }
From source file:org.jboss.as.test.clustering.cluster.singleton.SingletonDeploymentTestCase.java
@Test public void test(@ArquillianResource @OperateOnDeployment(DEPLOYMENT_1) ManagementClient client1, @ArquillianResource @OperateOnDeployment(DEPLOYMENT_2) ManagementClient client2, @ArquillianResource(TraceServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1, @ArquillianResource(TraceServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2) throws Exception { // In order to test undeploy in case another node becomes elected as the master, we need an election policy that will ever trigger that code path (WFLY-8184) executeOnNodesAndReload(// w ww. ja v a 2s. c om "/subsystem=singleton/singleton-policy=default/election-policy=simple:write-attribute(name=name-preferences,value=" + Arrays.toString(NODES) + ")", client1, client2); this.deploy(SINGLETON_DEPLOYMENT_1); Thread.sleep(DELAY); this.deploy(SINGLETON_DEPLOYMENT_2); Thread.sleep(DELAY); URI uri1 = TraceServlet.createURI(new URL(baseURL1.getProtocol(), baseURL1.getHost(), baseURL1.getPort(), "/" + this.deploymentName + "/")); URI uri2 = TraceServlet.createURI(new URL(baseURL2.getProtocol(), baseURL2.getHost(), baseURL2.getPort(), "/" + this.deploymentName + "/")); try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) { HttpResponse response = client.execute(new HttpGet(uri1)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); } finally { HttpClientUtils.closeQuietly(response); } response = client.execute(new HttpGet(uri2)); try { Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode()); } finally { HttpClientUtils.closeQuietly(response); } this.undeploy(SINGLETON_DEPLOYMENT_1); Thread.sleep(DELAY); response = client.execute(new HttpGet(uri1)); try { Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode()); } finally { HttpClientUtils.closeQuietly(response); } response = client.execute(new HttpGet(uri2)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); } finally { HttpClientUtils.closeQuietly(response); } this.deploy(SINGLETON_DEPLOYMENT_1); Thread.sleep(DELAY); response = client.execute(new HttpGet(uri1)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); } finally { HttpClientUtils.closeQuietly(response); } response = client.execute(new HttpGet(uri2)); try { Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode()); } finally { HttpClientUtils.closeQuietly(response); } this.undeploy(SINGLETON_DEPLOYMENT_2); Thread.sleep(DELAY); response = client.execute(new HttpGet(uri1)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); } finally { HttpClientUtils.closeQuietly(response); } response = client.execute(new HttpGet(uri2)); try { Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode()); } finally { HttpClientUtils.closeQuietly(response); } this.deploy(SINGLETON_DEPLOYMENT_2); Thread.sleep(DELAY); response = client.execute(new HttpGet(uri1)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); } finally { HttpClientUtils.closeQuietly(response); } response = client.execute(new HttpGet(uri2)); try { Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode()); } finally { HttpClientUtils.closeQuietly(response); } } finally { this.undeploy(SINGLETON_DEPLOYMENT_1, SINGLETON_DEPLOYMENT_2); executeOnNodesAndReload( "/subsystem=singleton/singleton-policy=default/election-policy=simple:undefine-attribute(name=name-preferences)", client1, client2); } }
From source file:cloudfoundry.norouter.f5.client.HttpClientIControlClient.java
@Override public void close() { HttpClientUtils.closeQuietly(httpClient); }
From source file:cf.client.DefaultUaa.java
@Override public TokenContents checkToken(String client, String clientSecret, Token token) { try {/*from www .j a v a2s . c o m*/ final URI checkTokenUri = uaa.resolve(CHECK_TOKEN); final HttpPost post = new HttpPost(checkTokenUri); post.setHeader(createClientCredentialsHeader(client, clientSecret)); final NameValuePair tokenType = new BasicNameValuePair("token_type", token.getType().getValue()); final NameValuePair tokenValue = new BasicNameValuePair("token", token.getAccessToken()); post.setEntity(new UrlEncodedFormEntity(Arrays.asList(tokenType, tokenValue))); final HttpResponse response = httpClient.execute(post); try { validateResponse(response); final HttpEntity entity = response.getEntity(); final InputStream content = entity.getContent(); return mapper.readValue(content, TokenContents.class); } finally { HttpClientUtils.closeQuietly(response); } } catch (IOException e) { throw new RuntimeException(e); } }
From source file:com.seyren.core.service.notification.BigPandaNotificationService.java
@Override public void sendNotification(Check check, Subscription subscription, List<Alert> alerts) throws NotificationFailedException { String bigPandaAppKey = StringUtils.trimToNull(subscription.getTarget()); if (bigPandaAppKey == null) { LOGGER.warn(//from w ww . j a v a2 s . co m "BigPanda Integration App Key in Subscription Target needs to be set before sending notifications to BigPanda"); return; } for (Alert alert : alerts) { String level = alert.getToType().toString(); String bigPandaStatus; if (level == "ERROR") { bigPandaStatus = "critical"; } else if (level == "WARN") { bigPandaStatus = "warning"; } else if (level == "OK") { bigPandaStatus = "ok"; } else { LOGGER.warn("Unknown level {} specified in alert. Can't send to BigPanda.", level); return; } String checkUrl = seyrenConfig.getBaseUrl() + "/#/checks/" + check.getId(); Long tstamp = alert.getTimestamp().getMillis() / 1000; Map<String, Object> body = new HashMap<String, Object>(); body.put("app_key", bigPandaAppKey); body.put("status", bigPandaStatus); body.put("service", check.getName()); body.put("check", alert.getTarget()); body.put("description", check.getDescription()); body.put("timestamp", tstamp); body.put("seyrenCheckUrl", checkUrl); body.put("currentValue", alert.getValue()); body.put("thresholdWarning", alert.getWarn()); body.put("thresholdCritical", alert.getError()); body.put("previewGraph", getPreviewImageUrl(check)); HttpClient client = HttpClientBuilder.create().useSystemProperties().build(); HttpPost post; if (StringUtils.isNotBlank(seyrenConfig.getBigPandaNotificationUrl())) { post = new HttpPost(seyrenConfig.getBigPandaNotificationUrl()); } else { LOGGER.warn( "BigPanda API URL in Seyren Config needs to be set before sending notifications to BigPanda"); return; } String authBearer; if (StringUtils.isNotBlank(seyrenConfig.getBigPandaAuthBearer())) { authBearer = seyrenConfig.getBigPandaAuthBearer(); } else { LOGGER.warn( "BigPanda Auth Bearer in Seyren Config needs to be set before sending notifications to BigPanda"); return; } try { post.addHeader("Authorization", "Bearer " + authBearer); HttpEntity entity = new StringEntity(MAPPER.writeValueAsString(body), ContentType.APPLICATION_JSON); post.setEntity(entity); LOGGER.info("Sending alert to BigPanda (AppKey: {}, Check: {}, Target: {}, Status: {})", bigPandaAppKey, check.getName(), alert.getTarget(), bigPandaStatus); HttpResponse response = client.execute(post); HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { LOGGER.info("Response : {} ", EntityUtils.toString(responseEntity)); } } catch (Exception e) { throw new NotificationFailedException("Failed to send notification to HTTP", e); } finally { post.releaseConnection(); HttpClientUtils.closeQuietly(client); } } }
From source file:org.jboss.as.test.clustering.cluster.web.AbstractWebFailoverTestCase.java
private void testFailover(Lifecycle lifecycle, URL baseURL1, URL baseURL2) throws Exception { HttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient(); URI uri1 = SimpleServlet.createURI(baseURL1); URI uri2 = SimpleServlet.createURI(baseURL2); this.establishTopology(baseURL1, NODES); try {//from ww w . java2 s. c om HttpResponse response = client.execute(new HttpGet(uri1)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(1, Integer.parseInt(response.getFirstHeader(SimpleServlet.VALUE_HEADER).getValue())); Map.Entry<String, String> entry = parseSessionRoute(response); Assert.assertEquals(NODE_1, entry.getValue()); Assert.assertEquals(entry.getKey(), response.getFirstHeader(SimpleServlet.SESSION_ID_HEADER).getValue()); } finally { HttpClientUtils.closeQuietly(response); } // Let's do this twice to have more debug info if failover is slow. response = client.execute(new HttpGet(uri1)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(2, Integer.parseInt(response.getFirstHeader(SimpleServlet.VALUE_HEADER).getValue())); Map.Entry<String, String> entry = parseSessionRoute(response); if (entry != null) { Assert.assertEquals(NODE_1, entry.getValue()); Assert.assertEquals(entry.getKey(), response.getFirstHeader(SimpleServlet.SESSION_ID_HEADER).getValue()); } } finally { HttpClientUtils.closeQuietly(response); } // Gracefully undeploy from/shutdown the 1st container. lifecycle.stop(NODE_1); this.establishTopology(baseURL2, NODE_2); // Now check on the 2nd server response = client.execute(new HttpGet(uri2)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals("Session failed to replicate after container 1 was shutdown.", 3, Integer.parseInt(response.getFirstHeader(SimpleServlet.VALUE_HEADER).getValue())); Map.Entry<String, String> entry = parseSessionRoute(response); Assert.assertEquals(NODE_2, entry.getValue()); Assert.assertEquals(entry.getKey(), response.getFirstHeader(SimpleServlet.SESSION_ID_HEADER).getValue()); } finally { HttpClientUtils.closeQuietly(response); } // Let's do one more check. response = client.execute(new HttpGet(uri2)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(4, Integer.parseInt(response.getFirstHeader(SimpleServlet.VALUE_HEADER).getValue())); Map.Entry<String, String> entry = parseSessionRoute(response); if (entry != null) { Assert.assertEquals(NODE_2, entry.getValue()); Assert.assertEquals(entry.getKey(), response.getFirstHeader(SimpleServlet.SESSION_ID_HEADER).getValue()); } } finally { HttpClientUtils.closeQuietly(response); } lifecycle.start(NODE_1); this.establishTopology(baseURL2, NODES); response = client.execute(new HttpGet(uri2)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals("Session failed to replicate after container 1 was brough up.", 5, Integer.parseInt(response.getFirstHeader(SimpleServlet.VALUE_HEADER).getValue())); Map.Entry<String, String> entry = parseSessionRoute(response); if (entry != null) { Assert.assertEquals(NODE_1, entry.getValue()); Assert.assertEquals(entry.getKey(), response.getFirstHeader(SimpleServlet.SESSION_ID_HEADER).getValue()); } } finally { HttpClientUtils.closeQuietly(response); } // The previous and next requests intentially hit the non-owning node this.nonOwnerTask.run(); // Let's do this twice to have more debug info if failover is slow. response = client.execute(new HttpGet(uri2)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(6, Integer.parseInt(response.getFirstHeader(SimpleServlet.VALUE_HEADER).getValue())); Map.Entry<String, String> entry = parseSessionRoute(response); if (entry != null) { Assert.assertEquals(NODE_1, entry.getValue()); Assert.assertEquals(entry.getKey(), response.getFirstHeader(SimpleServlet.SESSION_ID_HEADER).getValue()); } } finally { HttpClientUtils.closeQuietly(response); } // Until graceful undeploy is supported, we need to wait for replication to complete before undeploy (WFLY-6769). if (lifecycle instanceof RedeployLifecycle) { Thread.sleep(GRACE_TIME_TO_REPLICATE); } // Gracefully undeploy from/shutdown the 1st container. lifecycle.stop(NODE_2); this.establishTopology(baseURL1, NODE_1); // Now check on the 2nd server response = client.execute(new HttpGet(uri1)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals("Session failed to replicate after container 1 was shutdown.", 7, Integer.parseInt(response.getFirstHeader(SimpleServlet.VALUE_HEADER).getValue())); Map.Entry<String, String> entry = parseSessionRoute(response); if (entry != null) { Assert.assertEquals(NODE_1, entry.getValue()); Assert.assertEquals(entry.getKey(), response.getFirstHeader(SimpleServlet.SESSION_ID_HEADER).getValue()); } } finally { HttpClientUtils.closeQuietly(response); } // Let's do one more check. response = client.execute(new HttpGet(uri1)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(8, Integer.parseInt(response.getFirstHeader(SimpleServlet.VALUE_HEADER).getValue())); Map.Entry<String, String> entry = parseSessionRoute(response); if (entry != null) { Assert.assertEquals(NODE_1, entry.getValue()); Assert.assertEquals(entry.getKey(), response.getFirstHeader(SimpleServlet.SESSION_ID_HEADER).getValue()); } } finally { HttpClientUtils.closeQuietly(response); } lifecycle.start(NODE_2); this.establishTopology(baseURL1, NODES); response = client.execute(new HttpGet(uri1)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals("Session failed to replicate after container 1 was brought up.", 9, Integer.parseInt(response.getFirstHeader(SimpleServlet.VALUE_HEADER).getValue())); Map.Entry<String, String> entry = parseSessionRoute(response); if (entry != null) { Assert.assertEquals(NODE_2, entry.getValue()); Assert.assertEquals(entry.getKey(), response.getFirstHeader(SimpleServlet.SESSION_ID_HEADER).getValue()); } } finally { HttpClientUtils.closeQuietly(response); } // Let's do this twice to have more debug info if failover is slow. response = client.execute(new HttpGet(uri1)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(10, Integer.parseInt(response.getFirstHeader(SimpleServlet.VALUE_HEADER).getValue())); Map.Entry<String, String> entry = parseSessionRoute(response); if (entry != null) { Assert.assertEquals(NODE_2, entry.getValue()); Assert.assertEquals(entry.getKey(), response.getFirstHeader(SimpleServlet.SESSION_ID_HEADER).getValue()); } } finally { HttpClientUtils.closeQuietly(response); } } finally { HttpClientUtils.closeQuietly(client); } }