List of usage examples for org.apache.http.client.methods CloseableHttpResponse close
public void close() throws IOException;
From source file:org.sead.repositories.reference.util.SEADGoogleLogin.java
static void getAuthCode() { access_token = null;//from w w w. j a v a2 s. c om expires_in = -1; token_start_time = -1; refresh_token = null; new File("refresh.txt").delete(); if (gProps == null) { initGProps(); } // Contact google for a user code CloseableHttpClient httpclient = HttpClients.createDefault(); try { String codeUri = gProps.auth_uri.substring(0, gProps.auth_uri.length() - 4) + "device/code"; HttpPost codeRequest = new HttpPost(codeUri); MultipartEntityBuilder meb = MultipartEntityBuilder.create(); meb.addTextBody("client_id", gProps.client_id); meb.addTextBody("scope", "email profile"); HttpEntity reqEntity = meb.build(); codeRequest.setEntity(reqEntity); CloseableHttpResponse response = httpclient.execute(codeRequest); try { if (response.getStatusLine().getStatusCode() == 200) { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { String responseJSON = EntityUtils.toString(resEntity); ObjectNode root = (ObjectNode) new ObjectMapper().readTree(responseJSON); device_code = root.get("device_code").asText(); user_code = root.get("user_code").asText(); verification_url = root.get("verification_url").asText(); expires_in = root.get("expires_in").asInt(); } } else { log.error("Error response from Google: " + response.getStatusLine().getReasonPhrase()); } } finally { response.close(); httpclient.close(); } } catch (IOException e) { log.error("Error reading sead-google.json or making http requests for code."); log.error(e.getMessage()); } }
From source file:com.cloud.utils.rest.BasicRestClient.java
@Override public void closeResponse(final CloseableHttpResponse response) throws CloudstackRESTException { try {/* w w w . ja va 2 s . c om*/ s_logger.debug("Closing HTTP connection"); response.close(); } catch (final IOException e) { final StringBuilder sb = new StringBuilder(); sb.append("Failed to close response object for request.\nResponse: ").append(response); throw new CloudstackRESTException(sb.toString(), e); } }
From source file:com.srotya.tau.nucleus.qa.QACountingAggregationRules.java
@Test public void testACountingAggregations() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, IOException, InterruptedException { CloseableHttpClient client = null;// w w w . ja v 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) 12, "test_template", "alertAggregation@srotya.com", "mail", "aggregation", "aggregation", 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) 13, "SimpleAggregationRule", true, new EqualsCondition("value", 8.0), new Action[] { new FineCountingAggregationAction((short) 0, "host", "clientip", 10) }), 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) 15, "SimpleAlertRule", true, new AndCondition(Arrays.asList(new EqualsCondition(Constants.FIELD_RULE_ID, 13), new EqualsCondition(Constants.FIELD_ACTION_ID, 0))), new Action[] { new TemplatedAlertAction((short) 0, (short) 12) }), 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", 8.0); eventHeaders.put("@timestamp", "2014-04-23T13:40:2" + i + ".000Z"); eventHeaders.put(Constants.FIELD_EVENT_ID, 1200 + 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()) <= 3) { System.out.println("Waiting on aggregation window to close; email count:" + size); Thread.sleep(10000); } assertEquals(4, size); }
From source file:com.currencyfair.minfraud.MinFraudImplTest.java
private CloseableHttpResponse expectClose(CloseableHttpResponse httpResponse, IOException throwOnClose) throws Exception { httpResponse.close(); IExpectationSetters<?> expection = EasyMock.expectLastCall(); if (throwOnClose != null) { expection.andThrow(throwOnClose); }/*from w w w . ja v a 2 s. com*/ return httpResponse; }
From source file:kr.riotapi.core.ApiDomain.java
public String execute(ApiCall call) throws IOException, StatusCodeException { HttpGet get = new HttpGet(call.toUrlString()); String body = null;/* ww w . j a va 2 s. co m*/ int statusCode = 0; try (CloseableHttpClient client = HttpClients.createDefault()) { CloseableHttpResponse response = client.execute(get); statusCode = response.getStatusLine().getStatusCode(); body = EntityUtils.toString(response.getEntity()); response.close(); } catch (IOException ex) { throw new IOException("There was a problem receiving or processing a server response", ex); } if (statusCode != HttpStatus.SC_OK) throw new StatusCodeException("status code was not 200", statusCode); return body; }
From source file:com.abc.turkey.web.unfreeze.UnfreezeController.java
@RequestMapping(value = "/cap_union_getsig_new") public void getNewSig(HttpServletRequest request, HttpServletResponse response) { String url = captcha_prefix + "cap_union_getsig_new?" + request.getQueryString(); HttpGet httpGet = new HttpGet(url); try {//from ww w . ja v a 2s .c o m CloseableHttpResponse response2 = httpClient.execute(httpGet); response2.getEntity().writeTo(response.getOutputStream()); response2.close(); } catch (Exception e) { throw new ServiceException(e.getMessage(), e.getCause()); } }
From source file:com.abc.turkey.web.unfreeze.UnfreezeController.java
@RequestMapping(value = "/cap_union_getcapbysig_new") public void getCaptchaImage(HttpServletRequest request, HttpServletResponse response) { String url = captcha_prefix + "cap_union_getcapbysig_new?" + request.getQueryString(); HttpGet httpGet = new HttpGet(url); try {/*from w w w . jav a 2s. com*/ CloseableHttpResponse response2 = httpClient.execute(httpGet); response2.getEntity().writeTo(response.getOutputStream()); response2.close(); } catch (Exception e) { throw new ServiceException(e.getMessage(), e.getCause()); } }
From source file:com.abc.turkey.web.unfreeze.UnfreezeController.java
@RequestMapping(value = "/cap_union_verify_new") public void capVerify(HttpServletRequest request, HttpServletResponse response) { String url = captcha_prefix + "cap_union_verify_new?" + request.getQueryString(); HttpGet httpGet = new HttpGet(url); try {/*from w w w. j a v a2 s .c o m*/ CloseableHttpResponse response2 = httpClient.execute(httpGet); response2.getEntity().writeTo(response.getOutputStream()); response2.close(); } catch (Exception e) { throw new ServiceException(e.getMessage(), e.getCause()); } }
From source file:org.wuspba.ctams.ws.ITPersonController.java
protected static void delete() throws Exception { List<String> ids = new ArrayList<>(); 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); for (Person p : doc.getPeople()) { ids.add(p.getId());// ww w.j a v a 2s . c om } EntityUtils.consume(entity); } for (String id : ids) { 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); } } } } }
From source file:gda.util.ElogEntry.java
/** * Creates an ELog entry. Default ELog server is "http://rdb.pri.diamond.ac.uk/devl/php/elog/cs_logentryext_bl.php" * which is the development database. "http://rdb.pri.diamond.ac.uk/php/elog/cs_logentryext_bl.php" is the * production database. The java.properties file contains the property "gda.elog.targeturl" which can be set to be * either the development or production databases. * // w ww .j ava 2 s . c o m * @param title * The ELog title * @param content * The ELog content * @param userID * The user ID e.g. epics or gda or abc12345 * @param visit * The visit number * @param logID * The type of log book, The log book ID: Beam Lines: - BLB16, BLB23, BLI02, BLI03, BLI04, BLI06, BLI11, * BLI16, BLI18, BLI19, BLI22, BLI24, BLI15, DAG = Data Acquisition, EHC = Experimental Hall * Coordinators, OM = Optics and Meteorology, OPR = Operations, E * @param groupID * The group sending the ELog, DA = Data Acquisition, EHC = Experimental Hall Coordinators, OM = Optics * and Meteorology, OPR = Operations CS = Control Systems, GroupID Can also be a beam line, * @param fileLocations * The image file names with path to upload * @throws ELogEntryException */ public static void post(String title, String content, String userID, String visit, String logID, String groupID, String[] fileLocations) throws ELogEntryException { String targetURL = POST_UPLOAD_URL; try { String entryType = "41";// entry type is always a log (41) String titleForPost = visit == null ? title : "Visit: " + visit + " - " + title; MultipartEntityBuilder request = MultipartEntityBuilder.create().addTextBody("txtTITLE", titleForPost) .addTextBody("txtCONTENT", content).addTextBody("txtLOGBOOKID", logID) .addTextBody("txtGROUPID", groupID).addTextBody("txtENTRYTYPEID", entryType) .addTextBody("txtUSERID", userID); if (fileLocations != null) { for (int i = 1; i < fileLocations.length + 1; i++) { File targetFile = new File(fileLocations[i - 1]); request = request.addBinaryBody("userfile" + i, targetFile, ContentType.create("image/png"), targetFile.getName()); } } HttpEntity entity = request.build(); targetURL = LocalProperties.get("gda.elog.targeturl", POST_UPLOAD_URL); HttpPost httpPost = new HttpPost(targetURL); httpPost.setEntity(entity); CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(httpPost); try { String responseString = EntityUtils.toString(response.getEntity()); System.out.println(responseString); if (!responseString.contains("New Log Entry ID")) { throw new ELogEntryException("Upload failed, status=" + response.getStatusLine().getStatusCode() + " response=" + responseString + " targetURL = " + targetURL + " titleForPost = " + titleForPost + " logID = " + logID + " groupID = " + groupID + " entryType = " + entryType + " userID = " + userID); } } finally { response.close(); httpClient.close(); } } catch (ELogEntryException e) { throw e; } catch (Exception e) { throw new ELogEntryException("Error in ELogger. Database:" + targetURL, e); } }