Search in sources :

Example 96 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(HashMap<String, Integer> expectedEvents, String level, String host, String parameters) {
    boolean result = false;
    HashMap<String, Integer> actualEvents = new HashMap<String, Integer>();
    try {
        // get actual events
        String url = host + "/?command=listEvents&" + parameters;
        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();
    } catch (Exception ex) {
        s_logger.error(ex);
    }
    // compare actual events with expected events
    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;
    }
    return result;
}
Also used : HashMap(java.util.HashMap) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 97 with HttpMethod

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

the class Test method executeTest.

public boolean executeTest() {
    int error = 0;
    Element rootElement = this.getInputFile().get(0).getDocumentElement();
    NodeList commandLst = rootElement.getElementsByTagName("command");
    //Analyze each command, send request and build the array list of api commands
    for (int i = 0; i < commandLst.getLength(); i++) {
        Node fstNode = commandLst.item(i);
        Element fstElmnt = (Element) fstNode;
        //new command
        ApiCommand api = new ApiCommand(fstElmnt, this.getParam(), this.getCommands());
        //send a command
        api.sendCommand(this.getClient(), null);
    }
    //Try to create portForwarding rule for all available private/public ports
    ArrayList<String> port = new ArrayList<String>();
    for (int j = 1; j < 1000; j++) {
        port.add(Integer.toString(j));
    }
    //try all public ports	
    for (String portValue : port) {
        try {
            s_logger.info("public port is " + portValue);
            String url = "http://" + this.getParam().get("hostip") + ":8096/?command=createNetworkRule&publicPort=" + portValue + "&privatePort=22&protocol=tcp&isForward=true&securityGroupId=1&account=admin";
            HttpClient client = new HttpClient();
            HttpMethod method = new GetMethod(url);
            int responseCode = client.executeMethod(method);
            if (responseCode != 200) {
                error++;
                s_logger.error("Can't create portForwarding network rule for the public port " + portValue + ". Request was sent with url " + url);
            }
        } catch (Exception ex) {
            s_logger.error(ex);
        }
    }
    if (error != 0)
        return false;
    else
        return true;
}
Also used : Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) HttpClient(org.apache.commons.httpclient.HttpClient) ArrayList(java.util.ArrayList) GetMethod(org.apache.commons.httpclient.methods.GetMethod) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 98 with HttpMethod

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

the class StressTestDirectAttach method executeDeployment.

