Display the License information related to features whose keys are esxfull, esxExpress, drs, vmotion

GetLicenseInfo.java

Copyright © 2008 VMware, Inc. All rights reserved.

//# Copyright 2008 VMware, Inc.  All rights reserved.

//#######################################################################################
//# DISCLAIMER. THIS SCRIPT IS PROVIDED TO YOU "AS IS" WITHOUT WARRANTIES OR CONDITIONS 
//# OF ANY KIND, WHETHER ORAL OR WRITTEN, EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY 
//# DISCLAIMS ANY IMPLIED WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY 
//# QUALITY, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. 
//#######################################################################################


//#######################################################################################
//#
//# GetLicenseInfo.java
//#	Example script to reterieve the information of licence of a host related to features 
//# whose keys are esxfull, esxExpress, drs, vmotion
//#	Parameters:
//		   <url> 					url of ESX/VC
//		   <username> 				user name
//		   <password> 				password
//		   <hostname> 				Name of the host

//# This script works with VMware VirtualCenter 2.0 or later.

//# This script works with VMware ESX Server 3.0 or later.
//######################################################################################

package com.vmware.samples.general;

import com.vmware.vim.*;
import java.net.URL;
import javax.xml.rpc.Stub;
import java.lang.reflect.Method;
import java.util.*;
import java.lang.reflect.*;



public class GetLicenseInfo {
   private ManagedObjectReference _svcRef;
   private VimServiceLocator _locator;
   private VimPortType _service; 
   private ServiceContent _sic; 
   
//Method to connect to create ServiceInstance MOR                
   private void createServiceRef() throws Exception {
      _svcRef = new ManagedObjectReference();
      _svcRef.setType("ServiceInstance");
      _svcRef.set_value("ServiceInstance");
    
   } 
   
 //Method to connect to VC/ESX        
   private void connectAndLogin(String[] args) throws Exception {
      System.setProperty("org.apache.axis.components.net.SecureSocketFactory",
                            "org.apache.axis.components.net.SunFakeTrustSocketFactory");
      String url = args[0];
      String username = args[1];
      String password = args[2];      
      createServiceRef();					// Creating servicereference
      _locator = new VimServiceLocator();
      _locator.setMaintainSession(true);
      _service = _locator.getVimPort(new URL(url));
      _sic = _service.retrieveServiceContent(_svcRef);
      if (_sic.getSessionManager() != null) {
         _service.login(_sic.getSessionManager(), username, password, null);
      }
      System.out.println("info---"+_sic.getAbout().getFullName());
   }
   
//Logout    
   private void disconnect() throws Exception {
      if (_service != null) {
         _service.logout(_sic.getSessionManager());
         _service = null;
         _sic = null;
      }
   }
// Main Method
   public static void main(String[] args) throws Exception {       
      System.setProperty("axis.socketSecureFactory", 
                         "org.apache.axis.components.net.SunFakeTrustSocketFactory");
      GetLicenseInfo obj = new GetLicenseInfo();
      obj.connectAndLogin(args);            
      obj.initialize(args);  
      System.out.println("Disconnecting");    
      obj.disconnect();
   }
   // Displays all the Licenses available on a host.
   private void initialize(String [] args) throws Exception {
      String hostName = args[3];
      String[][] typeinfo = new String[][] { new String[] {"HostSystem","name"},};
      ManagedObjectReference hostMOR = getHostMOR(typeinfo,hostName);
      
      if(hostMOR != null) {      
         ManagedObjectReference licMgr =  _sic.getLicenseManager();         
         LicenseUsageInfo licInfo = _service.queryLicenseUsage(licMgr,hostMOR);
         LicenseReservationInfo [] test = licInfo.getReservationInfo();
         System.out.println("License Information ");
         for(int i=0; i<test.length; i++) {
            String key = test[i].getKey();
            if(key.equalsIgnoreCase("esxExpress") ||
               key.equalsIgnoreCase("esxFull") ||
               key.equalsIgnoreCase("vmotion") ||
               key.equalsIgnoreCase("drs")) {
               System.out.println("\n");
               System.out.println("Key      " + key);               
               System.out.println("State    " + test[i].getState().getValue());               
            }
         }
      }
      else {
         System.out.println("Host Not Found");
      }
   }  
 
