A-A+

VMware-vSphere-SDK-5.1.0+spring mvc二次开发实例

2014年09月24日 Spring mvc 暂无评论 阅读 1,573 views 次

一、环境搭建

1、安装jdk,这里我用jdk1.7.0_45,官网下载地址

http://www.oracle.com/technetwork/java/javase/downloads/index.html

2、下载VMware-vSphere-SDK-5.1.0

https://www.vmware.com/support/developer/vc-sdk/

二、建立相关目录

C:\Java\ 放置下载的javase

C:\devprojects 将VMware-vSphere-SDK-5.1.0解压后的sdk目录整个复制进来

C:\VMware-Certs\ 用于存放密钥,将服务器端生成的证书导入本机rui.crt,ESXi的证书在/etc/vmware/ssl/rui.crt;Vcenter的证书在C:/Documents and Settings/All Users/Application Data/VMware/VMware VitualCenter/SSL/rui.crt

三、配置环境变量

JAVA_HOME=C:\Java\jdk1.7.0_45

JAVAHOME=C:\Java\jdk1.7.0_45

jdk不要放在中间带有空格的目录下,否则在执行命令的时候会报错

SDKHOME=C:\devprojects

VMKEYSTORE=C:\VMware-Certs\vmware.keystore 密钥目录,很重要,必须验证正确才能连接到服务器

WEBHOME=C:\devprojects\vsphere-ws\java\Axis\lib\wbem.jar

WS_SDK_HOME=C:\devprojects\SDK\vsphere-ws

四、生成证书

切换到C:/VMware-Certs目录下,使用jdk的keytool工具导入证书:keytool -import -file <certificate-filename> -alias <server-name> -keystore vmware.keystore,其中certificate-filename为rui.crt,service-name可以为服务器的机器名或IP地址,运行成功后会在C:/VMware-Certs目录下生成vmware.keystore文件

五、重新编译

切换到C:\devprojects\SDK\vsphere-ws\java\JAXWS\,运行build.bat

运行结束出现

Generating stubs from wsdl
 
Compiling stubs.
...
Done
六、验证环境搭建是否成功
打开CMD,切换到C:\devprojects\SDK\vsphere-ws\java\JAXWS\run.bat com.vmware.general.SimpleClient --urlhttps://yourFQDNservername/sdk --username  username --password password,如下输出表示配置SDK成功
sdk
七、打开eclipse新建动态网页工程

打开VMware-vSphere-SDK-5.1.0-774886\SDK\vsphere-ws\java\JAXWS\samples

将目录中的整个com文件夹拖进src中,如图所示

ml

本工程使用的是spring mvc 框架,框架的搭建这里就不详细讲解了,因为功能的运行与框架的关系不大,即使是java工程也能够运行。

改造com/vmware/general/GetHostName.java,创建test方法查询主机信息,为方便大家理解,代码中把源代码的调用示例注释掉了,大家可以对比我写的方法和旧方法的区别


package com.vmware.general;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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;

import com.vmware.vim25.DynamicProperty;
import com.vmware.vim25.InvalidLocaleFaultMsg;
import com.vmware.vim25.InvalidLoginFaultMsg;
import com.vmware.vim25.InvalidPropertyFaultMsg;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.ObjectContent;
import com.vmware.vim25.ObjectSpec;
import com.vmware.vim25.PropertyFilterSpec;
import com.vmware.vim25.PropertySpec;
import com.vmware.vim25.RuntimeFaultFaultMsg;
import com.vmware.vim25.ServiceContent;
import com.vmware.vim25.TraversalSpec;
import com.vmware.vim25.VimPortType;
import com.vmware.vim25.VimService;

/**
 * <pre>
 * GetHostName
 *
 * This sample gets the hostname and additional details of the ESX Servers
 * in the inventory
 *
 * <b>Parameters:</b>
 * url          [required] : url of the web service
 * username     [required] : username for the authentication
 * password     [required] : password for the authentication
 *
 * <b>Command Line:</b>
 * run.bat com.vmware.general.GetHostName
 * --url [webservicesurl] --username [username] --password [password]
 * </pre>
 */

