CloudStack4.4开发,API调用java实例

来源:互联网 发布:极域电子教室软件 编辑:程序博客网 时间:2024/06/07 07:19

CloudStack API开发没有java例子很是苦恼,原站点文档只有python,所以研究了一把源码自己写了一个java版本开发的例子:


代码如下:

import java.io.IOException;
import java.io.InputStream;

import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.DocumentBuilder;

import org.apache.commons.codec.binary.Base64;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;

import org.apache.commons.httpclient.methods.GetMethod;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;


import javax.xml.parsers.DocumentBuilderFactory;

public class test1 {
    private static DocumentBuilderFactory factory = DocumentBuilderFactory
            .newInstance();

    /**
     * @param args
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws IOException
     * @throws HttpException
     */
    public static void main(String[] args) throws InvalidKeyException,
            NoSuchAlgorithmException, HttpException, IOException {
        // TODO Auto-generated method stub

        String developerServer = "http://10.11.1.212:8080/client/api";
        String ApiKey = "7hyD4QRRcNkC59ARxCRCO3cFoowcGmBDY5F23qmWwxYdQT22plI6GY7R1EDBWdiRj4-ktSE00HeDlk38EXZszw";
        String s_secretKey = "bR493wms46oujIJxKST6qkTH069pFdnzeQYFGgKqLsaotU5Dgugolnbx48Dq3NJSjYu06qXmINYVBkC0K-b2jQ";
        String encodedApiKey = URLEncoder.encode(ApiKey, "UTF-8");
        String encodedPublicIpId = "", encodedVmId = "";
        String urlold = "apikey=" + encodedApiKey + "&command=listUsers";
        urlold = urlold.toLowerCase();
        String signature = signRequest(urlold, s_secretKey);
        String encodedSignature = URLEncoder.encode(signature, "UTF-8");

        String url = developerServer + "?command=listUsers&apikey="
                + encodedApiKey + "&signature=" + encodedSignature;
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(url);
        System.out.println(url);
        int responseCode = client.executeMethod(method);

        // s_logger.info("url is " + url);
        // s_logger.info("list ip addresses for user " + userId +
        // " response code: " + responseCode);
        if (responseCode == 200) {
            InputStream is = method.getResponseBodyAsStream();
            Map<String, String> success = getSingleValueFromXML(is,
                    new String[] { "accountid" });
            System.out.print(success.get("accountid"));
            // s_logger.info("Enable Static NAT..success? " +
            // success.get("success"));
        } else {
            // s_logger.error("Enable Static NAT failed with error code: " +
            // responseCode + ". Following URL was sent: " + url);
            // return responseCode;
        }

    }

    public static String signRequest(String request, String secretkey)
            throws NoSuchAlgorithmException, InvalidKeyException {
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec keySpec = new SecretKeySpec(secretkey.getBytes(),
                "HmacSHA1");
        mac.init(keySpec);
        mac.update(request.getBytes());
        byte[] encryptedBytes = mac.doFinal();
        // System.out.println("HmacSHA1 hash: " + encryptedBytes);
        return new String(Base64.encodeBase64(encryptedBytes));
    }

    public static Map<String, String> getSingleValueFromXML(InputStream is,
            String[] tagNames) {
        Map<String, String> returnValues = new HashMap<String, String>();
        try {
            DocumentBuilder docBuilder = factory.newDocumentBuilder();
            Document doc = docBuilder.parse(is);
            Element rootElement = doc.getDocumentElement();

            for (int i = 0; i < tagNames.length; i++) {
                NodeList targetNodes = rootElement
                        .getElementsByTagName(tagNames[i]);
                if (targetNodes.getLength() <= 0) {
                    // s_logger.error("no " + tagNames[i] +
                    // " tag in XML response...returning null");
                } else {
                    returnValues.put(tagNames[i], targetNodes.item(0)
                            .getTextContent());
                }
            }
        } catch (Exception ex) {
            // s_logger.error("error processing XML", ex);
        }
        return returnValues;
    }
}

=================================================

控制台返回结果:

http://10.11.1.212:8080/client/api?command=listUsers&apikey=7hyD4QRRcNkC59ARxCRCO3cFoowcGmBDY5F23qmWwxYdQT22plI6GY7R1EDBWdiRj4-ktSE00HeDlk38EXZszw&signature=YKesN%2FiaEkkS36iue6RSE0ZYvVU%3D
0001dcae-1c4e-11e4-9ef8-000c29cff73b