private static Integer executeDeployment(String server, String developerServer, String username) throws HttpException, IOException {
    // test steps:
    // - create user
    // - deploy Windows VM
    // - deploy Linux VM
    // - associate IP address
    // - create two IP forwarding rules
    // - create load balancer rule
    // - list IP forwarding rules
    // - list load balancer rules
    // -----------------------------
    // CREATE USER
    // -----------------------------
    String encodedUsername = URLEncoder.encode(username, "UTF-8");
    String encryptedPassword = createMD5Password(username);
    String encodedPassword = URLEncoder.encode(encryptedPassword, "UTF-8");
    String url = server + "?command=createUser&username=" + encodedUsername + "&password=" + encodedPassword + "&firstname=Test&lastname=Test&email=test@vmops.com&domainId=1&accounttype=0";
    if (accountName != null) {
        url = server + "?command=createUser&username=" + encodedUsername + "&password=" + encodedPassword + "&firstname=Test&lastname=Test&email=test@vmops.com&domainId=1&accounttype=0&account=" + accountName;
    }
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    int responseCode = client.executeMethod(method);
    long userId = -1;
    if (responseCode == 200) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, String> userIdValues = getSingleValueFromXML(is, new String[] { "id", "account" });
        String userIdStr = userIdValues.get("id");
        s_logger.info("created user " + username + " with id " + userIdStr);
        if (userIdStr != null) {
            userId = Long.parseLong(userIdStr);
            _userId.set(userId);
            _account.set(userIdValues.get("account"));
            if (userId == -1) {
                s_logger.error("create user (" + username + ") failed to retrieve a valid user id, aborting depolyment test");
                return -1;
            }
        }
    } else {
        s_logger.error("create user test failed for user " + username + " with error code :" + responseCode);
        return responseCode;
    }
    _secretKey.set(executeRegistration(server, username, username));
    if (_secretKey.get() == null) {
        s_logger.error("FAILED to retrieve secret key during registration, skipping user: " + username);
        return -1;
    } else {
        s_logger.info("got secret key: " + _secretKey.get());
        s_logger.info("got api key: " + _apiKey.get());
    }
    // ---------------------------------
    // CREATE NETWORK GROUP AND ADD INGRESS RULE TO IT
    // ---------------------------------
    String networkAccount = null;
    if (accountName != null) {
        networkAccount = accountName;
    } else {
        networkAccount = encodedUsername;
    }
    String encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8");
    String requestToSign = "apikey=" + encodedApiKey + "&command=createSecurityGroup&name=" + encodedUsername;
    requestToSign = requestToSign.toLowerCase();
    String signature = signRequest(requestToSign, _secretKey.get());
    String encodedSignature = URLEncoder.encode(signature, "UTF-8");
    url = developerServer + "?command=createSecurityGroup&name=" + encodedUsername + "&apikey=" + encodedApiKey + "&signature=" + encodedSignature;
    method = new GetMethod(url);
    responseCode = client.executeMethod(method);
    if (responseCode == 200) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, String> values = getSingleValueFromXML(is, new String[] { "id" });
        if (values.get("id") == null) {
            s_logger.info("Create network rule response code: 401");
            return 401;
        } else {
            s_logger.info("Create security group response code: " + responseCode);
        }
    } else {
        s_logger.error("Create security group failed with error code: " + responseCode + ". Following URL was sent: " + url);
        return responseCode;
    }
    String encodedCidr = URLEncoder.encode("192.168.1.143/32", "UTF-8");
    url = server + "?command=authorizeSecurityGroupIngress&cidrlist=" + encodedCidr + "&endport=22&" + "securitygroupname=" + encodedUsername + "&protocol=tcp&startport=22&account=" + networkAccount + "&domainid=1";
    method = new GetMethod(url);
    responseCode = client.executeMethod(method);
    if (responseCode == 200) {
        InputStream input = method.getResponseBodyAsStream();
        Element el = queryAsyncJobResult(server, input);
        Map<String, String> values = getSingleValueFromXML(el, new String[] { "id" });
        if (values.get("id") == null) {
            s_logger.info("Authorise security group ingress response code: 401");
            return 401;
        } else {
            s_logger.info("Authorise security group ingress response code: " + responseCode);
        }
    } else {
        s_logger.error("Authorise security group ingress failed with error code: " + responseCode + ". Following URL was sent: " + url);
        return responseCode;
    }
    // ---------------------------------
    // DEPLOY LINUX VM
    // ---------------------------------
    {
        long templateId = 2;
        String encodedZoneId = URLEncoder.encode("" + zoneId, "UTF-8");
        String encodedServiceOfferingId = URLEncoder.encode("" + serviceOfferingId, "UTF-8");
        String encodedTemplateId = URLEncoder.encode("" + templateId, "UTF-8");
        encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8");
        requestToSign = "apikey=" + encodedApiKey + "&command=deployVirtualMachine&securitygrouplist=" + encodedUsername + "&serviceofferingid=" + encodedServiceOfferingId + "&templateid=" + encodedTemplateId + "&zoneid=" + encodedZoneId;
        requestToSign = requestToSign.toLowerCase();
        signature = signRequest(requestToSign, _secretKey.get());
        encodedSignature = URLEncoder.encode(signature, "UTF-8");
        url = developerServer + "?command=deployVirtualMachine&securitygrouplist=" + encodedUsername + "&zoneid=" + encodedZoneId + "&serviceofferingid=" + encodedServiceOfferingId + "&templateid=" + encodedTemplateId + "&apikey=" + encodedApiKey + "&signature=" + encodedSignature;
        method = new GetMethod(url);
        responseCode = client.executeMethod(method);
        if (responseCode == 200) {
            InputStream input = method.getResponseBodyAsStream();
            Element el = queryAsyncJobResult(server, input);
            Map<String, String> values = getSingleValueFromXML(el, new String[] { "id", "ipaddress" });
            if ((values.get("ipaddress") == null) || (values.get("id") == null)) {
                s_logger.info("deploy linux vm response code: 401");
                return 401;
            } else {
                s_logger.info("deploy linux vm response code: " + responseCode);
                long linuxVMId = Long.parseLong(values.get("id"));
                s_logger.info("got linux virtual machine id: " + linuxVMId);
                _linuxVmId.set(values.get("id"));
                _linuxIP.set(values.get("ipaddress"));
                _linuxPassword.set("rs-ccb35ea5");
            }
        } else {
            s_logger.error("deploy linux vm failed with error code: " + responseCode + ". Following URL was sent: " + url);
            return responseCode;
        }
    }
    //Create a new volume
    {
        url = server + "?command=createVolume&diskofferingid=" + diskOfferingId + "&zoneid=" + zoneId + "&name=newvolume&account=" + _account.get() + "&domainid=1";
        s_logger.info("Creating volume....");
        client = new HttpClient();
        method = new GetMethod(url);
        responseCode = client.executeMethod(method);
        if (responseCode == 200) {
            InputStream input = method.getResponseBodyAsStream();
            Element el = queryAsyncJobResult(server, input);
            Map<String, String> values = getSingleValueFromXML(el, new String[] { "id" });
            if (values.get("id") == null) {
                s_logger.info("create volume response code: 401");
                return 401;
            } else {
                s_logger.info("create volume response code: " + responseCode);
                String volumeId = values.get("id");
                s_logger.info("got volume id: " + volumeId);
                _newVolume.set(volumeId);
            }
        } else {
            s_logger.error("create volume failed with error code: " + responseCode + ". Following URL was sent: " + url);
            return responseCode;
        }
    }
    //attach a new volume to the vm
    {
        url = server + "?command=attachVolume&id=" + _newVolume.get() + "&virtualmachineid=" + _linuxVmId.get();
        s_logger.info("Attaching volume with id " + _newVolume.get() + " to the vm " + _linuxVmId.get());
        client = new HttpClient();
        method = new GetMethod(url);
        responseCode = client.executeMethod(method);
        s_logger.info("Attach data volume response code: " + responseCode);
        if (responseCode == 200) {
            InputStream input = method.getResponseBodyAsStream();
            Element el = queryAsyncJobResult(server, input);
            Map<String, String> values = getSingleValueFromXML(el, new String[] { "id" });
            if (values.get("id") == null) {
                s_logger.info("Attach volume response code: 401");
                return 401;
            } else {
                s_logger.info("Attach volume response code: " + responseCode);
            }
        } else {
            s_logger.error("Attach volume failed with error code: " + responseCode + ". Following URL was sent: " + url);
            return responseCode;
        }
    }
    //DEPLOY SECOND VM, ADD VOLUME TO IT
    // ---------------------------------
    // DEPLOY another linux vm
    // ---------------------------------
    {
        long templateId = 2;
        String encodedZoneId = URLEncoder.encode("" + zoneId, "UTF-8");
        String encodedServiceOfferingId = URLEncoder.encode("" + serviceOfferingId, "UTF-8");
        String encodedTemplateId = URLEncoder.encode("" + templateId, "UTF-8");
        encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8");
        requestToSign = "apikey=" + encodedApiKey + "&command=deployVirtualMachine&securitygrouplist=" + encodedUsername + "&serviceofferingid=" + encodedServiceOfferingId + "&templateid=" + encodedTemplateId + "&zoneid=" + encodedZoneId;
        requestToSign = requestToSign.toLowerCase();
        signature = signRequest(requestToSign, _secretKey.get());
        encodedSignature = URLEncoder.encode(signature, "UTF-8");
        url = developerServer + "?command=deployVirtualMachine&securitygrouplist=" + encodedUsername + "&zoneid=" + encodedZoneId + "&serviceofferingid=" + encodedServiceOfferingId + "&templateid=" + encodedTemplateId + "&apikey=" + encodedApiKey + "&signature=" + encodedSignature;
        method = new GetMethod(url);
        responseCode = client.executeMethod(method);
        if (responseCode == 200) {
            InputStream input = method.getResponseBodyAsStream();
            Element el = queryAsyncJobResult(server, input);
            Map<String, String> values = getSingleValueFromXML(el, new String[] { "id", "ipaddress" });
            if ((values.get("ipaddress") == null) || (values.get("id") == null)) {
                s_logger.info("deploy linux vm response code: 401");
                return 401;
            } else {
                s_logger.info("deploy linux vm response code: " + responseCode);
                long linuxVMId = Long.parseLong(values.get("id"));
                s_logger.info("got linux virtual machine id: " + linuxVMId);
                _linuxVmId1.set(values.get("id"));
            }
        } else {
            s_logger.error("deploy linux vm failed with error code: " + responseCode + ". Following URL was sent: " + url);
            return responseCode;
        }
    }
    //Create a new volume
    {
        url = server + "?command=createVolume&diskofferingid=" + diskOfferingId1 + "&zoneid=" + zoneId + "&name=newvolume1&account=" + _account.get() + "&domainid=1";
        s_logger.info("Creating volume....");
        client = new HttpClient();
        method = new GetMethod(url);
        responseCode = client.executeMethod(method);
        if (responseCode == 200) {
            InputStream input = method.getResponseBodyAsStream();
            Element el = queryAsyncJobResult(server, input);
            Map<String, String> values = getSingleValueFromXML(el, new String[] { "id" });
            if (values.get("id") == null) {
                s_logger.info("create volume response code: 401");
                return 401;
            } else {
                s_logger.info("create volume response code: " + responseCode);
                String volumeId = values.get("id");
                s_logger.info("got volume id: " + volumeId);
                _newVolume1.set(volumeId);
            }
        } else {
            s_logger.error("create volume failed with error code: " + responseCode + ". Following URL was sent: " + url);
            return responseCode;
        }
    }
    //attach a new volume to the vm
    {
        url = server + "?command=attachVolume&id=" + _newVolume1.get() + "&virtualmachineid=" + _linuxVmId1.get();
        s_logger.info("Attaching volume with id " + _newVolume1.get() + " to the vm " + _linuxVmId1.get());
        client = new HttpClient();
        method = new GetMethod(url);
        responseCode = client.executeMethod(method);
        s_logger.info("Attach data volume response code: " + responseCode);
        if (responseCode == 200) {
            InputStream input = method.getResponseBodyAsStream();
            Element el = queryAsyncJobResult(server, input);
            Map<String, String> values = getSingleValueFromXML(el, new String[] { "id" });
            if (values.get("id") == null) {
                s_logger.info("Attach volume response code: 401");
                return 401;
            } else {
                s_logger.info("Attach volume response code: " + responseCode);
            }
        } else {
            s_logger.error("Attach volume failed with error code: " + responseCode + ". Following URL was sent: " + url);
            return responseCode;
        }
    }
    return 200;
}
Also used : InputStream(java.io.InputStream) HttpClient(org.apache.commons.httpclient.HttpClient) Element(org.w3c.dom.Element) GetMethod(org.apache.commons.httpclient.methods.GetMethod) HashMap(java.util.HashMap) Map(java.util.Map) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 99 with HttpMethod

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