   private ObjectContent[] getObjectProperties(
      ManagedObjectReference collector,
      ManagedObjectReference mobj, String[] properties
   ) throws Exception {
      if (mobj == null) {
         return null;
      }
      ManagedObjectReference usecoll = collector;
      if (usecoll == null) {
         usecoll = _sic.getPropertyCollector();
      }
      PropertyFilterSpec spec = new PropertyFilterSpec();
      spec.setPropSet(new PropertySpec[] { new PropertySpec() });
      spec.getPropSet(0).setAll(new Boolean (properties == null || properties.length == 0));
      spec.getPropSet(0).setType(mobj.getType());
      spec.getPropSet(0).setPathSet(properties);
      spec.setObjectSet(new ObjectSpec[] { new ObjectSpec() });
      spec.getObjectSet(0).setObj(mobj);
      spec.getObjectSet(0).setSkip(Boolean.FALSE);
      return _service.retrieveProperties(usecoll, new PropertyFilterSpec[] { spec });
   }
   // Retrieve the properties of Managed object reference
   // Argument Managed Object Reference
   //          Property Name
   // Returns the object.
   private Object getDynamicProperty(
         ManagedObjectReference mor,
         String propertyName
   ) throws Exception {
      ObjectContent[] objContent = getObjectProperties(null, mor,
            new String[] { propertyName });      
      Object propertyValue = null;
      if (objContent != null) {
         DynamicProperty[] dynamicProperty = objContent[0].getPropSet();
         if (dynamicProperty != null) {
            Object dynamicPropertyVal = dynamicProperty[0].getVal();
            String dynamicPropertyName = dynamicPropertyVal.getClass().getName();
            if (dynamicPropertyName.indexOf("ArrayOf") != -1) {
               String methodName = dynamicPropertyName.substring(
                     dynamicPropertyName.indexOf("ArrayOf")
                     + "ArrayOf".length(), 
                     dynamicPropertyName.length());
               if (methodExists(dynamicPropertyVal,
                     "get" + methodName, null)) {
                  methodName = "get" + methodName;
               } else {
                  methodName = "get_" + 
                  methodName.toLowerCase();
               }
               Method getMorMethod = dynamicPropertyVal.getClass().
               getDeclaredMethod(methodName,  (Class[])null);
               propertyValue = getMorMethod.invoke(dynamicPropertyVal, (Object[])null);
            } else if (dynamicPropertyVal.getClass().isArray()) {
               propertyValue = dynamicPropertyVal;
            } else {
               propertyValue = dynamicPropertyVal;
            }
         }
      }
      return propertyValue;
   }
   // Retrieve the Host Managed Object Reference
   // Argument typeinfo -: To build property spec
   //          name     -: Name of the Managed Entity
   //  Retruns the Managed Object Reference
   private ManagedObjectReference getHostMOR(String[][] typeinfo,String name) throws Exception{
      try {
         ManagedObjectReference useroot = _sic.getRootFolder();
         SelectionSpec[] selectionSpecs = null;         
         selectionSpecs = buildFullTraversal();
         
         PropertySpec[] propspecary = buildPropertySpecArray(typeinfo);
         PropertyFilterSpec spec = 
         new PropertyFilterSpec(null,null,
            propspecary,
            new ObjectSpec[] { 
               new ObjectSpec(null,null,
                  useroot,
                  Boolean.FALSE,
                  selectionSpecs
               ) 
            }
         );
         ObjectContent[] retoc =
            _service.retrieveProperties(
            _sic.getPropertyCollector(),
            new PropertyFilterSpec[] { spec }
         );

         ManagedObjectReference ret = null;
         for(int i=0;i<retoc.length;i++) {
            ManagedObjectReference mor = retoc[i].getObj();
            String objname = (String)getDynamicProperty(mor,"name");
            if(name.equalsIgnoreCase(name)) {
               ret = mor;
               break;
            }
         }
         return ret;
      } catch( Exception e ) {
         System.out.println(e.getMessage());
         e.printStackTrace();
         return null;
      }
   }
   // Builds a traversal spec to search the managed entity in inventory.
   private SelectionSpec [] buildFullTraversal() {
      TraversalSpec rpToRp = new TraversalSpec(
            null, null, null,
            "ResourcePool", 
            "resourcePool", 
            Boolean.FALSE, 
            new SelectionSpec[] {new SelectionSpec(null, null, "rpToRp"),
                                 new SelectionSpec(null, null, "rpToVm")}
      );
      rpToRp.setName("rpToRp");
      TraversalSpec rpToVm = new TraversalSpec(null,null,null,
            "ResourcePool", 
            "vm", 
            Boolean.FALSE, 
            new SelectionSpec[] {}
      );
      rpToVm.setName("rpToVm");
      TraversalSpec crToRp = new TraversalSpec(
            null, null, null,
            "ComputeResource", 
            "resourcePool", 
            Boolean.FALSE, 
            new SelectionSpec[] {new SelectionSpec(null, null, "rpToRp"),
                                 new SelectionSpec(null, null, "rpToVm")}
      );
      crToRp.setName("crToRp");
      TraversalSpec crToH = new TraversalSpec(
            null, null, null,
            "ComputeResource", 
            "host", 
            Boolean.FALSE, 
            new SelectionSpec[] {}
      );
      crToH.setName("crToH");
      TraversalSpec dcToHf = new TraversalSpec(
            null, null, null,
            "Datacenter", 
            "hostFolder", 
            Boolean.FALSE, 
            new SelectionSpec[] {               
               new SelectionSpec(null, null, "visitFolders")
            }
      );
      dcToHf.setName("dcToHf");
      TraversalSpec dcToVmf = new TraversalSpec(
            null, null, null,
            "Datacenter", 
            "vmFolder", 
            Boolean.FALSE, 
            new SelectionSpec[] {
               new SelectionSpec(null, null, "visitFolders")               
            }
      );
      dcToVmf.setName("dcToVmf");   
      TraversalSpec HToVm = new TraversalSpec(null,null,null,
            "HostSystem", 
            "vm", 
            Boolean.FALSE, 
            new SelectionSpec[] {new SelectionSpec(null, null, "visitFolders")}
      );
      HToVm.setName("HToVm");
      TraversalSpec visitFolders = 
         new TraversalSpec(
               null, null, null,
               "Folder", 
               "childEntity", 
               Boolean.FALSE, 
               new SelectionSpec[] {
                  new SelectionSpec(null, null, "visitFolders"),
                  new SelectionSpec(null, null, "dcToHf"),
                  new SelectionSpec(null, null, "dcToVmf"),
                  new SelectionSpec(null, null, "crToH"),
                  new SelectionSpec(null, null, "crToRp"),
                  new SelectionSpec(null, null, "HToVm"),                  
                  new SelectionSpec(null, null, "rpToVm"),                  
               }
         );
      visitFolders.setName("visitFolders");
      return new SelectionSpec [] {visitFolders,dcToVmf,dcToHf,crToH,crToRp,rpToRp,HToVm,rpToVm};
   }
  // Build a property filter Spec
   private PropertySpec[] buildPropertySpecArray(
      String[][] typeinfo
   ) {      
      HashMap tInfo = new HashMap();
      for(int ti = 0; ti < typeinfo.length; ++ti) {
         Set props = (Set)tInfo.get(typeinfo[ti][0]);
         if(props == null) {
            props = new HashSet();
            tInfo.put(typeinfo[ti][0], props);
         }
         boolean typeSkipped = false;
         for(int pi=0; pi<typeinfo[ti].length; ++pi) {
            String prop = typeinfo[ti][pi];
            if(typeSkipped) {
               props.add(prop);
            } else {
               typeSkipped = true;
            }
         }
      }
      ArrayList pSpecs = new ArrayList();
      for(Iterator ki = tInfo.keySet().iterator(); ki.hasNext();) {
         String type = (String)ki.next();
         PropertySpec pSpec = new PropertySpec();
         Set props = (Set)tInfo.get(type);
         pSpec.setType(type);
         pSpec.setAll(props.isEmpty()?Boolean.TRUE:Boolean.FALSE);
         pSpec.setPathSet(new String[props.size()]);
         int index = 0;
         for(Iterator pi = props.iterator(); pi.hasNext();) {
            String prop = (String)pi.next();
            pSpec.setPathSet(index++, prop);
         }
         pSpecs.add(pSpec);
      }      
      return (PropertySpec[])pSpecs.toArray(new PropertySpec[0]);
   }