public class GetHostName {

    private static class TrustAllTrustManager implements
            javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }

        @Override
        public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }
    }

    private static final ManagedObjectReference SVC_INST_REF = new ManagedObjectReference();
    private static final String SVC_INST_NAME = "ServiceInstance";
    private static VimService vimService;
    private static VimPortType vimPort;
    private static ServiceContent serviceContent;

    private static String url;
    private static String userName;
    private static String password;
    private static boolean help = false;
    private static boolean isConnected = false;
    private static final List<String> hostSystemAttributesArr = new ArrayList<String>();

    private static void trustAllHttpsCertificates() {
        try {
            // Create a trust manager that does not validate certificate chains
            javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
            javax.net.ssl.TrustManager tm = new TrustAllTrustManager();
            trustAllCerts[0] = tm;
            javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
                    .getInstance("SSL");
            javax.net.ssl.SSLSessionContext sslsc = sc
                    .getServerSessionContext();
            sslsc.setSessionTimeout(0);
            sc.init(null, trustAllCerts, null);
            javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc
                    .getSocketFactory());
        } catch (KeyManagementException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException(e);
        }
    }

    // get common parameters
    private static void getConnectionParameters(String[] args)
            throws IllegalArgumentException {
        int ai = 0;
        String param = "";
        String val = "";
        while (ai < args.length) {
            param = args[ai].trim();
            if (ai + 1 < args.length) {
                val = args[ai + 1].trim();
            }
            if (param.equalsIgnoreCase("--help")) {
                help = true;
                break;
            } else if (param.equalsIgnoreCase("--url") && !val.startsWith("--")
                    && !val.isEmpty()) {
                url = val;
            } else if (param.equalsIgnoreCase("--username")
                    && !val.startsWith("--") && !val.isEmpty()) {
                userName = val;
            } else if (param.equalsIgnoreCase("--password")
                    && !val.startsWith("--") && !val.isEmpty()) {
                password = val;
            }
            val = "";
            ai += 2;
        }
        if (url == null || userName == null || password == null) {
            throw new IllegalArgumentException(
                    "Expected --url, --username, --password arguments.");
        }
    }

    /**
     * Establishes session with the vCenter server.
     *
     * @throws RuntimeFaultFaultMsg
     * @throws InvalidLoginFaultMsg
     * @throws InvalidLocaleFaultMsg
     *
     * @throws Exception
     *             the exception
     */
    private static void connect() throws RuntimeFaultFaultMsg,
            InvalidLocaleFaultMsg, InvalidLoginFaultMsg {

        HostnameVerifier hv = new HostnameVerifier() {
            @Override
            public boolean verify(String urlHostName, SSLSession session) {
                return true;
            }
        };
        trustAllHttpsCertificates();
        HttpsURLConnection.setDefaultHostnameVerifier(hv);

        SVC_INST_REF.setType(SVC_INST_NAME);
        SVC_INST_REF.setValue(SVC_INST_NAME);

        vimService = new VimService();
        vimPort = vimService.getVimPort();
        Map<String, Object> ctxt = ((BindingProvider) vimPort)
                .getRequestContext();

        ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url);
        ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);

        serviceContent = vimPort.retrieveServiceContent(SVC_INST_REF);
        vimPort.login(serviceContent.getSessionManager(), userName, password,
                null);
        isConnected = true;
    }

    /**
     * Disconnects the user session.
     *
     * @throws RuntimeFaultFaultMsg
     *
     * @throws Exception
     */
    private static void disconnect() throws RuntimeFaultFaultMsg {
        if (isConnected) {
            vimPort.logout(serviceContent.getSessionManager());
        }
        isConnected = false;
    }

    private static void printSoapFaultException(SOAPFaultException sfe) {
        System.out.println("SOAP Fault -");
        if (sfe.getFault().hasDetail()) {
            System.out.println(sfe.getFault().getDetail().getFirstChild()
                    .getLocalName());
        }
        if (sfe.getFault().getFaultString() != null) {
            System.out
                    .println("\n Message: " + sfe.getFault().getFaultString());
        }
    }

    /**
     * Returns all the MOREFs of the specified type that are present under the
     * container
     *
     * @param container
     *            {@link ManagedObjectReference} of the container to begin the
     *            search from
     * @param morefType
     *            Type of the managed entity that needs to be searched
     *
     * @param morefProperties
     *            Array of properties to be fetched for the moref
     * @return Map of MOREF and Map of name value pair of properties requested
     *         of the managed objects present. If none exist then empty Map is
     *         returned
     *
     * @throws InvalidPropertyFaultMsg
     * @throws RuntimeFaultFaultMsg
     */
    private static Map<ManagedObjectReference, Map<String, Object>> getMOREFsInContainerByType(
            ManagedObjectReference container, String morefType,
            String[] morefProperties) throws InvalidPropertyFaultMsg,
            RuntimeFaultFaultMsg {
        ManagedObjectReference viewManager = serviceContent.getViewManager();
        ManagedObjectReference containerView = vimPort.createContainerView(
                viewManager, container, Arrays.asList(morefType), true);

        Map<ManagedObjectReference, Map<String, Object>> tgtMoref = new HashMap<ManagedObjectReference, Map<String, Object>>();

        // Create Property Spec
        PropertySpec propertySpec = new PropertySpec();
        propertySpec.setAll(Boolean.FALSE);
        propertySpec.setType(morefType);
        propertySpec.getPathSet().addAll(Arrays.asList(morefProperties));

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

        // Now create Object Spec
        ObjectSpec objectSpec = new ObjectSpec();
        objectSpec.setObj(containerView);
        objectSpec.setSkip(Boolean.TRUE);
        objectSpec.getSelectSet().add(ts);

        // Create PropertyFilterSpec using the PropertySpec and ObjectPec
        // created above.
        PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec();
        propertyFilterSpec.getPropSet().add(propertySpec);
        propertyFilterSpec.getObjectSet().add(objectSpec);

        List<PropertyFilterSpec> propertyFilterSpecs = new ArrayList<PropertyFilterSpec>();
        propertyFilterSpecs.add(propertyFilterSpec);

        List<ObjectContent> oCont = vimPort.retrieveProperties(
                serviceContent.getPropertyCollector(), propertyFilterSpecs);
        if (oCont != null) {
            for (ObjectContent oc : oCont) {
                Map<String, Object> propMap = new HashMap<String, Object>();
                List<DynamicProperty> dps = oc.getPropSet();
                if (dps != null) {
                    for (DynamicProperty dp : dps) {
                        propMap.put(dp.getName(), dp.getVal());
                    }
                }
                tgtMoref.put(oc.getObj(), propMap);
            }
        }
        return tgtMoref;
    }

    private static void setHostSystemAttributesList() {
        hostSystemAttributesArr.add("name");
        hostSystemAttributesArr.add("config.product.productLineId");
        hostSystemAttributesArr.add("summary.hardware.cpuMhz");
        hostSystemAttributesArr.add("summary.hardware.numCpuCores");
        hostSystemAttributesArr.add("summary.hardware.cpuModel");
        hostSystemAttributesArr.add("summary.hardware.uuid");
        hostSystemAttributesArr.add("summary.hardware.vendor");
        hostSystemAttributesArr.add("summary.hardware.model");
        hostSystemAttributesArr.add("summary.hardware.memorySize");
        hostSystemAttributesArr.add("summary.hardware.numNics");
        hostSystemAttributesArr.add("summary.config.name");
        hostSystemAttributesArr.add("summary.config.product.osType");
        hostSystemAttributesArr.add("summary.config.vmotionEnabled");
        hostSystemAttributesArr.add("summary.quickStats.overallCpuUsage");
        hostSystemAttributesArr.add("summary.quickStats.overallMemoryUsage");
    }
    
    private static String formatStr(String pop){
        String str=pop;
        if("name".equals(pop)){
            str = "主机名";
        }
        if("summary.config.name".equals(pop)){
            str = "配置名";
        }
        if("summary.config.vmotionEnabled".equals(pop)){
            str = "虚拟化设置";
        }
        if("config.product.productLineId".equals(pop)){
            str = "产品ID";
        }
        if("summary.hardware.cpuMhz".equals(pop)){
            str = "CPU主频";
        }
        if("summary.hardware.numCpuCores".equals(pop)){
            str = "CPU内核数";
        }
        if("summary.hardware.cpuModel".equals(pop)){
            str = "CPU类型";
        }
        if("summary.hardware.uuid".equals(pop)){
            str = "序列号";
        }
        if("summary.hardware.vendor".equals(pop)){
            str = "生产商";
        }
        if("summary.hardware.model".equals(pop)){
            str = "主板";
        }
        if("summary.hardware.memorySize".equals(pop)){
            str = "内存大小";
        }
        if("summary.hardware.numNics".equals(pop)){
            str = "网卡";
        }
        if("summary.quickStats.overallCpuUsage".equals(pop)){
            str = "CPU使用";
        }
        if("summary.config.product.osType".equals(pop)){
            str = "操作系统类型";
        }
        if("summary.quickStats.overallMemoryUsage".equals(pop)){
            str = "内存使用";
        }
        
        return str;
    }

    /**
     * Prints the Host names.
     */
    private static List<String> printHostProductDetails() {
        List<String> list = new ArrayList<String>();
        try {
            setHostSystemAttributesList();
            Map<ManagedObjectReference, Map<String, Object>> hosts = getMOREFsInContainerByType(
                    serviceContent.getRootFolder(), "HostSystem",
                    hostSystemAttributesArr.toArray(new String[] {}));

            for (ManagedObjectReference host : hosts.keySet()) {
                Map<String, Object> hostprops = hosts.get(host);
                for (String prop : hostprops.keySet()) {
//                    System.out.println(prop + " : " + hostprops.get(prop));
                    list.add(formatStr(prop) + " : " + hostprops.get(prop));
                }
//                System.out
//                        .println("\n\n***************************************************************");
            }
        } catch (SOAPFaultException sfe) {
            printSoapFaultException(sfe);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    private static void printUsage() {
        System.out
                .println("This sample gets the hostname and additional details of the ESX "
                        + "Servers in the inventory");
        System.out.println("\nParameters:");
        System.out.println("url          [required] : url of the web service");
        System.out
                .println("username     [required] : username for the authentication");
        System.out
                .println("password     [required] : password for the authentication");
        System.out.println("\nCommand:");
        System.out.println("run.bat com.vmware.general.GetHostName");
        System.out
                .println("--url [webservicesurl] --username [username] --password [password]");
    }

//    public static void main(String[] args) {
//        try {
//            String[] arr = { "--url", "https://192.168.1.239/sdk",
//                    "--username", "root", "--password", "123456789",
//                    "--ignorecert", "ignorecert" };
//            getConnectionParameters(arr);
//            if (help) {
//                printUsage();
//                return;
//            }
//            connect();
//            printHostProductDetails();
//        } catch (IllegalArgumentException e) {
//            System.out.println(e.getMessage());
//            printUsage();
//        } catch (SOAPFaultException sfe) {
//            printSoapFaultException(sfe);
//        } catch (Exception e) {
//            System.out.println(" Connect Failed ");
//            e.printStackTrace();
//        } finally {
//            try {
//                disconnect();
//            } catch (SOAPFaultException sfe) {
//                printSoapFaultException(sfe);
//            } catch (Exception e) {
//                System.out.println("Failed to disconnect - " + e.getMessage());
//                e.printStackTrace();
//            }
//        }
//    }

    public List<String> test(String[] arr) {
        List<String> list = new ArrayList<String>();
        try {
            getConnectionParameters(arr);
//            if (help) {
//                printUsage();
//                return;
//            }
            connect();
            list = printHostProductDetails();
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
            printUsage();
        } catch (SOAPFaultException sfe) {
            printSoapFaultException(sfe);
        } catch (Exception e) {
            System.out.println(" Connect Failed ");
            e.printStackTrace();
        } finally {
            try {
                disconnect();
            } catch (SOAPFaultException sfe) {
                printSoapFaultException(sfe);
            } catch (Exception e) {
                System.out.println("Failed to disconnect - " + e.getMessage());
                e.printStackTrace();
            }
        }
        return list;
    }
}

改造com/vmware/general/Browser.java创建QueryVm方法查询虚拟机列表信息


package com.vmware.general;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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;

import com.vmware.vim25.DynamicProperty;
import com.vmware.vim25.InvalidPropertyFaultMsg;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.ObjectContent;
import com.vmware.vim25.ObjectSpec;
import com.vmware.vim25.PropertyFilterSpec;
import com.vmware.vim25.PropertySpec;
import com.vmware.vim25.RuntimeFaultFaultMsg;
import com.vmware.vim25.ServiceContent;
import com.vmware.vim25.TraversalSpec;
import com.vmware.vim25.VimPortType;
import com.vmware.vim25.VimService;

/**
 * <pre>
 * Browser
 *
 * This sample prints managed entity, its type, reference value,
 * property name, Property Value, Inner Object Type, its Inner Reference Value
 * and inner property value
 *
 * <b>Parameters:</b>
 * url         [required] : url of the web service
 * username    [required] : username for the authentication
 * password    [required] : password for the authentication
 *
 * <b>Command Line:</b>
 * run.bat com.vmware.general.Browser --url [webserviceurl]
 * --username [username] --password [password]
 * </pre>
 */

public class Browser {

   private static class TrustAllTrustManager implements
         javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {

      @Override
      public java.security.cert.X509Certificate[] getAcceptedIssuers() {
         return null;
      }

      @Override
      public void checkServerTrusted(
            java.security.cert.X509Certificate[] certs, String authType)
            throws java.security.cert.CertificateException {
         return;
      }

      @Override
      public void checkClientTrusted(
            java.security.cert.X509Certificate[] certs, String authType)
            throws java.security.cert.CertificateException {
         return;
      }
   }

   private static final ManagedObjectReference SVC_INST_REF =
         new ManagedObjectReference();
   private static final String SVC_INST_NAME = "ServiceInstance";
   private static final String PROP_ME_NAME = "name";
   private static ServiceContent serviceContent;
   private static ManagedObjectReference rootRef;
   private static VimService vimService;
   private static VimPortType vimPort;
   private static String url;
   private static String userName;
   private static String password;
   private static boolean help = false;
   private static boolean isConnected = false;

   private static void trustAllHttpsCertificates() throws Exception {
      // Create a trust manager that does not validate certificate chains:
      javax.net.ssl.TrustManager[] trustAllCerts =
            new javax.net.ssl.TrustManager[1];
      javax.net.ssl.TrustManager tm = new TrustAllTrustManager();
      trustAllCerts[0] = tm;
      javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
      javax.net.ssl.SSLSessionContext sslsc = sc.getServerSessionContext();
      sslsc.setSessionTimeout(0);
      sc.init(null, trustAllCerts, null);
      javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc
            .getSocketFactory());
   }

   // get common parameters
   private static void getConnectionParameters(String[] args)
         throws IllegalArgumentException {
      int ai = 0;
      String param = "";
      String val = "";
      while (ai < args.length) {
         param = args[ai].trim();
         if (ai + 1 < args.length) {
            val = args[ai + 1].trim();
         }
         if (param.equalsIgnoreCase("--help")) {
            help = true;
            break;
         } else if (param.equalsIgnoreCase("--url") && !val.startsWith("--")
               && !val.isEmpty()) {
            url = val;
         } else if (param.equalsIgnoreCase("--username")
               && !val.startsWith("--") && !val.isEmpty()) {
            userName = val;
         } else if (param.equalsIgnoreCase("--password")
               && !val.startsWith("--") && !val.isEmpty()) {
            password = val;
         }
         val = "";
         ai += 2;
      }
      if (url == null || userName == null || password == null) {
         throw new IllegalArgumentException(
               "Expected --url, --username, --password arguments.");
      }
   }

   /**
    * Establishes session with the vCenter server server.
    *
    * @throws Exception
    *            the exception
    */
   private static void connect() throws Exception {

      HostnameVerifier hv = new HostnameVerifier() {
         @Override
         public boolean verify(String urlHostName, SSLSession session) {
            return true;
         }
      };
      trustAllHttpsCertificates();
      HttpsURLConnection.setDefaultHostnameVerifier(hv);

      SVC_INST_REF.setType(SVC_INST_NAME);
      SVC_INST_REF.setValue(SVC_INST_NAME);

      vimService = new VimService();
      vimPort = vimService.getVimPort();
      Map<String, Object> ctxt =
            ((BindingProvider) vimPort).getRequestContext();

      ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url);
      ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);

      serviceContent = vimPort.retrieveServiceContent(SVC_INST_REF);
      vimPort.login(serviceContent.getSessionManager(), userName, password,
            null);
      isConnected = true;

      rootRef = serviceContent.getRootFolder();
   }

   /**
    * Disconnects the user session.
    *
    * @throws Exception
    */
   private static void disconnect() throws Exception {
      if (isConnected) {
         vimPort.logout(serviceContent.getSessionManager());
      }
      isConnected = false;
   }

   /**
    * Returns all the MOREFs of the specified type that are present under the
    * folder
    *
    * @param folder
    *           {@link ManagedObjectReference} of the folder to begin the search
    *           from
    * @param morefType
    *           Type of the managed entity that needs to be searched
    *
    * @return Map of name and MOREF of the managed objects present. If none
    *         exist then empty Map is returned
    *
    * @throws InvalidPropertyFaultMsg
    * @throws RuntimeFaultFaultMsg
    */
   private static Map<String, ManagedObjectReference> getMOREFsInFolderByType(
         ManagedObjectReference folder, String morefType)
         throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
      ManagedObjectReference viewManager = serviceContent.getViewManager();
      ManagedObjectReference containerView =
            vimPort.createContainerView(viewManager, folder,
                  Arrays.asList(morefType), true);

      Map<String, ManagedObjectReference> tgtMoref =
            new HashMap<String, ManagedObjectReference>();

      // Create Property Spec
      PropertySpec propertySpec = new PropertySpec();
      propertySpec.setAll(Boolean.FALSE);
      propertySpec.setType(morefType);
      propertySpec.getPathSet().add(PROP_ME_NAME);

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

      // Now create Object Spec
      ObjectSpec objectSpec = new ObjectSpec();
      objectSpec.setObj(containerView);
      objectSpec.setSkip(Boolean.TRUE);
      objectSpec.getSelectSet().add(ts);

      // Create PropertyFilterSpec using the PropertySpec and ObjectPec
      // created above.
      PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec();
      propertyFilterSpec.getPropSet().add(propertySpec);
      propertyFilterSpec.getObjectSet().add(objectSpec);

      List<PropertyFilterSpec> propertyFilterSpecs =
            new ArrayList<PropertyFilterSpec>();
      propertyFilterSpecs.add(propertyFilterSpec);

      List<ObjectContent> oCont =
            vimPort.retrieveProperties(serviceContent.getPropertyCollector(),
                  propertyFilterSpecs);
      if (oCont != null) {
         for (ObjectContent oc : oCont) {
            ManagedObjectReference mr = oc.getObj();
            String entityNm = null;
            List<DynamicProperty> dps = oc.getPropSet();
            if (dps != null) {
               for (DynamicProperty dp : dps) {
                  entityNm = (String) dp.getVal();
               }
            }
            tgtMoref.put(entityNm, mr);
         }
      }
      return tgtMoref;
   }

   private static List<String> printInventory() throws InvalidPropertyFaultMsg,
         RuntimeFaultFaultMsg {
      Map<String, ManagedObjectReference> inventory =
            getMOREFsInFolderByType(rootRef, "ManagedEntity");
      List<String> list = new ArrayList<String>();
      for (String entityName : inventory.keySet()) {
          list.add("> " + inventory.get(entityName).getType() + ":"
               + inventory.get(entityName).getValue() + "{" + entityName + "}");
//         System.out.println("> " + inventory.get(entityName).getType() + ":"
//               + inventory.get(entityName).getValue() + "{" + entityName + "}");
      }
      return list;
   }

   private static void printSoapFaultException(SOAPFaultException sfe) {
      System.out.println("SOAP Fault -");
      if (sfe.getFault().hasDetail()) {
         System.out.println(sfe.getFault().getDetail().getFirstChild()
               .getLocalName());
      }
      if (sfe.getFault().getFaultString() != null) {
         System.out.println("\n Message: " + sfe.getFault().getFaultString());
      }
   }

   private static void printUsage() {
      System.out
            .println("This sample prints managed entity, its type, reference value,");
      System.out.println("property name, Property Value, Inner Object Type,");
      System.out.println("its Inner Reference Value and inner property value");
      System.out.println("\nParameters:");
      System.out.println("url         [required] : url of the web service");
      System.out
            .println("username    [required] : username for the authentication");
      System.out
            .println("password    [required] : password for the authentication");
      System.out.println("\nCommand:");
      System.out
            .println("run.bat com.vmware.general.Browser --url [webserviceurl] "
                  + "--username [username] --password [password]");
   }

   public List<String> QueryVm(String[] args) {
      List<String> list = new ArrayList<String>();
      try {
         getConnectionParameters(args);
//         if (help) {
//            printUsage();
//            return;
//         }
         connect();
         list = printInventory();
      } catch (IllegalArgumentException e) {
         System.out.println(e.getMessage());
         printUsage();
      } catch (SOAPFaultException sfe) {
         printSoapFaultException(sfe);
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            disconnect();
         } catch (SOAPFaultException sfe) {
            printSoapFaultException(sfe);
         } catch (Exception e) {
            System.out.println("Failed to disconnect - " + e.getMessage());
            e.printStackTrace();
         }
      }
      return list;
   }
}

