Example #1
0
  /**
   * Creates the virtual machine.
   *
   * @throws RemoteException the remote exception
   * @throws Exception the exception
   */
  void createVirtualMachine()
      throws RemoteException, RuntimeFaultFaultMsg, InvalidPropertyFaultMsg,
          InvalidCollectorVersionFaultMsg, OutOfBoundsFaultMsg, DuplicateNameFaultMsg,
          VmConfigFaultFaultMsg, InsufficientResourcesFaultFaultMsg, AlreadyExistsFaultMsg,
          InvalidDatastoreFaultMsg, FileFaultFaultMsg, InvalidStateFaultMsg, InvalidNameFaultMsg,
          TaskInProgressFaultMsg {

    ManagedObjectReference dcmor =
        getMOREFsInContainerByType(serviceContent.getRootFolder(), "Datacenter")
            .get(dataCenterName);

    if (dcmor == null) {
      System.out.println("Datacenter " + dataCenterName + " not found.");
      return;
    }
    ManagedObjectReference hostmor = getMOREFsInContainerByType(dcmor, "HostSystem").get(hostname);
    if (hostmor == null) {
      System.out.println("Host " + hostname + " not found");
      return;
    }

    ManagedObjectReference crmor =
        (ManagedObjectReference)
            getMOREFs.entityProps(hostmor, new String[] {"parent"}).get("parent");
    if (crmor == null) {
      System.out.println("No Compute Resource Found On Specified Host");
      return;
    }

    ManagedObjectReference resourcepoolmor =
        (ManagedObjectReference)
            getMOREFs.entityProps(crmor, new String[] {"resourcePool"}).get("resourcePool");
    ManagedObjectReference vmFolderMor =
        (ManagedObjectReference)
            getMOREFs.entityProps(dcmor, new String[] {"vmFolder"}).get("vmFolder");

    VirtualMachineConfigSpec vmConfigSpec =
        createVmConfigSpec(virtualMachineName, dataStore, diskSize, crmor, hostmor);

    vmConfigSpec.setName(virtualMachineName);
    vmConfigSpec.setAnnotation("VirtualMachine Annotation");
    vmConfigSpec.setMemoryMB(new Long(vmMemory));
    vmConfigSpec.setNumCPUs(numCpus);
    vmConfigSpec.setGuestId(guestOsId);

    ManagedObjectReference taskmor =
        vimPort.createVMTask(vmFolderMor, vmConfigSpec, resourcepoolmor, hostmor);
    if (getTaskResultAfterDone(taskmor)) {
      System.out.printf("Success: Creating VM  - [ %s ] %n", virtualMachineName);
    } else {
      String msg = "Failure: Creating [ " + virtualMachineName + "] VM";
      throw new RuntimeException(msg);
    }
    ManagedObjectReference vmMor =
        (ManagedObjectReference)
            getMOREFs.entityProps(taskmor, new String[] {"info.result"}).get("info.result");
    System.out.println("Powering on the newly created VM " + virtualMachineName);
    // Start the Newly Created VM.
    powerOnVM(vmMor);
  }