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

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


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

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
CloudStack是一个开源的云计算管理平台,可以让用户快速搭建私有云、公共云和混合云等多种云环境。在Java中,通过CloudStack提供的API可以方便地查询和管理云资源。 要查询CloudStack中的列表,首先需要创建一个与CloudStack通信的CloudStack客户端对象,在Java中可以使用CloudStackClient类实现。然后,使用该对象调用相应的API方法来查询列表。 常见的查询列表的API包括: 1. listVirtualMachines:查询虚拟机列表; 2. listNetworks:查询网络列表; 3. listVolumes:查询存储卷列表; 4. listTemplates:查询模板列表; 5. listSnapshots:查询快照列表。 例如,要查询虚拟机列表,可以使用如下的代码片段: ``` CloudStackClient client = new CloudStackClient(...); // 创建与CloudStack通信的客户端对象 ListVirtualMachinesCmd cmd = new ListVirtualMachinesCmd(); ListVirtualMachinesResponse response = client.execute(cmd); // 调用查询虚拟机列表的API方法 List<VirtualMachine> virtualMachines = response.getVirtualMachines(); // 获取查询结果列表 for(VirtualMachine vm : virtualMachines) { // 处理每个虚拟机对象 } ``` 类似地,可以根据需要调用其他的API方法来查询不同类型的资源列表,并通过获取的结果列表进行后续的处理和操作。 总之,通过CloudStack提供的Java API,我们可以方便地查询CloudStack中的各种资源列表,并在应用程序中进一步处理和操作这些资源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值