spring mvc 控制层UserController.java调用上面创建的两个方法查询相关信息,本类中加入了一个验证码的方法是用于测试的,非必要方法


package com.sxt.action;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.servlet.ModelAndView;

import cn.dsjkf.util.ImageUtil;

//import com.util.ImageUtil;
import com.vmware.general.Browser;
import com.vmware.general.GetHostName;

@Controller("userController")
@RequestMapping("/server/")
public class UserController{
    
    @RequestMapping("queryServer")
    public ModelAndView user(HttpServletRequest request,String vCode,String ip,String root,String password,String queryType,ModelMap modelMap){
        ModelAndView mav=new ModelAndView();
        String[] arr = { "--url", "https://"+ip+"/sdk",
                "--username", root, "--password", password,
                "--ignorecert", "ignorecert" };
        List<String> list = new ArrayList<String>();
        String code = request.getSession().getAttribute("imageCode").toString();
        if(code.equals(vCode)){
            mav.setViewName("index");
            if("server".equals(queryType)){
                GetHostName ghn = new GetHostName();
                list = ghn.test(arr);
                mav.addObject("list",list);
            }
            if("vm".equals(queryType)){
                Browser b = new Browser();
                list = b.QueryVm(arr);
                mav.addObject("list",list);
            }
        }else{
            mav.setViewName("error");
            if(vCode!=null&&vCode!=""){
                mav.addObject("error","查询成功!");
            }else{
                mav.addObject("error","查询失败!");
            }
            
        }
        return mav;
    }
    
