Search in sources :

Example 71 with GetMethod

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;
}
Also used : HashMap(java.util.HashMap) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Properties(java.util.Properties) FileInputStream(java.io.FileInputStream) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) File(java.io.File) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 72 with GetMethod

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;
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Element(org.w3c.dom.Element) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) Document(org.w3c.dom.Document) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 73 with GetMethod

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;
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) InputStream(java.io.InputStream) Element(org.w3c.dom.Element) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) Document(org.w3c.dom.Document) HttpMethod(org.apache.commons.httpclient.HttpMethod) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 74 with GetMethod

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;
}
Also used : InputStream(java.io.InputStream) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 75 with GetMethod

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=&param1=&param2=... 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);
    }
}
Also used : StringTokenizer(java.util.StringTokenizer) HttpClient(org.apache.commons.httpclient.HttpClient) ArrayList(java.util.ArrayList) GetMethod(org.apache.commons.httpclient.methods.GetMethod) Properties(java.util.Properties) FileInputStream(java.io.FileInputStream) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Aggregations

GetMethod (org.apache.commons.httpclient.methods.GetMethod)357 HttpClient (org.apache.commons.httpclient.HttpClient)216 HttpMethod (org.apache.commons.httpclient.HttpMethod)93 IOException (java.io.IOException)82 Test (org.junit.Test)70 InputStream (java.io.InputStream)65 HttpException (org.apache.commons.httpclient.HttpException)41 Map (java.util.Map)39 ArrayList (java.util.ArrayList)37 HashMap (java.util.HashMap)36 JSONParser (org.json.simple.parser.JSONParser)34 JSONObject (org.json.simple.JSONObject)31 Header (org.apache.commons.httpclient.Header)22 Element (org.w3c.dom.Element)22 PostMethod (org.apache.commons.httpclient.methods.PostMethod)21 TypeToken (com.google.gson.reflect.TypeToken)20 List (java.util.List)19 HttpState (org.apache.commons.httpclient.HttpState)18 URI (java.net.URI)17 JSONArray (org.json.simple.JSONArray)17