Search in sources :

Example 71 with HttpMethod

use of org.apache.commons.httpclient.HttpMethod in project cloudstack by apache.

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 72 with HttpMethod

use of org.apache.commons.httpclient.HttpMethod in project cloudstack by apache.

the class ApiCommand method sendCommand.

// Send api command to the server
public void sendCommand(HttpClient client, Connection conn) {
    if (TestCaseEngine.s_printUrl == true) {
        s_logger.info("url is " + this.command);
    }
    if (this.getCommandType() == CommandType.SCRIPT) {
        try {
            s_logger.info("Executing command " + this.command);
            Runtime rtime = Runtime.getRuntime();
            Process child = rtime.exec(this.command);
            Thread.sleep(10000);
            int retCode = child.waitFor();
            if (retCode != 0) {
                this.responseCode = retCode;
            } else {
                this.responseCode = 200;
            }
        } catch (Exception ex) {
            s_logger.error("Unable to execute a command " + this.command, ex);
        }
    } else if (this.getCommandType() == CommandType.MYSQL) {
        try {
            Statement stmt = conn.createStatement();
            this.result = stmt.executeQuery(this.command);
            this.responseCode = 200;
        } catch (Exception ex) {
            this.responseCode = 400;
            s_logger.error("Unable to execute mysql query " + this.command, ex);
        }
    } else {
        HttpMethod method = new GetMethod(this.command);
        try {
            this.responseCode = client.executeMethod(method);
            if (this.responseCode == 200) {
                InputStream is = method.getResponseBodyAsStream();
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(is);
                doc.getDocumentElement().normalize();
                if (!(this.isAsync)) {
                    this.responseBody = doc.getDocumentElement();
                } else {
                    // get async job result
                    Element jobTag = (Element) doc.getDocumentElement().getElementsByTagName("jobid").item(0);
                    String jobId = jobTag.getTextContent();
                    Element responseBodyAsyncEl = queryAsyncJobResult(jobId);
                    if (responseBodyAsyncEl == null) {
                        s_logger.error("Can't get a async result");
                    } else {
                        this.responseBody = responseBodyAsyncEl;
                        // get status of the job
                        Element jobStatusTag = (Element) responseBodyAsyncEl.getElementsByTagName("jobstatus").item(0);
                        String jobStatus = jobStatusTag.getTextContent();
                        if (!jobStatus.equals("1")) {
                            // Need to modify with different error codes for jobAsync
                            // results
                            // set fake response code by now
                            this.responseCode = 400;
                        }
                    }
                }
            }
            if (TestCaseEngine.s_printUrl == true) {
                s_logger.info("Response code is " + this.responseCode);
            }
        } catch (Exception ex) {
            s_logger.error("Command " + command + " failed with exception " + ex.getMessage());
        } finally {
            method.releaseConnection();
        }
    }
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Statement(java.sql.Statement) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) DocumentBuilder(javax.xml.parsers.DocumentBuilder) GetMethod(org.apache.commons.httpclient.methods.GetMethod) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 73 with HttpMethod

use of org.apache.commons.httpclient.HttpMethod in project cloudstack by apache.

the class PerformanceWithAPI method CreateForwardingRule.

private static int CreateForwardingRule(User myUser, String privateIp, String publicIp, String publicPort, String privatePort) throws IOException {
    String encodedPrivateIp = URLEncoder.encode("" + privateIp, "UTF-8");
    String encodedPublicIp = URLEncoder.encode("" + publicIp, "UTF-8");
    String encodedPrivatePort = URLEncoder.encode("" + privatePort, "UTF-8");
    String encodedPublicPort = URLEncoder.encode("" + publicPort, "UTF-8");
    String encodedApiKey = URLEncoder.encode(myUser.getApiKey(), "UTF-8");
    int responseCode = 500;
    String requestToSign = "apiKey=" + encodedApiKey + "&command=createOrUpdateIpForwardingRule&privateIp=" + encodedPrivateIp + "&privatePort=" + encodedPrivatePort + "&protocol=tcp&publicIp=" + encodedPublicIp + "&publicPort=" + encodedPublicPort;
    requestToSign = requestToSign.toLowerCase();
    s_logger.info("Request to sign is " + requestToSign);
    String signature = TestClientWithAPI.signRequest(requestToSign, myUser.getSecretKey());
    String encodedSignature = URLEncoder.encode(signature, "UTF-8");
    String url = myUser.getDeveloperServer() + "?command=createOrUpdateIpForwardingRule" + "&publicIp=" + encodedPublicIp + "&publicPort=" + encodedPublicPort + "&privateIp=" + encodedPrivateIp + "&privatePort=" + encodedPrivatePort + "&protocol=tcp&apiKey=" + encodedApiKey + "&signature=" + encodedSignature;
    s_logger.info("Trying to create IP forwarding rule: " + url);
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    responseCode = client.executeMethod(method);
    s_logger.info("create ip forwarding rule response code: " + responseCode);
    if (responseCode == 200) {
        s_logger.info("The rule is created successfully");
    } else if (responseCode == 500) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, String> errorInfo = TestClientWithAPI.getSingleValueFromXML(is, new String[] { "errorCode", "description" });
        s_logger.error("create ip forwarding rule (linux) test failed with errorCode: " + errorInfo.get("errorCode") + " and description: " + errorInfo.get("description"));
    } else {
        s_logger.error("internal error processing request: " + method.getStatusText());
    }
    return responseCode;
}
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 74 with HttpMethod

use of org.apache.commons.httpclient.HttpMethod in project cloudstack by apache.

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)

Example 75 with HttpMethod

use of org.apache.commons.httpclient.HttpMethod in project cloudstack by apache.

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)

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