the class TestClientWithAPI method getNetworkStat.

private static boolean getNetworkStat(String server) {
    try {
        String url = server + "?command=listAccountStatistics&account=" + _account.get();
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(url);
        int responseCode = client.executeMethod(method);
        s_logger.info("listAccountStatistics response code: " + responseCode);
        if (responseCode == 200) {
            InputStream is = method.getResponseBodyAsStream();
            Map<String, String> requestKeyValues = getSingleValueFromXML(is, new String[] { "receivedbytes", "sentbytes" });
            int bytesReceived = Integer.parseInt(requestKeyValues.get("receivedbytes"));
            int bytesSent = Integer.parseInt(requestKeyValues.get("sentbytes"));
            if ((bytesReceived > 100000000) && (bytesSent > 0)) {
                s_logger.info("Network stat is correct for account" + _account.get() + "; bytest received is " + bytesReceived + " and bytes sent is " + bytesSent);
                return true;
            } else {
                s_logger.error("Incorrect value for bytes received/sent for the account " + _account.get() + ". We got " + bytesReceived + " bytes received; " + " and " + bytesSent + " bytes sent");
                return false;
            }
        } else {
            s_logger.error("listAccountStatistics failed with error code: " + responseCode + ". Following URL was sent: " + url);
            return false;
        }
    } catch (Exception ex) {
        s_logger.error("Exception while sending command listAccountStatistics");
        return false;
    }
}
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) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 100 with HttpMethod

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

