List of usage examples for org.apache.http.client.methods CloseableHttpResponse close
public void close() throws IOException;
From source file:io.crate.integrationtests.SQLHttpIntegrationTest.java
protected String upload(String table, String content) throws IOException { String digest = blobDigest(content); String url = Blobs.url(address, table, digest); HttpPut httpPut = new HttpPut(url); httpPut.setEntity(new StringEntity(content)); CloseableHttpResponse response = httpClient.execute(httpPut); assertThat(response.getStatusLine().getStatusCode(), is(201)); response.close(); return url;/*from w ww . j a va 2s . co m*/ }
From source file:com.cognifide.qa.bb.aem.core.login.AemAuthCookieFactoryImpl.java
/** * This method provides browser cookie for authenticating user to AEM instance * * @param url URL to AEM instance, like http://localhost:4502 * @param login Username to use/*from ww w. j a v a 2s. co m*/ * @param password Password to use * @return Cookie for selenium WebDriver. */ @Override public Cookie getCookie(String url, String login, String password) { if (!cookieJar.containsKey(url)) { HttpPost loginPost = new HttpPost(url + "/libs/granite/core/content/login.html/j_security_check"); List<NameValuePair> nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair("_charset_", "utf-8")); nameValuePairs.add(new BasicNameValuePair("j_username", login)); nameValuePairs.add(new BasicNameValuePair("j_password", password)); nameValuePairs.add(new BasicNameValuePair("j_validate", "true")); CookieStore cookieStore = new BasicCookieStore(); HttpClientContext context = HttpClientContext.create(); context.setCookieStore(cookieStore); try { loginPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); CloseableHttpResponse loginResponse = httpClient.execute(loginPost, context); loginResponse.close(); } catch (IOException e) { LOG.error("Can't get AEM authentication cookie", e); } finally { loginPost.reset(); } Cookie cookie = findAuthenticationCookie(cookieStore.getCookies()); if (cookie != null) { cookieJar.put(url, cookie); } } return cookieJar.get(url); }
From source file:org.wuspba.ctams.ws.ITSoloContestController.java
protected static void delete() throws Exception { String id;/*ww w. j a v a 2 s. c om*/ CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); HttpGet httpGet = new HttpGet(uri); try (CloseableHttpResponse response = httpclient.execute(httpGet)) { assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING); HttpEntity entity = response.getEntity(); CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity); id = doc.getSoloContests().get(0).getId(); EntityUtils.consume(entity); } httpclient = HttpClients.createDefault(); uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).setParameter("id", id) .build(); HttpDelete httpDelete = new HttpDelete(uri); CloseableHttpResponse response = null; try { response = httpclient.execute(httpDelete); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } ITVenueController.delete(); ITHiredJudgeController.delete(); ITJudgeController.delete(); }
From source file:httpServerClient.app.QuickStart.java
public static void sendMessage(String[] args) throws Exception { // arguments to run Quick start POST: // args[0] POST // args[1] IPAddress of server // args[2] port No. // args[3] user name // args[4] myMessage CloseableHttpClient httpclient = HttpClients.createDefault(); try {//from ww w . ja v a 2s .co m HttpPost httpPost = new HttpPost("http://" + args[1] + ":" + args[2] + "/sendMessage"); // httpPost.setEntity(new StringEntity("lubo je kral")); httpPost.setEntity( new StringEntity("{\"name\":\"" + args[3] + "\",\"myMessage\":\"" + args[4] + "\"}")); CloseableHttpResponse response1 = httpclient.execute(httpPost); // The underlying HTTP connection is still held by the response // object // to allow the response content to be streamed directly from the // network socket. // In order to ensure correct deallocation of system resources // the user MUST call CloseableHttpResponse#close() from a finally // clause. // Please note that if response content is not fully consumed the // underlying // connection cannot be safely re-used and will be shut down and // discarded // by the connection manager. try { System.out.println(response1.getStatusLine()); HttpEntity entity1 = response1.getEntity(); /* * Vypisanie odpovede do konzoly a discard dat zo serveru. */ System.out.println(EntityUtils.toString(entity1)); EntityUtils.consume(entity1); } finally { response1.close(); } } finally { httpclient.close(); } }
From source file:com.cognifide.qa.bb.aem.AemAuthCookieFactory.java
/** * This method provides browser cookie for authenticating user to AEM instance * * @param url URL to AEM instance, like http://localhost:4502 * @param login Username to use/*from w w w. j a va 2 s. com*/ * @param password Password to use * @return Cookie for selenium WebDriver. */ public Cookie getCookie(String url, String login, String password) { if (!cookieJar.containsKey(url)) { HttpPost loginPost = new HttpPost(url + "/libs/granite/core/content/login.html/j_security_check"); List<NameValuePair> nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair("_charset_", "utf-8")); nameValuePairs.add(new BasicNameValuePair("j_username", login)); nameValuePairs.add(new BasicNameValuePair("j_password", password)); nameValuePairs.add(new BasicNameValuePair("j_validate", "true")); CookieStore cookieStore = new BasicCookieStore(); HttpClientContext context = HttpClientContext.create(); if ("true".equals(properties.getProperty(ConfigKeys.WEBDRIVER_PROXY_COOKIE))) { addProxyCookie(cookieStore); } context.setCookieStore(cookieStore); try { loginPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); CloseableHttpResponse loginResponse = httpClient.execute(loginPost, context); loginResponse.close(); } catch (IOException e) { LOG.error("Can't get AEM authentication cookie", e); } finally { loginPost.reset(); } Cookie cookie = findAuthenticationCookie(cookieStore.getCookies()); if (cookie != null) { cookieJar.put(url, cookie); } } return cookieJar.get(url); }
From source file:org.pepstock.jem.node.https.HttpJobListener.java
@Override public void ended(Job job) { // if job is not waiting, return if (job.isNowait()) { return;//from ww w .j a v a 2 s.c o m } // if there is the IP address // to reply if (job.getInputArguments() != null && job.getInputArguments().contains(SubmitHandler.JOB_SUBMIT_IP_ADDRESS_KEY)) { // creates the URL // the path is always the JOBID String url = "http://" + job.getInputArguments().get(0) + ":" + job.getInputArguments().get(1) + "/" + job.getId(); // creates a HTTP client CloseableHttpClient httpclient = null; try { httpclient = HttpUtil.createHttpClient(url); // gets if printoutput is required boolean printOutput = Parser.parseBoolean(job.getInputArguments().get(2), false); // creates the response // ALWAYS the return code StringBuilder sb = new StringBuilder(); sb.append(job.getResult().getReturnCode()).append("\n"); // if client needs output // it adds teh output of job if (printOutput) { File file = Main.getOutputSystem().getMessagesLogFile(job); sb.append(FileUtils.readFileToString(file)); } // creates teh HTTP entity StringEntity entity = new StringEntity(sb.toString(), ContentType.create("text/plain", CharSet.DEFAULT_CHARSET_NAME)); // prepares POST request and basic response handler HttpPost httppost = new HttpPost(url); httppost.setEntity(entity); // executes and no parsing // result must be only a string CloseableHttpResponse response = httpclient.execute(httppost); response.close(); return; } catch (Exception e) { LogAppl.getInstance().emit(NodeMessage.JEMC289E, e, job.getInputArguments().get(0) + ":" + job.getInputArguments().get(1), job.toString()); } finally { // close http client if (httpclient != null) { try { httpclient.close(); } catch (IOException e) { LogAppl.getInstance().ignore(e.getMessage(), e); } } } } }
From source file:eu.diacron.crawlservice.app.Util.java
public static void getAllCrawls() { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(Configuration.REMOTE_CRAWLER_USERNAME, Configuration.REMOTE_CRAWLER_PASS)); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); try {//from ww w.j a v a2s . co m //HttpGet httpget = new HttpGet("http://diachron.hanzoarchives.com/crawl"); HttpGet httpget = new HttpGet(Configuration.REMOTE_CRAWLER_URL_CRAWL); System.out.println("Executing request " + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpget); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println("----------------------------------------"); System.out.println(response.getEntity().getContent()); BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); EntityUtils.consume(response.getEntity()); } finally { response.close(); } } catch (IOException ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } finally { try { httpclient.close(); } catch (IOException ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:it.polimi.tower4clouds.rules.actions.RestCall.java
@Override public void execute(String resourceId, String value, String timestamp) { getLogger().info("Action requested. Input data: {}, {}, {}", resourceId, value, timestamp); try {// ww w. j av a 2 s. c om CloseableHttpClient client = HttpClients.createDefault(); HttpUriRequest request; String url = getParameters().get(URL); String method = getParameters().get(METHOD).toUpperCase(); switch (method) { case POST: request = new HttpPost(url); break; case PUT: request = new HttpPut(url); break; case DELETE: request = new HttpDelete(url); break; case GET: request = new HttpGet(url); break; default: getLogger().error("Unknown method {}", method); return; } request.setHeader("Cache-Control", "no-cache"); CloseableHttpResponse response = client.execute(request); getLogger().info("Rest call executed"); response.close(); } catch (Exception e) { getLogger().error("Error executing rest call", e); } }
From source file:org.wuspba.ctams.ws.ITBandController.java
private static void add(Band band) throws Exception { CTAMSDocument doc = new CTAMSDocument(); doc.getBands().add(band);/*w ww . jav a2s . c o m*/ String xml = XMLUtils.marshal(doc); CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); HttpPost httpPost = new HttpPost(uri); StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML); CloseableHttpResponse response = null; try { httpPost.setEntity(xmlEntity); response = httpclient.execute(httpPost); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); doc = IntegrationTestUtils.convertEntity(responseEntity); TestFixture.INSTANCE.skye.setId(doc.getBands().get(0).getId()); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } }
From source file:com.srotya.tau.nucleus.qa.QAStateAggregationRules.java
@Test public void testAStateAggregations() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, IOException, InterruptedException { CloseableHttpClient client = null;// ww w .jav a 2 s .c o m // Create a template for alerting and upload it client = Utils.buildClient("http://localhost:8080/commands/templates", 2000, 2000); HttpPut templateUpload = new HttpPut("http://localhost:8080/commands/templates"); String template = AlertTemplateSerializer.serialize(new AlertTemplate((short) 22, "test_template", "alertAggregation@srotya.com", "mail", "state tracking", "state tracking", 30, 1), false); templateUpload.addHeader("content-type", "application/json"); templateUpload.setEntity(new StringEntity(new Gson().toJson(new TemplateCommand("all", false, template)))); CloseableHttpResponse response = client.execute(templateUpload); response.close(); assertTrue( response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300); // Create aggregation rule and upload it HttpPut ruleUpload = null; String rule = null; client = Utils.buildClient("http://localhost:8080/commands/rules", 2000, 2000); ruleUpload = new HttpPut("http://localhost:8080/commands/rules"); ruleUpload.addHeader("content-type", "application/json"); rule = RuleSerializer.serializeRuleToJSONString(new SimpleRule((short) 23, "SimpleStateTrackingRule", true, new EqualsCondition("value", 9.0), new Action[] { new StateAggregationAction((short) 0, "host", 10, new EqualsCondition("value", 9.0)) }), false); ruleUpload.setEntity(new StringEntity( new Gson().toJson(new RuleCommand(StatelessRulesEngine.ALL_RULEGROUP, false, rule)))); response = client.execute(ruleUpload); response.close(); assertTrue(response.getStatusLine().getReasonPhrase(), response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300); // Create alert rule for aggregation rule's output and upload it client = Utils.buildClient("http://localhost:8080/commands/rules", 2000, 2000); ruleUpload = new HttpPut("http://localhost:8080/commands/rules"); rule = RuleSerializer.serializeRuleToJSONString(new SimpleRule((short) 25, "SimpleStateAlertRule", true, new AndCondition(Arrays.asList(new EqualsCondition(Constants.FIELD_RULE_ID, 23), new EqualsCondition(Constants.FIELD_ACTION_ID, 0))), new Action[] { new TemplatedAlertAction((short) 0, (short) 22) }), false); ruleUpload.addHeader("content-type", "application/json"); ruleUpload.setEntity(new StringEntity( new Gson().toJson(new RuleCommand(StatelessRulesEngine.ALL_RULEGROUP, false, rule)))); response = client.execute(ruleUpload); response.close(); assertTrue( response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300); for (int i = 0; i < 5; i++) { client = Utils.buildClient("http://localhost:8080/events", 2000, 2000); Map<String, Object> eventHeaders = new HashMap<>(); eventHeaders.put("clientip", i); eventHeaders.put("host", "host1"); eventHeaders.put("value", 9.0); eventHeaders.put("@timestamp", "2014-04-23T13:40:2" + i + ".000Z"); eventHeaders.put(Constants.FIELD_EVENT_ID, 1300 + i); HttpPost eventUpload = new HttpPost("http://localhost:8080/events"); eventUpload.addHeader("content-type", "application/json"); eventUpload.setEntity(new StringEntity(new Gson().toJson(eventHeaders))); response = client.execute(eventUpload); response.close(); assertTrue(response.getStatusLine().getReasonPhrase(), response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300); } int size = 0; while ((size = AllQATests.getSmtpServer().getReceivedEmailSize()) <= 4) { System.out.println("Waiting on aggregation window to close; email count:" + size); Thread.sleep(10000); } assertEquals(5, size); }