use of org.apache.commons.httpclient.HttpException in project cloudstack by apache.
the class RegionsApiUtil method makeDomainAPICall.
/**
* Makes an api call using region service end_point, api command and params
* Returns Domain object on success
* @param region
* @param command
* @param params
* @return
*/
protected static RegionDomain makeDomainAPICall(Region region, String command, List<NameValuePair> params) {
try {
String url = buildUrl(buildParams(command, params), region);
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
if (client.executeMethod(method) == 200) {
InputStream is = method.getResponseBodyAsStream();
XStream xstream = new XStream(new DomDriver());
//Translate response to Domain object
xstream.alias("domain", RegionDomain.class);
xstream.aliasField("id", RegionDomain.class, "uuid");
xstream.aliasField("parentdomainid", RegionDomain.class, "parentUuid");
xstream.aliasField("networkdomain", DomainVO.class, "networkDomain");
try (ObjectInputStream in = xstream.createObjectInputStream(is)) {
return (RegionDomain) in.readObject();
} catch (IOException e) {
s_logger.error(e.getMessage());
return null;
}
} else {
return null;
}
} catch (HttpException e) {
s_logger.error(e.getMessage());
return null;
} catch (IOException e) {
s_logger.error(e.getMessage());
return null;
} catch (ClassNotFoundException e) {
s_logger.error(e.getMessage());
return null;
}
}
use of org.apache.commons.httpclient.HttpException in project cloudstack by apache.
the class RegionsApiUtil method makeUserAccountAPICall.
/**
* Makes an api call using region service end_point, api command and params
* Returns UserAccount object on success
* @param region
* @param command
* @param params
* @return
*/
protected static UserAccount makeUserAccountAPICall(Region region, String command, List<NameValuePair> params) {
try {
String url = buildUrl(buildParams(command, params), region);
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
if (client.executeMethod(method) == 200) {
InputStream is = method.getResponseBodyAsStream();
XStream xstream = new XStream(new DomDriver());
xstream.alias("useraccount", UserAccountVO.class);
xstream.aliasField("id", UserAccountVO.class, "uuid");
try (ObjectInputStream in = xstream.createObjectInputStream(is)) {
return (UserAccountVO) in.readObject();
} catch (IOException e) {
s_logger.error(e.getMessage());
return null;
}
} else {
return null;
}
} catch (HttpException e) {
s_logger.error(e.getMessage());
return null;
} catch (IOException e) {
s_logger.error(e.getMessage());
return null;
} catch (ClassNotFoundException e) {
s_logger.error(e.getMessage());
return null;
}
}
use of org.apache.commons.httpclient.HttpException in project cloudstack by apache.
the class RegionsApiUtil method makeAccountAPICall.
/**
* Makes an api call using region service end_point, api command and params
* Returns Account object on success
* @param region
* @param command
* @param params
* @return
*/
protected static RegionAccount makeAccountAPICall(Region region, String command, List<NameValuePair> params) {
try {
String url = buildUrl(buildParams(command, params), region);
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
if (client.executeMethod(method) == 200) {
InputStream is = method.getResponseBodyAsStream();
//Translate response to Account object
XStream xstream = new XStream(new DomDriver());
xstream.alias("account", RegionAccount.class);
xstream.alias("user", RegionUser.class);
xstream.aliasField("id", RegionAccount.class, "uuid");
xstream.aliasField("name", RegionAccount.class, "accountName");
xstream.aliasField("accounttype", RegionAccount.class, "type");
xstream.aliasField("domainid", RegionAccount.class, "domainUuid");
xstream.aliasField("networkdomain", RegionAccount.class, "networkDomain");
xstream.aliasField("id", RegionUser.class, "uuid");
xstream.aliasField("accountId", RegionUser.class, "accountUuid");
try (ObjectInputStream in = xstream.createObjectInputStream(is)) {
return (RegionAccount) in.readObject();
} catch (IOException e) {
s_logger.error(e.getMessage());
return null;
}
} else {
return null;
}
} catch (HttpException e) {
s_logger.error(e.getMessage());
return null;
} catch (IOException e) {
s_logger.error(e.getMessage());
return null;
} catch (ClassNotFoundException e) {
s_logger.error(e.getMessage());
return null;
}
}
use of org.apache.commons.httpclient.HttpException in project openhab1-addons by openhab.
the class Telegram method sendTelegram.
@ActionDoc(text = "Sends a Telegram via Telegram REST API - direct message")
public static boolean sendTelegram(@ParamDoc(name = "group") String group, @ParamDoc(name = "message") String message) {
if (groupTokens.get(group) == null) {
logger.error("Bot '{}' not defined, action skipped", group);
return false;
}
String url = String.format(TELEGRAM_URL, groupTokens.get(group).getToken());
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod(url);
postMethod.getParams().setContentCharset("UTF-8");
postMethod.getParams().setSoTimeout(HTTP_TIMEOUT);
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
NameValuePair[] data = { new NameValuePair("chat_id", groupTokens.get(group).getChatId()), new NameValuePair("text", message) };
postMethod.setRequestBody(data);
try {
int statusCode = client.executeMethod(postMethod);
if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
return true;
}
if (statusCode != HttpStatus.SC_OK) {
logger.warn("Method failed: {}", postMethod.getStatusLine());
return false;
}
InputStream tmpResponseStream = postMethod.getResponseBodyAsStream();
Header encodingHeader = postMethod.getResponseHeader("Content-Encoding");
if (encodingHeader != null) {
for (HeaderElement ehElem : encodingHeader.getElements()) {
if (ehElem.toString().matches(".*gzip.*")) {
tmpResponseStream = new GZIPInputStream(tmpResponseStream);
logger.debug("GZipped InputStream from {}", url);
} else if (ehElem.toString().matches(".*deflate.*")) {
tmpResponseStream = new InflaterInputStream(tmpResponseStream);
logger.debug("Deflated InputStream from {}", url);
}
}
}
String responseBody = IOUtils.toString(tmpResponseStream);
if (!responseBody.isEmpty()) {
logger.debug(responseBody);
}
} catch (HttpException e) {
logger.error("Fatal protocol violation: {}", e.toString());
return false;
} catch (IOException e) {
logger.error("Fatal transport error: {}", e.toString());
return false;
} finally {
postMethod.releaseConnection();
}
return true;
}
use of org.apache.commons.httpclient.HttpException in project CloudStack-archive by CloudStack-extras.
the class TestClientWithAPI method executeEventsAndBilling.
private static int executeEventsAndBilling(String server, String developerServer) throws HttpException, IOException {
// test steps:
// - get all the events in the system for all users in the system
// - generate all the usage records in the system
// - get all the usage records in the system
// -----------------------------
// GET EVENTS
// -----------------------------
String url = server + "?command=listEvents&page=1&pagesize=100&&account=" + _account.get();
s_logger.info("Getting events for the account " + _account.get());
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
int responseCode = client.executeMethod(method);
s_logger.info("get events response code: " + responseCode);
if (responseCode == 200) {
InputStream is = method.getResponseBodyAsStream();
Map<String, List<String>> eventDescriptions = getMultipleValuesFromXML(is, new String[] { "description" });
List<String> descriptionText = eventDescriptions.get("description");
if (descriptionText == null) {
s_logger.info("no events retrieved...");
} else {
for (String text : descriptionText) {
s_logger.info("event: " + text);
}
}
} else {
s_logger.error("list events failed with error code: " + responseCode + ". Following URL was sent: " + url);
return responseCode;
}
// -------------------------------------------------------------------------------------
// GENERATE USAGE RECORDS (note: typically this is done infrequently)
// -------------------------------------------------------------------------------------
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date currentDate = new Date();
String endDate = dateFormat.format(currentDate);
s_logger.info("Generating usage records from September 1st till " + endDate);
// generate
url = server + "?command=generateUsageRecords&startdate=2009-09-01&enddate=" + endDate;
// all usage record till today
client = new HttpClient();
method = new GetMethod(url);
responseCode = client.executeMethod(method);
s_logger.info("generate usage records response code: " + responseCode);
if (responseCode == 200) {
InputStream is = method.getResponseBodyAsStream();
Map<String, String> successStr = getSingleValueFromXML(is, new String[] { "success" });
s_logger.info("successfully generated usage records? " + successStr.get("success"));
} else {
s_logger.error("generate usage records failed with error code: " + responseCode + ". Following URL was sent: " + url);
return responseCode;
}
// Sleeping for a 2 minutes before getting a usage records from the database
try {
Thread.sleep(120000);
} catch (Exception ex) {
s_logger.error(ex);
}
// --------------------------------
// GET USAGE RECORDS
// --------------------------------
url = server + "?command=listUsageRecords&startdate=2009-09-01&enddate=" + endDate + "&account=" + _account.get() + "&domaindid=1";
s_logger.info("Getting all usage records with request: " + url);
client = new HttpClient();
method = new GetMethod(url);
responseCode = client.executeMethod(method);
s_logger.info("get usage records response code: " + responseCode);
if (responseCode == 200) {
InputStream is = method.getResponseBodyAsStream();
Map<String, List<String>> usageRecValues = getMultipleValuesFromXML(is, new String[] { "description", "usage" });
if ((usageRecValues.containsKey("description") == true) && (usageRecValues.containsKey("usage") == true)) {
List<String> descriptions = usageRecValues.get("description");
List<String> usages = usageRecValues.get("usage");
for (int i = 0; i < descriptions.size(); i++) {
String desc = descriptions.get(i);
String usage = "";
if (usages != null) {
if (i < usages.size()) {
usage = ", usage: " + usages.get(i);
}
}
s_logger.info("desc: " + desc + usage);
}
}
} else {
s_logger.error("list usage records failed with error code: " + responseCode + ". Following URL was sent: " + url);
return responseCode;
}
return responseCode;
}
Aggregations