    @RequestMapping("code")
    public void code(HttpServletResponse response,HttpServletRequest request) throws IOException{
        Map<String, BufferedImage> imageMap = ImageUtil.createImage();
        String imageCode = imageMap.keySet().iterator().next();
        HttpSession session = request.getSession();  
        session.setAttribute("imageCode", imageCode);
        BufferedImage image = imageMap.get(imageCode);
        InputStream in = null;
        byte[] tmp = null;
        try {
            in = ImageUtil.getInputStream(image);;
            tmp = new byte[in.available()];
            in.read(tmp);
            ServletOutputStream out = response.getOutputStream();
            out.write(tmp);
            out.flush();
        } finally{
            if(in!=null){
                in.close();
            }
        }
    }

}

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>测试页面</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">

<script src="js/jquery.js"></script>
</head>
<script language="javascript">
    function setQueryType(queryType){
        $('#queryType').attr("value",queryType);
    }
    
    function change(imgObj) {
        imgObj.src = "<%=basePath%>server/code.do?date="+new Date().getTime();
    }
</script>
<body>
    <table>
        <tr>
            <td>
                <form action="<%=basePath%>server/queryServer.do" method="POST" target="back">
                    <input type="hidden" name="method" value="queryServer" />
                    <input type="hidden" name="u.uname" value="lilei">
                    <input type="hidden" id="queryType" name="queryType" value="">
                    <fieldset>
                        <legend>服务器查询:</legend>
                        <table>
                            <tr>
                                <td>服务IP:</td>
                                <td>
                                    <select name="ip">
                                      <option value ="192.168.1.239">192.168.1.239</option>
                                    </select>
                                </td>
                                <td>用户名:</td>
                                <td>
                                    <input type="text" name="root">
                                </td>
                                <td>密码:</td>
                                <td>
                                    <input type="text" name="password">
                                </td>
                            </tr>
                            <tr>
                                <td class="login_info">验证码:</td>
                                <td class="width70"><input id="vCode" name="vCode" type="text" class="width70" /></td>
                                <td><img id="vImg" src="<%=basePath%>server/code.do" alt="验证码" title="点击更换" onclick="change(this);"/></td>            
                            </tr>
                            <tr>
                                <td colspan="6" style="text-align:center;">
                                    <input type="submit" onclick="setQueryType('server');" value="查询服务器"/>
                                    <input type="submit" onclick="setQueryType('vm');" value="查询虚拟机"/>
                                </td>
                            </tr>
                        </table>
                    </fieldset>
                </form>
            </td>
        </tr>
        <tr>
            <td><iframe width=800 height=600 frameborder=0 name="back"></iframe></td>
        </tr>
    </table>
</body>
</html>

最后一步,配置运行时变量
右键工程-Run As->Run Configuration,在变量中引入证书文件变量,让程序运行时能够找到它并执行验证
pz

运行时错误处理:如果运行时提示找不到vim.wsdl或vimService.wsdl,请在VMware-vSphere-SDK-5.1.0文件夹里搜索并把这两个文件复制到
com/vmware/vim25下

工程实例下载:http://pan.baidu.com/s/1gd7W2Sr

标签:
admin

给我留言

Copyright © 大师级 保留所有权利.   Theme  大师级 桂ICP备14003638号

用户登录

分享到: