VMware vSphere Web Services SDK编程指南(七)- 7.4 PropertyCollector 示例 (RetrievePropertiesEx)

来源:互联网 发布:nb iot 编程 编辑:程序博客网 时间:2024/06/05 02:31

7.4 PropertyCollector 示例 (RetrievePropertiesEx)


本节的示例程序是用 Java 写的一个简单的 PropertyCollector 示例。
示例使用 ContainerView 有效的访问清单和使用一个包含一个 ObjectSpec, 一个 TraversalSpec 和一个 PropertySpec 的 PropertyFilterSpec 对象。
这个程序执行如下任务

■ 接受 vSphere 服务器名( DNS 名称或 IP 地址)、用户名和密码的命令行参数

■ 连接 vSphere 服务器

■ 使用 ContainerView 创建清单的一个子集,这个子集只包含虚拟机

■ 使用 RetrievePropertiesEx 方法进行一次单个检索操作

■ 收集清单中所有虚拟机的名称,并使用标准输出流打印出这些虚拟机名称

下面步骤使用的代码片段取自于 Simple PropertyCollector Example (Java) 程序,完整的示例包含服务器连接代码,这里的步骤只描述了使用 PropertyCollector 时需要做的工作。

使用 PropertyCollector 进行一次检索操作

1 获取到 ViewManager 和 PropertyCollector 的引用;
在示例中,sContent 对 ServiceContent 数据对象是可用的,sContent 提供了到 vSphere 服务检索托管对象引用的方法。

ManagedObjectReference viewMgrRef = sContent.getViewManager();ManagedObjectReference propColl = sContent.getPropertyCollector();

2 为虚拟机创建一个容器视图;
对 VimPortType 对象来说,方法是变量,VimPortType 定义了与 vSphere API 方法相对应的Java方法。createContainerView 参数container (清单根目录,由方法 sContent.getRootFolder 返回)和 type (“Virtual Machine”) 指引 ViewManager 从 root folder 开始选择虚拟机,递归参数值的 ture 值将选择范围扩展到根文件夹之外,这样 ViewManager 将沿着子目录路径,将虚拟机添加到视图中。容器视图提供了在清单里面的所有虚拟机的引用。

List<String> vmList = new ArrayList<String>();vmList.add("VirtualMachine");ManagedObjectReference cViewRef = methods.createContainerView(viewMgrRef,sContent.getRootFolder(),vmList,true );

3 创建一个对象规范来定义清单检索的起始点;
ObjectSpec.obj 属性确定起始对象(container 视图),这个实例只收集虚拟机数据,因此 skip 属性设置为 true ,在收集时忽略 container 视图本身。

ObjectSpec oSpec = new ObjectSpec();oSpec.setObj(cViewRef);oSpec.setSkip(true);

4 创建一个遍历规范,以确定收集的路径;
TraversalSpec 属性 type 和 path 确定了遍历路径,TraversalSpec.type 确定了对象类型,TraversalSpec.path 确定了在 type 对象中的一个属性。
PropertyCollector 使用 path 对象来选择额外的对象。
该示例使用单个 TraversalSpec 来遍历容器视图中可用的虚拟机列表。
下面的代码片段指定了 TraversalSpec.type 属性确定的 ContainerView 对象,及 TraversalSpec.path 属性确定的在 ContainerView 对象中的 视图属性。这里的 skip 属性设置为 false,因此 PropertyCollector 会从 path 对象收集数据(在容器视图中的虚拟机)。

TraversalSpec tSpec = new TraversalSpec();tSpec.setName("traverseEntities");tSpec.setPath("view");tSpec.setSkip(false);tSpec.setType("ContainerView");

5 添加 TraversalSpec 到 ObjectSpec.selectSet 数组;

oSpec.getSelectSet().add(tSpec);

6 确定要检索的属性;
该示例程序创建一个 PropertySpec 数据对象指定要收集的属性,type 设置为 VirtualMachine 用于匹配容器视图中的对象选择,pathSet 属性确定一个或多个在 type 对象中的属性。
该示例指定了 VirtualMachine.name 属性。

PropertySpec pSpec = new PropertySpec();pSpec.setType("VirtualMachine");pSpec.getPathSet().add("name");

7 添加对象和属性规范到属性过滤器规范(specification)中;
PropertyFilterSpec 规范必须至少有一个 ObjectSpec 和一个 PropertySpec.

PropertyFilterSpec fSpec = new PropertyFilterSpec();fSpec.getObjectSet().add(oSpec);fSpec.getPropSet().add(pSpec);

8 创建一个过滤器列表并将过滤规范添加进去;

List<PropertyFilterSpec> fSpecList = new ArrayList<PropertyFilterSpec>();fSpecList.add(fSpec);

9 检索数据;
要调用一个单属性收集操作,调用 RetrievePropertiesEx 方法,该示例应用程序将设置的 PropertyFilterSpec 和一个空的 options 结构传递给该方法, RetrieveOptions.maxObjects 默认没有设置指定能够返回的最大对象数量。
PropertyCollector 可以设置一个最大值,如果收集的对象数比最大值大,PropertyCollector 在 RetrieveResult 数据对象中返回一个令牌值,这个令牌被用于 ContinueRetrievePropertiesEx API 方法检索剩余的其他属性。

RetrieveOptions ro = new RetrieveOptions();RetrieveResult props = methods.retrievePropertiesEx(propColl,fSpecList,ro);

10 打印虚拟机名称
下面的代码片段遍历在 RetrieveResult 中返回的 ObjectContent 对象列表,对每个对象(ObjectContent),内循环打印出 name-value 对。

if (props != null) {    for (ObjectContent oc : props.getObjects()) {        String vmName = null;        String path = null;        List<DynamicProperty> dps = oc.getPropSet();        if (dps != null) {            for (DynamicProperty dp : dps) {                vmName = (String) dp.getVal();                path = dp.getName();                System.out.println(path + " = " + vmName);            }        }    }}

下图显示了示例 (简单 PropertyCollector 示例) 中用到的对象,该图表示直接或间接地确认清单元素的属性,并没有显示不同对象的所有属性。

属性过滤器规范

这里写图片描述

示例:简单 PropertyCollector 示例(Java)