   boolean methodExists(Object obj, 
         String methodName, 
         Class[] parameterTypes) {
      boolean exists = false;
      try {
         Method method = obj.getClass().getMethod(methodName, parameterTypes);
         if (method != null) {
            exists = true;
         }
      } catch(Exception e){}
      return exists;
   }
}

The sample code is provided "AS-IS" for use, modification, and redistribution in source and binary forms, provided that the copyright notice and this following list of conditions are retained and/or reproduced in your distribution. To the maximum extent permitted by law, VMware, Inc., its subsidiaries and affiliates hereby disclaim all express, implied and/or statutory warranties, including duties or conditions of merchantability, fitness for a particular purpose, and non-infringement of intellectual property rights. IN NO EVENT WILL VMWARE, ITS SUBSIDIARIES OR AFFILIATES BE LIABLE TO ANY OTHER PARTY FOR THE COST OF PROCURING SUBSTITUTE GOODS OR SERVICES, LOST PROFITS, LOSS OF USE, LOSS OF DATA, OR ANY INCIDENTAL, CONSEQUENTIAL, DIRECT, INDIRECT, OR SPECIAL DAMAGES, ARISING OUT OF THIS OR ANY OTHER AGREEMENT RELATING TO THE SAMPLE CODE.

You agree to defend, indemnify and hold harmless VMware, and any of its directors, officers, employees, agents, affiliates, or subsidiaries from and against all losses, damages, costs and liabilities arising from your use, modification and distribution of the sample code.

VMware does not certify or endorse your use of the sample code, nor is any support or other service provided in connection with the sample code.