Search in sources :

Example 21 with HttpMethod

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

the class StressTestDirectAttach method executeStop.

private static int executeStop(String server, String developerServer, String username) throws HttpException, IOException {
    // test steps:
    // - get userId for the given username
    // - list virtual machines for the user
    // - stop all virtual machines
    // - get ip addresses for the user
    // - release ip addresses
    // -----------------------------
    // GET USER
    // -----------------------------
    String userId = _userId.get().toString();
    String encodedUserId = URLEncoder.encode(userId, "UTF-8");
    String url = server + "?command=listUsers&id=" + encodedUserId;
    s_logger.info("Stopping resources for user: " + username);
    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> userIdValues = getSingleValueFromXML(is, new String[] { "id" });
        String userIdStr = userIdValues.get("id");
        if (userIdStr != null) {
            userId = userIdStr;
            if (userId == null) {
                s_logger.error("get user failed to retrieve a valid user id, aborting depolyment 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;
    }
    {
        // ----------------------------------
        // LIST VIRTUAL MACHINES
        // ----------------------------------
        String encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8");
        String requestToSign = "apikey=" + encodedApiKey + "&command=listVirtualMachines";
        requestToSign = requestToSign.toLowerCase();
        String signature = signRequest(requestToSign, _secretKey.get());
        String encodedSignature = URLEncoder.encode(signature, "UTF-8");
        url = developerServer + "?command=listVirtualMachines&apikey=" + encodedApiKey + "&signature=" + encodedSignature;
        s_logger.info("Listing all virtual machines for the user with url " + url);
        String[] vmIds = null;
        client = new HttpClient();
        method = new GetMethod(url);
        responseCode = client.executeMethod(method);
        s_logger.info("list virtual machines response code: " + responseCode);
        if (responseCode == 200) {
            InputStream is = method.getResponseBodyAsStream();
            Map<String, List<String>> vmIdValues = getMultipleValuesFromXML(is, new String[] { "id" });
            if (vmIdValues.containsKey("id")) {
                List<String> vmIdList = vmIdValues.get("id");
                if (vmIdList != null) {
                    vmIds = new String[vmIdList.size()];
                    vmIdList.toArray(vmIds);
                    String vmIdLogStr = "";
                    if ((vmIds != null) && (vmIds.length > 0)) {
                        vmIdLogStr = vmIds[0];
                        for (int i = 1; i < vmIds.length; i++) {
                            vmIdLogStr = vmIdLogStr + "," + vmIds[i];
                        }
                    }
                    s_logger.info("got virtual machine ids: " + vmIdLogStr);
                }
            }
        } else {
            s_logger.error("list virtual machines test failed with error code: " + responseCode + ". Following URL was sent: " + url);
            return responseCode;
        }
        // ----------------------------------
        if (vmIds != null) {
            for (String vmId : vmIds) {
                requestToSign = "apikey=" + encodedApiKey + "&command=stopVirtualMachine&id=" + vmId;
                requestToSign = requestToSign.toLowerCase();
                signature = signRequest(requestToSign, _secretKey.get());
                encodedSignature = URLEncoder.encode(signature, "UTF-8");
                url = developerServer + "?command=stopVirtualMachine&id=" + vmId + "&apikey=" + encodedApiKey + "&signature=" + encodedSignature;
                client = new HttpClient();
                method = new GetMethod(url);
                responseCode = client.executeMethod(method);
                s_logger.info("StopVirtualMachine" + " [" + vmId + "] 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("StopVirtualMachine..success? " + success.get("success"));
                } else {
                    s_logger.error("Stop virtual machine test failed with error code: " + responseCode + ". Following URL was sent: " + url);
                    return responseCode;
                }
            }
        }
    //			{
    //				url = server + "?command=deleteUser&id=" + userId;
    //				client = new HttpClient();
    //				method = new GetMethod(url);
    //				responseCode = client.executeMethod(method);
    //				s_logger.info("delete user response code: " + responseCode);
    //				if (responseCode == 200) {
    //					InputStream input = method.getResponseBodyAsStream();
    //					Element el = queryAsyncJobResult(server, input);
    //					s_logger
    //							.info("Deleted user successfully");
    //				} else  {
    //					s_logger.error("delete user failed with error code: " + responseCode + ". Following URL was sent: " + url);
    //					return responseCode;
    //				} 
    //			}
    }
    _linuxIP.set("");
    _linuxVmId.set("");
    _linuxPassword.set("");
    _windowsIP.set("");
    _secretKey.set("");
    _apiKey.set("");
    _userId.set(Long.parseLong("0"));
    _account.set("");
    _domainRouterId.set("");
    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) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 22 with HttpMethod

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

the class StressTestDirectAttach 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 23 with HttpMethod

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

the class StressTestDirectAttach 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;
        }
    }
    // -----------------------------
    // Execute reboot/stop/start commands for the VMs before deleting the account - made to exercise xen
    // -----------------------------
    //Reboot centos VM
    String encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8");
    String requestToSign = "apikey=" + encodedApiKey + "&command=rebootVirtualMachine&id=" + _linuxVmId.get();
    requestToSign = requestToSign.toLowerCase();
    String signature = signRequest(requestToSign, _secretKey.get());
    String encodedSignature = URLEncoder.encode(signature, "UTF-8");
    url = developerServer + "?command=rebootVirtualMachine&id=" + _linuxVmId.get() + "&apikey=" + encodedApiKey + "&signature=" + encodedSignature;
    client = new HttpClient();
    method = new GetMethod(url);
    responseCode = client.executeMethod(method);
    s_logger.info("Reboot 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("VM was rebooted with the status: " + success.get("success"));
    } else {
        s_logger.error(" 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 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("VM was stopped with the status: " + success.get("success"));
    } else {
        s_logger.error("Stop VM test failed with error code: " + responseCode + ". Following URL was sent: " + url);
        return responseCode;
    }
    //Start centos VM
    requestToSign = "apikey=" + encodedApiKey + "&command=startVirtualMachine&id=" + _linuxVmId.get();
    requestToSign = requestToSign.toLowerCase();
    signature = signRequest(requestToSign, _secretKey.get());
    encodedSignature = URLEncoder.encode(signature, "UTF-8");
    url = developerServer + "?command=startVirtualMachine&id=" + _linuxVmId.get() + "&apikey=" + encodedApiKey + "&signature=" + encodedSignature;
    client = new HttpClient();
    method = new GetMethod(url);
    responseCode = client.executeMethod(method);
    s_logger.info("Start VM response code: " + responseCode);
    if (responseCode == 200) {
        InputStream input = method.getResponseBodyAsStream();
        Element el = queryAsyncJobResult(server, input);
        Map<String, String> success = getSingleValueFromXML(el, new String[] { "id" });
        if (success.get("id") == null) {
            s_logger.info("Start linux vm response code: 401");
            return 401;
        } else {
            s_logger.info("Start vm response code: " + responseCode);
        }
        s_logger.info("VM was started with the status: " + success.get("success"));
    } else {
        s_logger.error("Start VM test failed with error code: " + responseCode + ". Following URL was sent: " + url);
        return responseCode;
    }
    ////		// -----------------------------
    ////		// DISABLE USER
    ////		// -----------------------------
    //		{
    //			url = server + "?command=disableUser&id=" + userId;
    //			client = new HttpClient();
    //			method = new GetMethod(url);
    //			responseCode = client.executeMethod(method);
    //			s_logger.info("disable user response code: " + responseCode);
    //			if (responseCode == 200) {
    //				InputStream input = method.getResponseBodyAsStream();
    //				Element el = queryAsyncJobResult(server, input);
    //				s_logger
    //						.info("Disabled user successfully");
    //			} else  {
    //				s_logger.error("disable user failed with error code: " + responseCode + ". Following URL was sent: " + url);
    //				return responseCode;
    //			} 
    //		}
    // -----------------------------
    // DELETE USER
    // -----------------------------
    {
        url = server + "?command=deleteUser&id=" + userId;
        client = new HttpClient();
        method = new GetMethod(url);
        responseCode = client.executeMethod(method);
        s_logger.info("delete user response code: " + responseCode);
        if (responseCode == 200) {
            InputStream input = method.getResponseBodyAsStream();
            Element el = queryAsyncJobResult(server, input);
            s_logger.info("Deleted user successfully");
        } else {
            s_logger.error("delete user 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)

Example 24 with HttpMethod

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

the class User method launchUser.

public void launchUser() throws IOException {
    String encodedUsername = URLEncoder.encode(this.getUserName(), "UTF-8");
    this.encryptedPassword = TestClientWithAPI.createMD5Password(this.getPassword());
    String encodedPassword = URLEncoder.encode(this.encryptedPassword, "UTF-8");
    String url = this.server + "?command=createUser&username=" + encodedUsername + "&password=" + encodedPassword + "&firstname=Test&lastname=Test&email=alena@vmops.com&domainId=1";
    String userIdStr = 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> userIdValues = TestClientWithAPI.getSingleValueFromXML(is, new String[] { "id" });
        userIdStr = userIdValues.get("id");
        if ((userIdStr != null) && (Long.parseLong(userIdStr) != -1)) {
            this.setUserId(userIdStr);
        }
    }
}
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 25 with HttpMethod

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

the class User method retrievePublicIp.

public void retrievePublicIp(long zoneId) throws IOException {
    String encodedApiKey = URLEncoder.encode(this.apiKey, "UTF-8");
    String encodedZoneId = URLEncoder.encode("" + zoneId, "UTF-8");
    String requestToSign = "apiKey=" + encodedApiKey + "&command=associateIpAddress" + "&zoneId=" + encodedZoneId;
    requestToSign = requestToSign.toLowerCase();
    String signature = TestClientWithAPI.signRequest(requestToSign, this.secretKey);
    String encodedSignature = URLEncoder.encode(signature, "UTF-8");
    String url = this.developerServer + "?command=associateIpAddress" + "&apiKey=" + encodedApiKey + "&zoneId=" + encodedZoneId + "&signature=" + encodedSignature;
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    int responseCode = client.executeMethod(method);
    if (responseCode == 200) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, String> values = TestClientWithAPI.getSingleValueFromXML(is, new String[] { "ipaddress" });
        this.getPublicIp().add(values.get("ipaddress"));
        s_logger.info("Ip address is " + 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("associate ip 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)

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