the class TestClientWithAPI method executeCleanup.

private static int executeCleanup(String server, String developerServer, String username) throws HttpException, IOException {
    // test steps:
    // - get user
    // - delete user
    // -----------------------------
    // GET USER
    // -----------------------------
    String userId = _userId.get().toString();
    String encodedUserId = URLEncoder.encode(userId, "UTF-8");
    String url = server + "?command=listUsers&id=" + encodedUserId;
    s_logger.info("Cleaning up resources for user: " + userId + " with url " + url);
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    int responseCode = client.executeMethod(method);
    s_logger.info("get user response code: " + responseCode);
    if (responseCode == 200) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, String> userInfo = getSingleValueFromXML(is, new String[] { "username", "id", "account" });
        if (!username.equals(userInfo.get("username"))) {
            s_logger.error("get user failed to retrieve requested user, aborting cleanup test" + ". Following URL was sent: " + url);
            return -1;
        }
    } else {
        s_logger.error("get user failed with error code: " + responseCode + ". Following URL was sent: " + url);
        return responseCode;
    }
    // -----------------------------
    // UPDATE USER
    // -----------------------------
    {
        url = server + "?command=updateUser&id=" + userId + "&firstname=delete&lastname=me";
        client = new HttpClient();
        method = new GetMethod(url);
        responseCode = client.executeMethod(method);
        s_logger.info("update user response code: " + responseCode);
        if (responseCode == 200) {
            InputStream is = method.getResponseBodyAsStream();
            Map<String, String> success = getSingleValueFromXML(is, new String[] { "success" });
            s_logger.info("update user..success? " + success.get("success"));
        } else {
            s_logger.error("update user failed with error code: " + responseCode + ". Following URL was sent: " + url);
            return responseCode;
        }
    }
    // -----------------------------
    // Detach existin dataVolume, create a new volume, attach it to the vm
    // -----------------------------
    {
        url = server + "?command=listVolumes&virtualMachineId=" + _linuxVmId.get() + "&type=dataDisk";
        s_logger.info("Getting dataDisk id of Centos vm");
        client = new HttpClient();
        method = new GetMethod(url);
        responseCode = client.executeMethod(method);
        s_logger.info("List volumes response code: " + responseCode);
        if (responseCode == 200) {
            InputStream is = method.getResponseBodyAsStream();
            Map<String, String> success = getSingleValueFromXML(is, new String[] { "id" });
            s_logger.info("Got dataDiskVolume with id " + success.get("id"));
            _dataVolume.set(success.get("id"));
        } else {
            s_logger.error("List volumes failed with error code: " + responseCode + ". Following URL was sent: " + url);
            return responseCode;
        }
    }
    // Detach volume
    {
        url = server + "?command=detachVolume&id=" + _dataVolume.get();
        s_logger.info("Detaching volume with id " + _dataVolume.get());
        client = new HttpClient();
        method = new GetMethod(url);
        responseCode = client.executeMethod(method);
        s_logger.info("Detach data volume response code: " + responseCode);
        if (responseCode == 200) {
            InputStream input = method.getResponseBodyAsStream();
            Element el = queryAsyncJobResult(server, input);
            s_logger.info("The volume was detached successfully");
        } else {
            s_logger.error("Detach data disk failed with error code: " + responseCode + ". Following URL was sent: " + url);
            return responseCode;
        }
    }
    // Delete a volume
    {
        url = server + "?command=deleteVolume&id=" + _dataVolume.get();
        s_logger.info("Deleting volume with id " + _dataVolume.get());
        client = new HttpClient();
        method = new GetMethod(url);
        responseCode = client.executeMethod(method);
        s_logger.info("Delete data volume response code: " + responseCode);
        if (responseCode == 200) {
            s_logger.info("The volume was deleted successfully");
        } else {
            s_logger.error("Delete volume failed with error code: " + responseCode + ". Following URL was sent: " + url);
            return responseCode;
        }
    }
    // Create a new volume
    {
        url = server + "?command=createVolume&diskofferingid=" + diskOfferingId + "&zoneid=" + zoneId + "&name=newvolume&account=" + _account.get() + "&domainid=1";
        s_logger.info("Creating volume....");
        client = new HttpClient();
        method = new GetMethod(url);
        responseCode = client.executeMethod(method);
        if (responseCode == 200) {
            InputStream input = method.getResponseBodyAsStream();
            Element el = queryAsyncJobResult(server, input);
            Map<String, String> values = getSingleValueFromXML(el, new String[] { "id" });
            if (values.get("id") == null) {
                s_logger.info("create volume response code: 401");
                return 401;
            } else {
                s_logger.info("create volume response code: " + responseCode);
                long volumeId = Long.parseLong(values.get("id"));
                s_logger.info("got volume id: " + volumeId);
                _newVolume.set(values.get("id"));
            }
        } else {
            s_logger.error("create volume failed with error code: " + responseCode + ". Following URL was sent: " + url);
            return responseCode;
        }
    }
    // attach a new volume to the vm
    {
        url = server + "?command=attachVolume&id=" + _newVolume.get() + "&virtualmachineid=" + _linuxVmId.get();
        s_logger.info("Attaching volume with id " + _newVolume.get() + " to the vm " + _linuxVmId.get());
        client = new HttpClient();
        method = new GetMethod(url);
        responseCode = client.executeMethod(method);
        s_logger.info("Attach data volume response code: " + responseCode);
        if (responseCode == 200) {
            InputStream input = method.getResponseBodyAsStream();
            Element el = queryAsyncJobResult(server, input);
            s_logger.info("The volume was attached successfully");
        } else {
            s_logger.error("Attach volume failed with error code: " + responseCode + ". Following URL was sent: " + url);
            return responseCode;
        }
    }
    // Create a snapshot
    // list volumes
    {
        url = server + "?command=listVolumes&virtualMachineId=" + _linuxVmId.get() + "&type=root";
        s_logger.info("Getting rootDisk id of Centos vm");
        client = new HttpClient();
        method = new GetMethod(url);
        responseCode = client.executeMethod(method);
        s_logger.info("List volumes response code: " + responseCode);
        if (responseCode == 200) {
            InputStream is = method.getResponseBodyAsStream();
            Map<String, String> success = getSingleValueFromXML(is, new String[] { "id" });
            if (success.get("id") == null) {
                s_logger.error("Unable to get root volume. Followin url was sent: " + url);
            }
            s_logger.info("Got rootVolume with id " + success.get("id"));
            _rootVolume.set(success.get("id"));
        } else {
            s_logger.error("List volumes failed with error code: " + responseCode + ". Following URL was sent: " + url);
            return responseCode;
        }
    }
    // //Create snapshot from root disk volume
    String encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8");
    String requestToSign = "apikey=" + encodedApiKey + "&command=createSnapshot&volumeid=" + _rootVolume.get();
    requestToSign = requestToSign.toLowerCase();
    String signature = signRequest(requestToSign, _secretKey.get());
    String encodedSignature = URLEncoder.encode(signature, "UTF-8");
    url = developerServer + "?command=createSnapshot&volumeid=" + _rootVolume.get() + "&apikey=" + encodedApiKey + "&signature=" + encodedSignature;
    client = new HttpClient();
    method = new GetMethod(url);
    responseCode = client.executeMethod(method);
    s_logger.info("Create snapshot response code: " + responseCode);
    if (responseCode == 200) {
        InputStream input = method.getResponseBodyAsStream();
        Element el = queryAsyncJobResult(server, input);
        Map<String, String> values = getSingleValueFromXML(el, new String[] { "id" });
        if (values.get("id") == null) {
            s_logger.info("create snapshot response code: 401");
            return 401;
        } else {
            s_logger.info("create snapshot response code: " + responseCode + ". Got snapshot with id " + values.get("id"));
            _snapshot.set(values.get("id"));
        }
    } else {
        s_logger.error("create snapshot failed with error code: " + responseCode + ". Following URL was sent: " + url);
        return responseCode;
    }
    // Create volume from the snapshot created on the previous step and attach it to the running vm
    /*      encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8");
        requestToSign = "apikey=" + encodedApiKey + "&command=createVolume&name=" + _account.get() + "&snapshotid=" + _snapshot.get();
        requestToSign = requestToSign.toLowerCase();
        signature = signRequest(requestToSign, _secretKey.get());
        encodedSignature = URLEncoder.encode(signature, "UTF-8");

        url = developerServer + "?command=createVolume&name=" + _account.get() + "&snapshotid=" + _snapshot.get() + "&apikey=" + encodedApiKey + "&signature=" + encodedSignature;
        client = new HttpClient();
        method = new GetMethod(url);
        responseCode = client.executeMethod(method);
        s_logger.info("Create volume from snapshot response code: " + responseCode);
        if (responseCode == 200) {
            InputStream input = method.getResponseBodyAsStream();
            Element el = queryAsyncJobResult(server, input);
            Map<String, String> values = getSingleValueFromXML(el, new String[] { "id" });

            if (values.get("id") == null) {
                s_logger.info("create volume from snapshot response code: 401");
                return 401;
            } else {
                s_logger.info("create volume from snapshot response code: " + responseCode + ". Got volume with id " + values.get("id") + ". The command was sent with url " + url);
                _volumeFromSnapshot.set(values.get("id"));
            }
        } else {
            s_logger.error("create volume from snapshot failed with error code: " + responseCode + ". Following URL was sent: " + url);
            return responseCode;
        }

        {
            url = server + "?command=attachVolume&id=" + _volumeFromSnapshot.get() + "&virtualmachineid=" + _linuxVmId.get();
            s_logger.info("Attaching volume with id " + _volumeFromSnapshot.get() + " to the vm " + _linuxVmId.get());
            client = new HttpClient();
            method = new GetMethod(url);
            responseCode = client.executeMethod(method);
            s_logger.info("Attach volume from snapshot to linux vm response code: " + responseCode);
            if (responseCode == 200) {
                InputStream input = method.getResponseBodyAsStream();
                Element el = queryAsyncJobResult(server, input);
                s_logger.info("The volume created from snapshot was attached successfully to linux vm");
            } else {
                s_logger.error("Attach volume created from snapshot failed with error code: " + responseCode + ". Following URL was sent: " + url);
                return responseCode;
            }
        }
*/
    // -----------------------------
    // Execute reboot/stop/start commands for the VMs before deleting the account - made to exercise xen
    // -----------------------------
    // Reboot windows VM
    requestToSign = "apikey=" + encodedApiKey + "&command=rebootVirtualMachine&id=" + _windowsVmId.get();
    requestToSign = requestToSign.toLowerCase();
    signature = signRequest(requestToSign, _secretKey.get());
    encodedSignature = URLEncoder.encode(signature, "UTF-8");
    url = developerServer + "?command=rebootVirtualMachine&id=" + _windowsVmId.get() + "&apikey=" + encodedApiKey + "&signature=" + encodedSignature;
    client = new HttpClient();
    method = new GetMethod(url);
    responseCode = client.executeMethod(method);
    s_logger.info("Reboot windows Vm response code: " + responseCode);
    if (responseCode == 200) {
        InputStream input = method.getResponseBodyAsStream();
        Element el = queryAsyncJobResult(server, input);
        Map<String, String> success = getSingleValueFromXML(el, new String[] { "success" });
        s_logger.info("Windows VM was rebooted with the status: " + success.get("success"));
    } else {
        s_logger.error("Reboot windows VM test failed with error code: " + responseCode + ". Following URL was sent: " + url);
        return responseCode;
    }
    // Stop centos VM
    requestToSign = "apikey=" + encodedApiKey + "&command=stopVirtualMachine&id=" + _linuxVmId.get();
    requestToSign = requestToSign.toLowerCase();
    signature = signRequest(requestToSign, _secretKey.get());
    encodedSignature = URLEncoder.encode(signature, "UTF-8");
    url = developerServer + "?command=stopVirtualMachine&id=" + _linuxVmId.get() + "&apikey=" + encodedApiKey + "&signature=" + encodedSignature;
    client = new HttpClient();
    method = new GetMethod(url);
    responseCode = client.executeMethod(method);
    s_logger.info("Stop linux Vm response code: " + responseCode);
    if (responseCode == 200) {
        InputStream input = method.getResponseBodyAsStream();
        Element el = queryAsyncJobResult(server, input);
        Map<String, String> success = getSingleValueFromXML(el, new String[] { "success" });
        s_logger.info("Linux VM was stopped with the status: " + success.get("success"));
    } else {
        s_logger.error("Stop linux VM test failed with error code: " + responseCode + ". Following URL was sent: " + url);
        return responseCode;
    }
    // Create private template from root disk volume
    requestToSign = "apikey=" + encodedApiKey + "&command=createTemplate" + "&displaytext=" + _account.get() + "&name=" + _account.get() + "&ostypeid=11" + "&snapshotid=" + _snapshot.get();
    requestToSign = requestToSign.toLowerCase();
    signature = signRequest(requestToSign, _secretKey.get());
    encodedSignature = URLEncoder.encode(signature, "UTF-8");
    url = developerServer + "?command=createTemplate" + "&displaytext=" + _account.get() + "&name=" + _account.get() + "&ostypeid=11" + "&snapshotid=" + _snapshot.get() + "&apikey=" + encodedApiKey + "&signature=" + encodedSignature;
    client = new HttpClient();
    method = new GetMethod(url);
    responseCode = client.executeMethod(method);
    s_logger.info("Create private template response code: " + responseCode);
    if (responseCode == 200) {
        InputStream input = method.getResponseBodyAsStream();
        Element el = queryAsyncJobResult(server, input);
        Map<String, String> values = getSingleValueFromXML(el, new String[] { "id" });
        if (values.get("id") == null) {
            s_logger.info("create private template response code: 401");
            return 401;
        } else {
            s_logger.info("create private template response code: " + responseCode);
        }
    } else {
        s_logger.error("create private template failed with error code: " + responseCode + ". Following URL was sent: " + url);
        return responseCode;
    }
    // Start centos VM
    requestToSign = "apikey=" + encodedApiKey + "&command=startVirtualMachine&id=" + _windowsVmId.get();
    requestToSign = requestToSign.toLowerCase();
    signature = signRequest(requestToSign, _secretKey.get());
    encodedSignature = URLEncoder.encode(signature, "UTF-8");
    url = developerServer + "?command=startVirtualMachine&id=" + _windowsVmId.get() + "&apikey=" + encodedApiKey + "&signature=" + encodedSignature;
    client = new HttpClient();
    method = new GetMethod(url);
    responseCode = client.executeMethod(method);
    s_logger.info("Start linux Vm response code: " + responseCode);
    if (responseCode != 200) {
        s_logger.error("Start linux VM test failed with error code: " + responseCode + ". Following URL was sent: " + url);
        return responseCode;
    }
    // get domainRouter id
    {
        url = server + "?command=listRouters&zoneid=" + zoneId + "&account=" + _account.get() + "&domainid=1";
        client = new HttpClient();
        method = new GetMethod(url);
        responseCode = client.executeMethod(method);
        s_logger.info("List domain routers response code: " + responseCode);
        if (responseCode == 200) {
            InputStream is = method.getResponseBodyAsStream();
            Map<String, String> success = getSingleValueFromXML(is, new String[] { "id" });
            s_logger.info("Got the domR with id " + success.get("id"));
            _domainRouterId.set(success.get("id"));
        } else {
            s_logger.error("List domain routers failed with error code: " + responseCode + ". Following URL was sent: " + url);
            return responseCode;
        }
    }
    // reboot the domain router
    {
        url = server + "?command=rebootRouter&id=" + _domainRouterId.get();
        s_logger.info("Rebooting domR with id " + _domainRouterId.get());
        client = new HttpClient();
        method = new GetMethod(url);
        responseCode = client.executeMethod(method);
        s_logger.info("Reboot domain router response code: " + responseCode);
        if (responseCode == 200) {
            InputStream input = method.getResponseBodyAsStream();
            Element el = queryAsyncJobResult(server, input);
            s_logger.info("Domain router was rebooted successfully");
        } else {
            s_logger.error("Reboot domain routers failed with error code: " + responseCode + ". Following URL was sent: " + url);
            return responseCode;
        }
    }
    // -----------------------------
    // DELETE ACCOUNT
    // -----------------------------
    {
        url = server + "?command=deleteAccount&id=" + _accountId.get();
        client = new HttpClient();
        method = new GetMethod(url);
        responseCode = client.executeMethod(method);
        s_logger.info("delete account response code: " + responseCode);
        if (responseCode == 200) {
            InputStream input = method.getResponseBodyAsStream();
            Element el = queryAsyncJobResult(server, input);
            s_logger.info("Deleted account successfully");
        } else {
            s_logger.error("delete account failed with error code: " + responseCode + ". Following URL was sent: " + url);
            return responseCode;
        }
    }
    return responseCode;
}
Also used : InputStream(java.io.InputStream) HttpClient(org.apache.commons.httpclient.HttpClient) Element(org.w3c.dom.Element) GetMethod(org.apache.commons.httpclient.methods.GetMethod) HashMap(java.util.HashMap) Map(java.util.Map) 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