==================================

在浏览器中将url贴上去,也可以返回整个XML:


<listusersresponse cloud-stack-version="4.4.0"><count>1</count><user><id>0001e898-1c4e-11e4-9ef8-000c29cff73b</id><username>admin</username><firstname>admin</firstname><lastname>cloud</lastname><created>2014-08-05T19:10:06+0800</created><state>enabled</state><account>admin</account><accounttype>1</accounttype><domainid>c4bf5d1a-1c4d-11e4-9ef8-000c29cff73b</domainid><domain>ROOT</domain><apikey>7hyD4QRRcNkC59ARxCRCO3cFoowcGmBDY5F23qmWwxYdQT22plI6GY7R1EDBWdiRj4-ktSE00HeDlk38EXZszw</apikey><secretkey>bR493wms46oujIJxKST6qkTH069pFdnzeQYFGgKqLsaotU5Dgugolnbx48Dq3NJSjYu06qXmINYVBkC0K-b2jQ</secretkey><accountid>0001dcae-1c4e-11e4-9ef8-000c29cff73b</accountid><iscallerchilddomain>false</iscallerchilddomain><isdefault>true</isdefault></user></listusersresponse>

=======================================================================================

java引用了几个apache的公用类包:

commons-codec-1.3.jar

commons-httpclient-3.1.jar

commons-logging.jar

jdk版本为1.7

=======================================================================================

官网API参考地址:

http://cloudstack.apache.org/docs/api/


=======================================================================================

测试另外一个API,listNetworks,API说明在此:http://cloudstack.apache.org/docs/api/apidocs-4.4/root_admin/listNetworks.html

修改main()方法:


    public static void main(String[] args) throws InvalidKeyException,
            NoSuchAlgorithmException, HttpException, IOException {
        // TODO Auto-generated method stub

        String developerServer = "http://10.11.1.212:8080/client/api";
        String ApiKey = "7hyD4QRRcNkC59ARxCRCO3cFoowcGmBDY5F23qmWwxYdQT22plI6GY7R1EDBWdiRj4-ktSE00HeDlk38EXZszw";
        String s_secretKey = "bR493wms46oujIJxKST6qkTH069pFdnzeQYFGgKqLsaotU5Dgugolnbx48Dq3NJSjYu06qXmINYVBkC0K-b2jQ";
        String encodedApiKey = URLEncoder.encode(ApiKey, "UTF-8");
        String encodedPublicIpId = "", encodedVmId = "";
        //String urlold = "apikey=" + encodedApiKey + "&command=listUsers";
        String urlold = "apikey=" + encodedApiKey + "&command=listNetworks";
        urlold = urlold.toLowerCase();
        String signature = signRequest(urlold, s_secretKey);
        String encodedSignature = URLEncoder.encode(signature, "UTF-8");

        //String url = developerServer + "?command=listUsers&apikey="
        String url = developerServer + "?command=listNetworks&apikey="
                + encodedApiKey + "&signature=" + encodedSignature;
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(url);
        System.out.println(url);
        int responseCode = client.executeMethod(method);

        // s_logger.info("url is " + url);
        // s_logger.info("list ip addresses for user " + userId +
        // " response code: " + responseCode);
        if (responseCode == 200) {
            InputStream is = method.getResponseBodyAsStream();
            Map<String, String> success = getSingleValueFromXML(is,
                    new String[] { "accountid","id","account","name" });
            System.out.print(success.get("id")+success.get("name")+success.get("account"));
            // s_logger.info("Enable Static NAT..success? " +
            // success.get("success"));
        } else {
            // s_logger.error("Enable Static NAT failed with error code: " +
            // responseCode + ". Following URL was sent: " + url);
            // return responseCode;
        }

    }


返回结果:

http://10.11.1.212:8080/client/api?command=listNetworks&apikey=7hyD4QRRcNkC59ARxCRCO3cFoowcGmBDY5F23qmWwxYdQT22plI6GY7R1EDBWdiRj4-ktSE00HeDlk38EXZszw&signature=NPHxoT08ArbHJSLKBCnCjUA7MOQ%3D
a7ec78ae-0dd6-42f7-8015-cdb2ca14ec66defaultGuestNetworknull


==============================================================

1 0