use of org.apache.commons.httpclient.methods.GetMethod in project CloudStack-archive by CloudStack-extras.
the class ApiCommand method verifyEvents.
public static boolean verifyEvents(String fileName, String level, String host, String account) {
boolean result = false;
HashMap<String, Integer> expectedEvents = new HashMap<String, Integer>();
HashMap<String, Integer> actualEvents = new HashMap<String, Integer>();
String key = "";
File file = new File(fileName);
if (file.exists()) {
Properties pro = new Properties();
try {
// get expected events
FileInputStream in = new FileInputStream(file);
pro.load(in);
Enumeration<?> en = pro.propertyNames();
while (en.hasMoreElements()) {
key = (String) en.nextElement();
expectedEvents.put(key, Integer.parseInt(pro.getProperty(key)));
}
// get actual events
String url = host + "/?command=listEvents&account=" + account + "&level=" + level + "&domainid=1&pagesize=100";
s_logger.info("Getting events with the following url " + url);
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
int responseCode = client.executeMethod(method);
if (responseCode == 200) {
InputStream is = method.getResponseBodyAsStream();
ArrayList<HashMap<String, String>> eventValues = UtilsForTest.parseMulXML(is, new String[] { "event" });
for (int i = 0; i < eventValues.size(); i++) {
HashMap<String, String> element = eventValues.get(i);
if (element.get("level").equals(level)) {
if (actualEvents.containsKey(element.get("type")) == true) {
actualEvents.put(element.get("type"), actualEvents.get(element.get("type")) + 1);
} else {
actualEvents.put(element.get("type"), 1);
}
}
}
}
method.releaseConnection();
// compare actual events with expected events
// compare expected result and actual result
Iterator<?> iterator = expectedEvents.keySet().iterator();
Integer expected;
Integer actual;
int fail = 0;
while (iterator.hasNext()) {
expected = null;
actual = null;
String type = iterator.next().toString();
expected = expectedEvents.get(type);
actual = actualEvents.get(type);
if (actual == null) {
s_logger.error("Event of type " + type + " and level " + level + " is missing in the listEvents response. Expected number of these events is " + expected);
fail++;
} else if (expected.compareTo(actual) != 0) {
fail++;
s_logger.info("Amount of events of " + type + " type and level " + level + " is incorrect. Expected number of these events is " + expected + ", actual number is " + actual);
}
}
if (fail == 0) {
result = true;
}
} catch (Exception ex) {
s_logger.error(ex);
}
} else {
s_logger.info("File " + fileName + " not found");
}
return result;
}
use of org.apache.commons.httpclient.methods.GetMethod in project CloudStack-archive by CloudStack-extras.
the class ApiCommand method queryAsyncJobResult.
public Element queryAsyncJobResult(String jobId) {
Element returnBody = null;
int code = 400;
String resultUrl = this.host + ":8096/?command=queryAsyncJobResult&jobid=" + jobId;
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(resultUrl);
while (true) {
try {
code = client.executeMethod(method);
if (code == 200) {
InputStream is = method.getResponseBodyAsStream();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(is);
doc.getDocumentElement().normalize();
returnBody = doc.getDocumentElement();
Element jobStatusTag = (Element) returnBody.getElementsByTagName("jobstatus").item(0);
String jobStatus = jobStatusTag.getTextContent();
if (jobStatus.equals("0")) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
} else {
break;
}
method.releaseConnection();
} else {
s_logger.error("Error during queryJobAsync. Error code is " + code);
this.responseCode = code;
return null;
}
} catch (Exception ex) {
s_logger.error(ex);
}
}
return returnBody;
}
use of org.apache.commons.httpclient.methods.GetMethod in project CloudStack-archive by CloudStack-extras.
the class TestClientWithAPI method queryAsyncJobResult.
public static Element queryAsyncJobResult(String host, InputStream inputStream) {
Element returnBody = null;
Map<String, String> values = getSingleValueFromXML(inputStream, new String[] { "jobid" });
String jobId = values.get("jobid");
if (jobId == null) {
s_logger.error("Unable to get a jobId");
return null;
}
// s_logger.info("Job id is " + jobId);
String resultUrl = host + "?command=queryAsyncJobResult&jobid=" + jobId;
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(resultUrl);
while (true) {
try {
client.executeMethod(method);
// s_logger.info("Method is executed successfully. Following url was sent " + resultUrl);
InputStream is = method.getResponseBodyAsStream();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(is);
returnBody = doc.getDocumentElement();
doc.getDocumentElement().normalize();
Element jobStatusTag = (Element) returnBody.getElementsByTagName("jobstatus").item(0);
String jobStatus = jobStatusTag.getTextContent();
if (jobStatus.equals("0")) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
} else {
break;
}
} catch (Exception ex) {
s_logger.error(ex);
}
}
return returnBody;
}
use of org.apache.commons.httpclient.methods.GetMethod in project CloudStack-archive by CloudStack-extras.
the class TestClientWithAPI method executeRegistration.
private static String executeRegistration(String server, String username, String password) throws HttpException, IOException {
String url = server + "?command=registerUserKeys&id=" + _userId.get().toString();
s_logger.info("registering: " + username);
String returnValue = null;
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
int responseCode = client.executeMethod(method);
if (responseCode == 200) {
InputStream is = method.getResponseBodyAsStream();
Map<String, String> requestKeyValues = getSingleValueFromXML(is, new String[] { "apikey", "secretkey" });
_apiKey.set(requestKeyValues.get("apikey"));
returnValue = requestKeyValues.get("secretkey");
} else {
s_logger.error("registration failed with error code: " + responseCode);
}
return returnValue;
}
use of org.apache.commons.httpclient.methods.GetMethod in project CloudStack-archive by CloudStack-extras.
the class UserCloudAPIExecutor method main.
public static void main(String[] args) {
// Host
String host = null;
// Fully qualified URL with http(s)://host:port
String apiUrl = null;
// ApiKey and secretKey as given by your CloudStack vendor
String apiKey = null;
String secretKey = null;
try {
Properties prop = new Properties();
prop.load(new FileInputStream("usercloud.properties"));
// host
host = prop.getProperty("host");
if (host == null) {
System.out.println("Please specify a valid host in the format of http(s)://:/client/api in your usercloud.properties file.");
}
// apiUrl
apiUrl = prop.getProperty("apiUrl");
if (apiUrl == null) {
System.out.println("Please specify a valid API URL in the format of command=¶m1=¶m2=... in your usercloud.properties file.");
}
// apiKey
apiKey = prop.getProperty("apiKey");
if (apiKey == null) {
System.out.println("Please specify your API Key as provided by your CloudStack vendor in your usercloud.properties file.");
}
// secretKey
secretKey = prop.getProperty("secretKey");
if (secretKey == null) {
System.out.println("Please specify your secret Key as provided by your CloudStack vendor in your usercloud.properties file.");
}
if (apiUrl == null || apiKey == null || secretKey == null) {
return;
}
System.out.println("Constructing API call to host = '" + host + "' with API command = '" + apiUrl + "' using apiKey = '" + apiKey + "' and secretKey = '" + secretKey + "'");
// Step 1: Make sure your APIKey is URL encoded
String encodedApiKey = URLEncoder.encode(apiKey, "UTF-8");
// Step 2: URL encode each parameter value, then sort the parameters and apiKey in
// alphabetical order, and then toLowerCase all the parameters, parameter values and apiKey.
// Please note that if any parameters with a '&' as a value will cause this test client to fail since we are using
// '&' to delimit
// the string
List<String> sortedParams = new ArrayList<String>();
sortedParams.add("apikey=" + encodedApiKey.toLowerCase());
StringTokenizer st = new StringTokenizer(apiUrl, "&");
String url = null;
boolean first = true;
while (st.hasMoreTokens()) {
String paramValue = st.nextToken();
String param = paramValue.substring(0, paramValue.indexOf("="));
String value = URLEncoder.encode(paramValue.substring(paramValue.indexOf("=") + 1, paramValue.length()), "UTF-8");
if (first) {
url = param + "=" + value;
first = false;
} else {
url = url + "&" + param + "=" + value;
}
sortedParams.add(param.toLowerCase() + "=" + value.toLowerCase());
}
Collections.sort(sortedParams);
System.out.println("Sorted Parameters: " + sortedParams);
// Step 3: Construct the sorted URL and sign and URL encode the sorted URL with your secret key
String sortedUrl = null;
first = true;
for (String param : sortedParams) {
if (first) {
sortedUrl = param;
first = false;
} else {
sortedUrl = sortedUrl + "&" + param;
}
}
System.out.println("sorted URL : " + sortedUrl);
String encodedSignature = signRequest(sortedUrl, secretKey);
// Step 4: Construct the final URL we want to send to the CloudStack Management Server
// Final result should look like:
// http(s)://://client/api?&apiKey=&signature=
String finalUrl = host + "?" + url + "&apiKey=" + apiKey + "&signature=" + encodedSignature;
System.out.println("final URL : " + finalUrl);
// Step 5: Perform a HTTP GET on this URL to execute the command
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(finalUrl);
int responseCode = client.executeMethod(method);
if (responseCode == 200) {
// SUCCESS!
System.out.println("Successfully executed command");
} else {
// FAILED!
System.out.println("Unable to execute command with response code: " + responseCode);
}
} catch (Throwable t) {
System.out.println(t);
}
}
Aggregations