import com.vmware.vim25.*;import java.util.*;import javax.net.ssl.HostnameVerifier;import javax.net.ssl.HttpsURLConnection;import javax.net.ssl.SSLSession;import javax.xml.ws.BindingProvider;import javax.xml.ws.soap.SOAPFaultException;// PropertyCollector example// command line input: server name, user name, passwordpublic class PCollector {    private static void collectProperties(VimPortType methods,            ServiceContent sContent) throws Exception {        // Get references to the ViewManager and PropertyCollector        ManagedObjectReference viewMgrRef = sContent.getViewManager();        ManagedObjectReference propColl = sContent.getPropertyCollector();        // use a container view for virtual machines to define the traversal        // - invoke the VimPortType method createContainerView (corresponds        // to the ViewManager method) - pass the ViewManager MOR and        // the other parameters required for the method invocation        // - createContainerView takes a string[] for the type parameter;        // declare an arraylist and add the type string to it        List<String> vmList = new ArrayList<String>();        vmList.add("VirtualMachine");        ManagedObjectReference cViewRef = methods.createContainerView(                viewMgrRef, sContent.getRootFolder(), vmList, true);        // create an object spec to define the beginning of the traversal;        // container view is the root object for this traversal        ObjectSpec oSpec = new ObjectSpec();        oSpec.setObj(cViewRef);        oSpec.setSkip(true);        // create a traversal spec to select all objects in the view        TraversalSpec tSpec = new TraversalSpec();        tSpec.setName("traverseEntities");        tSpec.setPath("view");        tSpec.setSkip(false);        tSpec.setType("ContainerView");        // add the traversal spec to the object spec;        // the accessor method (getSelectSet) returns a reference        // to the mapped XML representation of the list; using this        // reference to add the spec will update the list        oSpec.getSelectSet().add(tSpec);        // specify the property for retrieval (virtual machine name)        PropertySpec pSpec = new PropertySpec();        pSpec.setType("VirtualMachine");        pSpec.getPathSet().add("name");        // create a PropertyFilterSpec and add the object and        // property specs to it; use the getter method to reference        // the mapped XML representation of the lists and add the specs        // directly to the list        PropertyFilterSpec fSpec = new PropertyFilterSpec();        fSpec.getObjectSet().add(oSpec);        fSpec.getPropSet().add(pSpec);        // Create a list for the filters and add the spec to it        List<PropertyFilterSpec> fSpecList = new ArrayList<PropertyFilterSpec>();        fSpecList.add(fSpec);        // get the data from the server        RetrieveOptions ro = new RetrieveOptions();        RetrieveResult props = methods.retrievePropertiesEx(propColl,                fSpecList, ro);        // go through the returned list and print out the data        if (props != null) {            for (ObjectContent oc : props.getObjects()) {                String vmName = null;                String path = null;                List<DynamicProperty> dps = oc.getPropSet();                if (dps != null) {                    for (DynamicProperty dp : dps) {                        vmName = (String) dp.getVal();                        path = dp.getName();                        System.out.println(path + " = " + vmName);                    }                }            }        }    }// end collectProperties()    // Authentication is handled by using a TrustManager and supplying    // a host name verifier method. (The host name verifier is declared    // in the main function.)    //    // For the purposes of this example, this TrustManager implementation    // will accept all certificates. This is only appropriate for    // a development environment. Production code should implement certificate    // support.    private static class TrustAllTrustManager implements            javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {        public java.security.cert.X509Certificate[] getAcceptedIssuers() {            return null;        }        public boolean isServerTrusted(                java.security.cert.X509Certificate[] certs) {            return true;        }        public boolean isClientTrusted(                java.security.cert.X509Certificate[] certs) {            return true;        }        public void checkServerTrusted(                java.security.cert.X509Certificate[] certs, String authType)                throws java.security.cert.CertificateException {            return;        }        public void checkClientTrusted(                java.security.cert.X509Certificate[] certs, String authType)                throws java.security.cert.CertificateException {            return;        }    }    public static void main(String[] args) throws Exception {        // arglist variables        String serverName = args[0];        String userName = args[1];        String password = args[2];        String url = "https://" + serverName + "/sdk/vimService";        // Variables of the following types for access to the API methods        // and to the vSphere inventory.        // -- ManagedObjectReference for the ServiceInstance on the Server        // -- VimService for access to the vSphere Web service        // -- VimPortType for access to methods        // -- ServiceContent for access to managed object services        ManagedObjectReference SVC_INST_REF = new ManagedObjectReference();        VimService vimService;        VimPortType vimPort;        ServiceContent serviceContent;        // Declare a host name verifier that will automatically enable        // the connection. The host name verifier is invoked during        // the SSL handshake.        HostnameVerifier hv = new HostnameVerifier() {            public boolean verify(String urlHostName, SSLSession session) {                return true;            }        };        // Create the trust manager.        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];        javax.net.ssl.TrustManager tm = new TrustAllTrustManager();        trustAllCerts[0] = tm;        // Create the SSL context        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext                .getInstance("SSL");        // Create the session context        javax.net.ssl.SSLSessionContext sslsc = sc.getServerSessionContext();        // Initialize the contexts; the session context takes the trust manager.        sslsc.setSessionTimeout(0);        sc.init(null, trustAllCerts, null);        // Use the default socket factory to create the socket for the secure        // connection        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc                .getSocketFactory());        // Set the default host name verifier to enable the connection.        HttpsURLConnection.setDefaultHostnameVerifier(hv);        // Set up the manufactured managed object reference for the        // ServiceInstance        SVC_INST_REF.setType("ServiceInstance");        SVC_INST_REF.setValue("ServiceInstance");        // Create a VimService object to obtain a VimPort binding provider.        // The BindingProvider provides access to the protocol fields        // in request/response messages. Retrieve the request context        // which will be used for processing message requests.        vimService = new VimService();        vimPort = vimService.getVimPort();        Map<String, Object> ctxt = ((BindingProvider) vimPort)                .getRequestContext();        // Store the Server URL in the request context and specify true        // to maintain the connection between the client and server.        // The client API will include the Server's HTTP cookie in its        // requests to maintain the session. If you do not set this to true,        // the Server will start a new session with each request.        ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url);        ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);        // Retrieve the ServiceContent object and login        serviceContent = vimPort.retrieveServiceContent(SVC_INST_REF);        vimPort.login(serviceContent.getSessionManager(), userName, password,                null);        // retrieve data        collectProperties(vimPort, serviceContent);        // close the connection        vimPort.logout(serviceContent.getSessionManager());    }}

原文:
VMware vSphere 6.5 Documentation Center:PropertyCollector Example (RetrievePropertiesEx)

阅读全文
0 0
原创粉丝点击