Search in sources :

Example 26 with HttpMethod

use of org.apache.commons.httpclient.HttpMethod in project CloudStack-archive by CloudStack-extras.

the class VirtualMachine method deployVM.

public void deployVM(long zoneId, long serviceOfferingId, long templateId, String server, String apiKey, String secretKey) throws IOException {
    String encodedZoneId = URLEncoder.encode("" + zoneId, "UTF-8");
    String encodedServiceOfferingId = URLEncoder.encode("" + serviceOfferingId, "UTF-8");
    String encodedTemplateId = URLEncoder.encode("" + templateId, "UTF-8");
    String encodedApiKey = URLEncoder.encode(apiKey, "UTF-8");
    String requestToSign = "apiKey=" + encodedApiKey + "&command=deployVirtualMachine&serviceOfferingId=" + encodedServiceOfferingId + "&templateId=" + encodedTemplateId + "&zoneId=" + encodedZoneId;
    requestToSign = requestToSign.toLowerCase();
    String signature = TestClientWithAPI.signRequest(requestToSign, secretKey);
    String encodedSignature = URLEncoder.encode(signature, "UTF-8");
    String url = server + "?command=deployVirtualMachine" + "&zoneId=" + encodedZoneId + "&serviceOfferingId=" + encodedServiceOfferingId + "&templateId=" + encodedTemplateId + "&apiKey=" + encodedApiKey + "&signature=" + encodedSignature;
    s_logger.info("Sending this request to deploy a VM: " + url);
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    int responseCode = client.executeMethod(method);
    s_logger.info("deploy linux vm response code: " + responseCode);
    if (responseCode == 200) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, String> values = TestClientWithAPI.getSingleValueFromXML(is, new String[] { "id", "ipaddress" });
        long linuxVMId = Long.parseLong(values.get("id"));
        s_logger.info("got linux virtual machine id: " + linuxVMId);
        this.setPrivateIp(values.get("ipaddress"));
    } else if (responseCode == 500) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, String> errorInfo = TestClientWithAPI.getSingleValueFromXML(is, new String[] { "errorcode", "description" });
        s_logger.error("deploy linux vm test failed with errorCode: " + errorInfo.get("errorCode") + " and description: " + errorInfo.get("description"));
    } else {
        s_logger.error("internal error processing request: " + method.getStatusText());
    }
}
Also used : InputStream(java.io.InputStream) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) Map(java.util.Map) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 27 with HttpMethod

use of org.apache.commons.httpclient.HttpMethod 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 28 with HttpMethod

use of org.apache.commons.httpclient.HttpMethod 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 29 with HttpMethod

use of org.apache.commons.httpclient.HttpMethod 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 30 with HttpMethod

use of org.apache.commons.httpclient.HttpMethod 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)

Aggregations

HttpMethod (org.apache.commons.httpclient.HttpMethod)151 HttpClient (org.apache.commons.httpclient.HttpClient)99 GetMethod (org.apache.commons.httpclient.methods.GetMethod)95 InputStream (java.io.InputStream)61 IOException (java.io.IOException)43 ArrayList (java.util.ArrayList)30 HttpException (org.apache.commons.httpclient.HttpException)28 Map (java.util.Map)24 Test (org.junit.Test)23 Element (org.w3c.dom.Element)22 HashMap (java.util.HashMap)20 PostMethod (org.apache.commons.httpclient.methods.PostMethod)19 Header (org.apache.commons.httpclient.Header)17 List (java.util.List)14 NameValuePair (org.apache.commons.httpclient.NameValuePair)13 NodeList (org.w3c.dom.NodeList)12 FileInputStream (java.io.FileInputStream)10 HttpTest (org.apache.sling.commons.testing.integration.HttpTest)10 SAXBuilder (org.jdom.input.SAXBuilder)10 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)9