com.vmware.vim25.VimPortType Java Examples

The following examples show how to use com.vmware.vim25.VimPortType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VimUtil.java    From vsphere-automation-sdk-java with MIT License 6 votes vote down vote up
/**
 * Deletes a managed object and waits for the delete operation to complete
 * 
 * @param vimPort
 * @param serviceContent
 * @param mor
 */
public static boolean deleteManagedEntity(VimPortType vimPort,
        ServiceContent serviceContent, ManagedObjectReference mor) {
    WaitForValues waitForValues = new WaitForValues(vimPort,
            serviceContent);
    System.out.println("Deleting : [" + mor.getValue() + "]");
    try {
        ManagedObjectReference taskmor = vimPort.destroyTask(mor);
        if (waitForValues.getTaskResultAfterDone(taskmor)) {
            System.out.println("Successful delete of Managed Entity - ["
                    + mor.getValue() + "]" + " and Entity Type - ["
                    + mor.getType() + "]");
            return true;
        } else {
            System.out
                    .println("Unable to delete : [" + mor.getValue() + "]");
            return false;
        }
    } catch (Exception e) {
        System.out.println("Unable to delete : [" + mor.getValue() + "]");
        System.out.println("Reason :" + e.getLocalizedMessage());
        return false;
    }
}
 
Example #2
Source File: VimUtil.java    From vsphere-automation-sdk-java with MIT License 6 votes vote down vote up
public static boolean createSnapshot(VimPortType vimPort,
        ServiceContent serviceContent, ManagedObjectReference vmMor,
        String snapshotname, String description) {
    WaitForValues waitForValues = new WaitForValues(vimPort,
            serviceContent);
    System.out.println("Taking snapshot : [" + snapshotname + "]");
    try {
        ManagedObjectReference taskMor = vimPort.createSnapshotTask(vmMor,
                snapshotname, description, false, false);
        if (waitForValues.getTaskResultAfterDone(taskMor)) {
            System.out.println("Snapshot - [" + snapshotname
                    + "] Creation Successful");
            return true;
        } else {
            System.out.println(
                    "Snapshot - [" + snapshotname + "] Creation Failed");
            return false;
        }
    } catch (Exception e) {
        System.out.println(
                "Snapshot - [" + snapshotname + "] Creation Failed");
        System.out.println("Reason :" + e.getLocalizedMessage());
        return false;
    }
}
 
Example #3
Source File: Actions.java    From development with Apache License 2.0 6 votes vote down vote up
protected TaskInfo getTaskInfo(VMwareClient vmw,
        VMPropertyHandler paramHandler) throws Exception {

    String instanceId = paramHandler.getInstanceName();
    String taskKey = paramHandler
            .getServiceSetting(VMPropertyHandler.TASK_KEY);
    logger.debug("VM: " + instanceId + " taskId: " + taskKey);
    if (taskKey == null || "".equals(taskKey)) {
        return null;
    }

    VimPortType service = vmw.getConnection().getService();
    ManagedObjectReference taskManager = vmw.getConnection()
            .getServiceContent().getTaskManager();
    ManagedObjectReference taskHistoryCollector = service
            .createCollectorForTasks(taskManager, new TaskFilterSpec());
    try {
        service.resetCollector(taskHistoryCollector);
        service.readNextTasks(taskHistoryCollector, 100);
        List<TaskInfo> taskList = vmw.getConnection().getService()
                .readPreviousTasks(taskHistoryCollector, 100);

        if (taskList != null) {
            for (TaskInfo taskInfo : taskList) {
                if (taskInfo != null && taskKey.equals(taskInfo.getKey())) {
                    logTaskInfo(taskInfo);
                    return taskInfo;
                }
            }
        }

        logger.error("Task not found. VM: " + instanceId + " taskId: "
                + taskKey);
        return null;
    } finally {
        service.destroyCollector(taskHistoryCollector);
    }
}
 
Example #4
Source File: VimUtil.java    From vsphere-automation-sdk-java with MIT License 5 votes vote down vote up
/**
 * Get access to the service content
 *
 * @param vimPortType
 * @return {@link ServiceContent}
 * @throws RuntimeFaultFaultMsg
 */
public static ServiceContent getServiceContent(VimPortType vimPortType)
        throws RuntimeFaultFaultMsg {
    // get the service content
    ManagedObjectReference serviceInstance = new ManagedObjectReference();
    serviceInstance.setType("ServiceInstance");
    serviceInstance.setValue("ServiceInstance");
    return vimPortType.retrieveServiceContent(serviceInstance);
}
 
Example #5
Source File: GetObjectProperties.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
/**
 * Uses the new RetrievePropertiesEx method to emulate the now deprecated
 * RetrieveProperties method
 *
 * @param propertyFilterSpecList
 * @return list of object content
 * @throws Exception
 */
private static List<ObjectContent> retrievePropertiesAllObjects(ConnectionResources connectionResources,
                                                               List<PropertyFilterSpec> propertyFilterSpecList)
        throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg {

    VimPortType vimPort = connectionResources.getVimPortType();
    ManagedObjectReference serviceInstance = connectionResources.getServiceInstance();
    ServiceContent serviceContent = vimPort.retrieveServiceContent(serviceInstance);
    ManagedObjectReference propertyCollectorReference = serviceContent.getPropertyCollector();
    RetrieveOptions propertyObjectRetrieveOptions = new RetrieveOptions();
    List<ObjectContent> objectContentList = new ArrayList<>();

    RetrieveResult results = vimPort.retrievePropertiesEx(propertyCollectorReference,
            propertyFilterSpecList,
            propertyObjectRetrieveOptions);

    if (results != null && results.getObjects() != null && !results.getObjects().isEmpty()) {
        objectContentList.addAll(results.getObjects());
    }

    String token = null;
    if (results != null && results.getToken() != null) {
        token = results.getToken();
    }

    while (token != null && !token.isEmpty()) {
        results = vimPort.continueRetrievePropertiesEx(propertyCollectorReference, token);
        token = null;
        if (results != null) {
            token = results.getToken();
            if (results.getObjects() != null && !results.getObjects().isEmpty()) {
                objectContentList.addAll(results.getObjects());
            }
        }
    }

    return objectContentList;
}
 
Example #6
Source File: VM.java    From development with Apache License 2.0 5 votes vote down vote up
public TaskInfo updateCommentField(String comment) throws Exception {
    LOG.debug("instanceName: " + instanceName + " comment: " + comment);
    VimPortType service = vmw.getConnection().getService();
    VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
    String annotation = vmConfigSpec.getAnnotation();
    comment = updateComment(comment, annotation);
    vmConfigSpec.setAnnotation(comment);
    LOG.debug("Call vSphere API: reconfigVMTask()");
    ManagedObjectReference reconfigureTask = service
            .reconfigVMTask(vmInstance, vmConfigSpec);

    return (TaskInfo) vmw.getServiceUtil()
            .getDynamicProperty(reconfigureTask, "info");
}
 
Example #7
Source File: VimUtil.java    From vsphere-automation-sdk-java with MIT License 5 votes vote down vote up
/**
 * Uses the new RetrievePropertiesEx method to emulate the now deprecated
 * RetrieveProperties method.
 *
 * @param listpfs
 * @return list of object content
 * @throws Exception
 */
public static List<ObjectContent> retrievePropertiesAllObjects(
        VimPortType vimPort, ManagedObjectReference propCollectorRef,
        List<PropertyFilterSpec> listpfs)
        throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
    RetrieveOptions propObjectRetrieveOpts = new RetrieveOptions();
    List<ObjectContent> listobjcontent = new ArrayList<ObjectContent>();

    RetrieveResult rslts = vimPort.retrievePropertiesEx(propCollectorRef,
            listpfs, propObjectRetrieveOpts);
    if (rslts != null && rslts.getObjects() != null
            && !rslts.getObjects().isEmpty()) {
        listobjcontent.addAll(rslts.getObjects());
    }
    String token = null;
    if (rslts != null && rslts.getToken() != null) {
        token = rslts.getToken();
    }
    while (token != null && !token.isEmpty()) {
        rslts = vimPort.continueRetrievePropertiesEx(propCollectorRef,
                token);
        token = null;
        if (rslts != null) {
            token = rslts.getToken();
            if (rslts.getObjects() != null
                    && !rslts.getObjects().isEmpty()) {
                listobjcontent.addAll(rslts.getObjects());
            }
        }
    }

    return listobjcontent;
}
 
Example #8
Source File: VM.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * Reconfigures VMware instance. Memory, CPU, disk space and network
 * adapter. The VM has been created and must be stopped to reconfigure the
 * hardware.
 */
public TaskInfo reconfigureVirtualMachine(VMPropertyHandler paramHandler)
        throws Exception {
    LOG.debug("instanceName: " + instanceName);

    VimPortType service = vmw.getConnection().getService();
    VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();

    vmConfigSpec
            .setMemoryMB(Long.valueOf(paramHandler.getConfigMemoryMB()));
    vmConfigSpec.setNumCPUs(Integer.valueOf(paramHandler.getConfigCPUs()));

    String reqUser = paramHandler
            .getServiceSetting(VMPropertyHandler.REQUESTING_USER);

    String comment = Messages.get(paramHandler.getLocale(), "vm_comment",
            new Object[] { paramHandler.getSettings().getOrganizationName(),
                    paramHandler.getSettings().getSubscriptionId(),
                    reqUser });
    String annotation = vmConfigSpec.getAnnotation();
    comment = updateComment(comment, annotation);
    vmConfigSpec.setAnnotation(comment);

    DiskManager diskManager = new DiskManager(vmw, paramHandler);
    diskManager.reconfigureDisks(vmConfigSpec, vmInstance);

    NetworkManager.configureNetworkAdapter(vmw, vmConfigSpec, paramHandler,
            vmInstance);

    LOG.debug("Call vSphere API: reconfigVMTask()");
    ManagedObjectReference reconfigureTask = service
            .reconfigVMTask(vmInstance, vmConfigSpec);

    return (TaskInfo) vmw.getServiceUtil()
            .getDynamicProperty(reconfigureTask, "info");
}
 
Example #9
Source File: VimUtil.java    From vsphere-automation-sdk-java with MIT License 5 votes vote down vote up
/**
 * Get the required properties of the specified object.
 *
 * @param vimPort
 * @param serviceContent
 * @param moRef
 * @param type
 * @param properties
 * @return
 * @throws RuntimeFaultFaultMsg
 * @throws InvalidPropertyFaultMsg
 */
public static List<DynamicProperty> getProperties(VimPortType vimPort,
        ServiceContent serviceContent, ManagedObjectReference moRef,
        String type, List<String> properties)
        throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg {
    // Create Property Spec
    PropertySpec propertySpec = new PropertySpec();
    propertySpec.setAll(false);
    propertySpec.setType(type);
    propertySpec.getPathSet().addAll(properties);

    // Now create Object Spec
    ObjectSpec objectSpec = new ObjectSpec();
    objectSpec.setObj(moRef);
    objectSpec.setSkip(false);

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

    List<PropertyFilterSpec> listpfs = new ArrayList<PropertyFilterSpec>(1);
    listpfs.add(propertyFilterSpec);
    List<ObjectContent> listobjcontent = VimUtil
            .retrievePropertiesAllObjects(vimPort,
                    serviceContent.getPropertyCollector(), listpfs);
    assert listobjcontent != null && listobjcontent.size() > 0;
    ObjectContent contentObj = listobjcontent.get(0);
    List<DynamicProperty> objList = contentObj.getPropSet();
    return objList;
}
 
Example #10
Source File: VMwareClient.java    From development with Apache License 2.0 4 votes vote down vote up
public VimPortType getService() {
    return getConnection().getService();
}
 
Example #11
Source File: VMwareUtil.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public static Map<String, ManagedObjectReference> getVms(VMwareConnection connection) throws Exception {
    Map<String, ManagedObjectReference> nameToVm = new HashMap<>();

    ManagedObjectReference rootFolder = connection.getServiceContent().getRootFolder();

    TraversalSpec tSpec = getVMTraversalSpec();

    PropertySpec propertySpec = new PropertySpec();

    propertySpec.setAll(Boolean.FALSE);
    propertySpec.getPathSet().add("name");
    propertySpec.setType("VirtualMachine");

    ObjectSpec objectSpec = new ObjectSpec();

    objectSpec.setObj(rootFolder);
    objectSpec.setSkip(Boolean.TRUE);
    objectSpec.getSelectSet().add(tSpec);

    PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec();

    propertyFilterSpec.getPropSet().add(propertySpec);
    propertyFilterSpec.getObjectSet().add(objectSpec);

    List<PropertyFilterSpec> lstPfs = new ArrayList<>(1);

    lstPfs.add(propertyFilterSpec);

    VimPortType vimPortType = connection.getVimPortType();
    ManagedObjectReference propertyCollector = connection.getServiceContent().getPropertyCollector();

    List<ObjectContent> lstObjectContent = retrievePropertiesAllObjects(lstPfs, vimPortType, propertyCollector);

    if (lstObjectContent != null) {
        for (ObjectContent oc : lstObjectContent) {
            ManagedObjectReference mor = oc.getObj();
            List<DynamicProperty> dps = oc.getPropSet();
            String vmName = null;

            if (dps != null) {
                for (DynamicProperty dp : dps) {
                    vmName = (String)dp.getVal();
                }
            }

            if (vmName != null) {
                nameToVm.put(vmName, mor);
            }
        }
    }

    return nameToVm;
}
 
Example #12
Source File: DeployOvfTemplateService.java    From cs-actions with Apache License 2.0 4 votes vote down vote up
private ManagedObjectReference getOvfManager(final ConnectionResources connectionResources) throws RuntimeFaultFaultMsg {
    final VimPortType vimPort = connectionResources.getVimPortType();
    final ManagedObjectReference serviceInstance = connectionResources.getServiceInstance();
    final ServiceContent serviceContent = vimPort.retrieveServiceContent(serviceInstance);
    return serviceContent.getOvfManager();
}
 
Example #13
Source File: ConnectionResources.java    From cs-actions with Apache License 2.0 4 votes vote down vote up
public VimPortType getVimPortType() {
    return vimPortType;
}
 
Example #14
Source File: BasicConnection.java    From cs-actions with Apache License 2.0 4 votes vote down vote up
public VimPortType getVimPort() {
    return vimPort;
}
 
Example #15
Source File: VmwareContext.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public VimPortType getService() {
    return _vimClient.getService();
}
 
Example #16
Source File: VmwareClient.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
/**
 * @return Service instance
 */
public VimPortType getService() {
    return vimPort;
}
 
Example #17
Source File: VMwareUtil.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
VMwareConnection(VimPortType vimPortType, ServiceContent serviceContent) {
    _vimPortType = vimPortType;
    _serviceContent = serviceContent;
}
 
Example #18
Source File: VMwareUtil.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
VimPortType getVimPortType() {
    return _vimPortType;
}
 
Example #19
Source File: WaitForValues.java    From vsphere-automation-sdk-java with MIT License 4 votes vote down vote up
public WaitForValues(VimPortType vimPort, ServiceContent serviceContent) {
    this.vimPort = vimPort;
    this.serviceContent = serviceContent;
}
 
Example #20
Source File: VMwareClient.java    From development with Apache License 2.0 4 votes vote down vote up
/**
 * Establish a connection to the vCenter.
 */
public void connect() throws Exception {
    // FIXME what to do?
    HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(String urlHostName, SSLSession session) {
            return true;
        }
    };

    int numFailedLogins = 0;
    boolean repeatLogin = true;

    while (repeatLogin) {
        try {
            HttpsURLConnection.setDefaultHostnameVerifier(hv);

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

            ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url);
            ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY,
                    Boolean.TRUE);

            ManagedObjectReference morSvcInstance = new ManagedObjectReference();
            morSvcInstance.setType("ServiceInstance");
            morSvcInstance.setValue("ServiceInstance");
            ServiceContent serviceContent = vimPort
                    .retrieveServiceContent(morSvcInstance);
            vimPort.login(serviceContent.getSessionManager(), user,
                    password, null);
            connection = new ServiceConnection(vimPort, serviceContent);
            LOG.debug("Established connection to vSphere. URL: " + url
                    + ", UserId: " + user);

            repeatLogin = false;
        } catch (Exception e) {
            LOG.error("Failed to establish connection to vSphere. URL: "
                    + url + ", UserId: " + user, e);
            if (numFailedLogins > 2) {
                throw e;
            }
            numFailedLogins++;
            repeatLogin = true;
            try {
                Thread.sleep(3000);
            } catch (@SuppressWarnings("unused") InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
        }
    }
}
 
Example #21
Source File: ServiceConnection.java    From development with Apache License 2.0 4 votes vote down vote up
public ServiceConnection(VimPortType service, ServiceContent content) {
    this.service = service;
    this.content = content;
}
 
Example #22
Source File: Script.java    From development with Apache License 2.0 4 votes vote down vote up
public void execute(VMwareClient vmw, ManagedObjectReference vmwInstance)
        throws Exception {

    LOG.debug("");

    String vcenter = ph
            .getServiceSetting(VMPropertyHandler.TS_TARGET_VCENTER_SERVER);
    VimPortType vimPort = vmw.getConnection().getService();
    ServiceConnection conn = new ServiceConnection(vimPort, vmw
            .getConnection().getServiceContent());
    ManagedObjectAccessor moa = new ManagedObjectAccessor(conn);
    ManagedObjectReference guestOpManger = vmw.getConnection()
            .getServiceContent().getGuestOperationsManager();
    ManagedObjectReference fileManagerRef = (ManagedObjectReference) moa
            .getDynamicProperty(guestOpManger, "fileManager");
    ManagedObjectReference processManagerRef = (ManagedObjectReference) moa
            .getDynamicProperty(guestOpManger, "processManager");

    NamePasswordAuthentication auth = new NamePasswordAuthentication();
    auth.setUsername(guestUserId);
    auth.setPassword(guestPassword);
    auth.setInteractiveSession(false);

    String scriptPatched = insertServiceParameter();

    DataAccessService das = new DataAccessService(ph.getLocale());
    URL vSphereURL = new URL(das.getCredentials(vcenter).getURL());

    uploadScriptFileToVM(vimPort, vmwInstance, fileManagerRef, auth,
            scriptPatched, vSphereURL.getHost());
    LOG.debug("Executing CreateTemporaryFile guest operation");
    String tempFilePath = vimPort.createTemporaryFileInGuest(
            fileManagerRef, vmwInstance, auth, "", "", "");
    LOG.debug("Successfully created a temporary file at: " + tempFilePath
            + " inside the guest");

    GuestProgramSpec spec = new GuestProgramSpec();

    if (os == OS.WINDOWS) {
        spec.setProgramPath(WINDOWS_GUEST_FILE_PATH);
        spec.setArguments(" > " + tempFilePath);
    } else {
        spec.setProgramPath(LINUX_GUEST_FILE_PATH);
        spec.setArguments(" > " + tempFilePath + " 2>&1");
    }

    LOG.debug("Starting the specified program inside the guest");
    long pid = vimPort.startProgramInGuest(processManagerRef, vmwInstance,
            auth, spec);
    LOG.debug("Process ID of the program started is: " + pid + "");

    List<GuestProcessInfo> procInfo = null;
    List<Long> pidsList = new ArrayList<Long>();
    pidsList.add(Long.valueOf(pid));
    do {
        LOG.debug("Waiting for the process to finish running.");
        try {
            procInfo = vimPort.listProcessesInGuest(processManagerRef,
                    vmwInstance, auth, pidsList);
        } catch (Exception e) {
            LOG.warn(
                    "listProcessesInGuest() failed. setting new Linux root password for authentication",
                    e);

            if (os == OS.WINDOWS) {
                auth.setPassword(ph
                        .getServiceSetting(VMPropertyHandler.TS_WINDOWS_LOCAL_ADMIN_PWD));
            } else {
                auth.setPassword(ph
                        .getServiceSetting(VMPropertyHandler.TS_LINUX_ROOT_PWD));
            }
        }
        Thread.sleep(5 * 1000);
    } while (procInfo != null && procInfo.get(0).getEndTime() == null);

    if (procInfo != null && procInfo.get(0).getExitCode().intValue() != 0) {
        LOG.error("Script return code: " + procInfo.get(0).getExitCode());
        FileTransferInformation fileTransferInformation = null;
        fileTransferInformation = vimPort.initiateFileTransferFromGuest(
                fileManagerRef, vmwInstance, auth, tempFilePath);
        String fileDownloadUrl = fileTransferInformation.getUrl()
                .replaceAll("\\*", vSphereURL.getHost());
        LOG.debug("Downloading the output file from :" + fileDownloadUrl);
        String scriptOutput = downloadFile(fileDownloadUrl);
        LOG.error("Script execution output: " + scriptOutput);
    }

}
 
Example #23
Source File: VimAuthenticationHelper.java    From vsphere-automation-sdk-java with MIT License 4 votes vote down vote up
public VimPortType getVimPort() {
    return this.vimPort;
}
 
Example #24
Source File: VimUtil.java    From vsphere-automation-sdk-java with MIT License 4 votes vote down vote up
/**
 * Getting the MOREF of the entity.
 */
public static ManagedObjectReference getEntityByName(
        VimPortType vimPortType, ServiceContent serviceContent,
        String entityName, String entityType) {
    ManagedObjectReference propCollectorRef = serviceContent
            .getPropertyCollector();
    ManagedObjectReference rootFolderRef = serviceContent.getRootFolder();
    ManagedObjectReference retVal = null;

    try {
        // Create Property Spec
        PropertySpec propertySpec = new PropertySpec();
        propertySpec.setAll(Boolean.FALSE);
        propertySpec.setType(entityType);
        propertySpec.getPathSet().add("name");

        // Now create Object Spec
        ObjectSpec objectSpec = new ObjectSpec();
        objectSpec.setObj(rootFolderRef);
        objectSpec.setSkip(Boolean.TRUE);
        objectSpec.getSelectSet().addAll(Arrays.asList(buildTraversal()));

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

        List<PropertyFilterSpec> listpfs =
                new ArrayList<PropertyFilterSpec>(1);
        listpfs.add(propertyFilterSpec);
        List<ObjectContent> listobjcont = retrievePropertiesAllObjects(
                vimPortType, propCollectorRef, listpfs);
        if (listobjcont != null) {
            for (ObjectContent oc : listobjcont) {
                if (oc.getPropSet().get(0).getVal().equals(entityName)) {
                    retVal = oc.getObj();
                    break;
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return retVal;
}
 
Example #25
Source File: VimUtil.java    From vsphere-automation-sdk-java with MIT License 4 votes vote down vote up
/**
 * Retrieves the vm managed object reference for the specified vm name using
 * the vim port type.
 *
 * @param vimPortType
 * @param serviceContent
 * @param vmname
 * @return
 * @throws NotFoundFaultMsg
 * @throws RuntimeFaultFaultMsg
 * @throws InvalidPropertyFaultMsg
 */
public static ManagedObjectReference getVM(VimPortType vimPortType,
        ServiceContent serviceContent, String vmname)
        throws NotFoundFaultMsg, InvalidPropertyFaultMsg,
        RuntimeFaultFaultMsg {
    ManagedObjectReference propCollectorRef = serviceContent
            .getPropertyCollector();
    ManagedObjectReference rootFolderRef = serviceContent.getRootFolder();

    ManagedObjectReference retVmRef = null;
    TraversalSpec tSpec = getVMTraversalSpec();

    PropertySpec propertySpec = new PropertySpec();
    propertySpec.setAll(Boolean.FALSE);
    propertySpec.getPathSet().add("name");
    propertySpec.setType("VirtualMachine");

    ObjectSpec objectSpec = new ObjectSpec();
    objectSpec.setObj(rootFolderRef);
    objectSpec.setSkip(Boolean.TRUE);
    objectSpec.getSelectSet().add(tSpec);

    PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec();
    propertyFilterSpec.getPropSet().add(propertySpec);
    propertyFilterSpec.getObjectSet().add(objectSpec);

    List<PropertyFilterSpec> listpfs = new ArrayList<PropertyFilterSpec>(1);
    listpfs.add(propertyFilterSpec);
    List<ObjectContent> listobjcont = retrievePropertiesAllObjects(
            vimPortType, propCollectorRef, listpfs);

    if (listobjcont != null) {
        for (ObjectContent oc : listobjcont) {
            ManagedObjectReference mr = oc.getObj();
            String vmnm = null;
            List<DynamicProperty> dps = oc.getPropSet();
            if (dps != null) {
                for (DynamicProperty dp : dps) {
                    vmnm = (String) dp.getVal();
                }
            }
            if (vmnm != null && vmnm.equals(vmname)) {
                retVmRef = mr;
                break;
            }
        }
    }
    if (retVmRef == null) {
        throw new NotFoundFaultMsg("VM Not Found - " + vmname,
                new NotFound());
    }
    return retVmRef;
}
 
Example #26
Source File: VimUtil.java    From vsphere-automation-sdk-java with MIT License 4 votes vote down vote up
/**
 * Retrieves the list of hosts of the given cluster.
 *
 * @param vimPort
 *            vimPort
 * @param serviceContent
 *            serviceContent
 * @param cluster
 *            cluster
 * @return the list of hosts of the clusters
 * @throws InvalidPropertyFaultMsg
 * @throws RuntimeFaultFaultMsg
 */
public static List<ManagedObjectReference> getHosts(VimPortType vimPort,
        ServiceContent serviceContent, ManagedObjectReference cluster)
        throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
    PropertySpec hostPropSpec = new PropertySpec();
    hostPropSpec.setType("HostSystem");
    hostPropSpec.setAll(false);
    hostPropSpec.getPathSet().addAll(Collections.<String>emptyList());

    TraversalSpec hostTSpec = new TraversalSpec();
    hostTSpec.setType("ComputeResource");
    hostTSpec.setPath("host");
    hostTSpec.setName("hosts");

    final SelectionSpec selectionSpec = new SelectionSpec();
    selectionSpec.setName(hostTSpec.getName());

    hostTSpec.getSelectSet().add(selectionSpec);

    List<ObjectSpec> ospecList = new ArrayList<>();
    ObjectSpec ospec = new ObjectSpec();
    ospec.setObj(cluster);
    ospec.setSkip(true);
    ospec.getSelectSet().addAll(Arrays.asList(hostTSpec));
    ospecList.add(ospec);

    PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec();
    propertyFilterSpec.getPropSet().addAll(Arrays.asList(hostPropSpec));
    propertyFilterSpec.getObjectSet().addAll(ospecList);

    List<PropertyFilterSpec> listpfs = new ArrayList<>(1);
    listpfs.add(propertyFilterSpec);
    List<ObjectContent> listObjContent = VimUtil
            .retrievePropertiesAllObjects(vimPort,
                    serviceContent.getPropertyCollector(), listpfs);

    List<ManagedObjectReference> hosts = new ArrayList<>();

    if (listObjContent != null) {
        for (ObjectContent oc : listObjContent) {
            hosts.add(oc.getObj());
        }
    }
    return hosts;
}
 
Example #27
Source File: VimUtil.java    From vsphere-automation-sdk-java with MIT License 4 votes vote down vote up
/**
 * Retrieves the cluster managed object reference for the specified cluster
 * name using the vim port type.
 *
 * @param vimPortType
 *
 * @param serviceContent
 *            {@link ServiceContent}
 * @param clusterName
 *            name of the cluster to be searched for.
 * @return {@link ManagedObjectReference}
 * @throws InvalidPropertyFaultMsg
 * @throws RuntimeFaultFaultMsg
 * @throws NotFoundFaultMsg
 */
public static ManagedObjectReference getCluster(VimPortType vimPortType,
        ServiceContent serviceContent, String clusterName)
        throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg,
        NotFoundFaultMsg {

    // Spec to allow recursion on the Folder to Folder traversal
    SelectionSpec folderToFolderSelection = new SelectionSpec();
    folderToFolderSelection.setName("folderToFolder");

    SelectionSpec dcToHostFolderSelection = new SelectionSpec();
    dcToHostFolderSelection.setName("dcToHostFolder");

    // spec to traverse from Datacenter to hostFolder
    TraversalSpec dcToHostFolderTraversal = new TraversalSpec();
    dcToHostFolderTraversal.setName("dcToHostFolder");
    dcToHostFolderTraversal.setPath("hostFolder");
    dcToHostFolderTraversal.setType("Datacenter");
    dcToHostFolderTraversal.getSelectSet().addAll(
            Arrays.asList(new SelectionSpec[] { folderToFolderSelection }));
    dcToHostFolderTraversal.setSkip(false);

    // spec to traverse from Folder to a child folder
    TraversalSpec folderToFolderTraversal = new TraversalSpec();
    folderToFolderTraversal.setName("folderToFolder");
    folderToFolderTraversal.setPath("childEntity");
    folderToFolderTraversal.setType("Folder");
    folderToFolderTraversal.getSelectSet()
            .addAll(Arrays.asList(new SelectionSpec[] {
                folderToFolderSelection, dcToHostFolderSelection }));
    folderToFolderTraversal.setSkip(false);

    PropertySpec propertySpec = new PropertySpec();
    propertySpec.getPathSet()
            .addAll(Arrays.asList(new String[] { "name" }));
    propertySpec.setType("ClusterComputeResource");

    ObjectSpec objectSpec = new ObjectSpec();
    objectSpec.setObj(serviceContent.getRootFolder());
    objectSpec.getSelectSet().addAll(Arrays.asList(new SelectionSpec[] {
        folderToFolderTraversal, dcToHostFolderTraversal }));
    objectSpec.setSkip(false);

    // Create PropertyFilterSpec using the PropertySpec and ObjectPec
    PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec();
    propertyFilterSpec.getPropSet()
            .addAll(Arrays.asList(new PropertySpec[] { propertySpec }));
    propertyFilterSpec.getObjectSet()
            .addAll(Arrays.asList(new ObjectSpec[] { objectSpec }));

    ManagedObjectReference morPropertyCollector = serviceContent
            .getPropertyCollector();
    List<ObjectContent> objectContents = vimPortType.retrieveProperties(
            morPropertyCollector,
            Arrays.asList(new PropertyFilterSpec[] { propertyFilterSpec }));

    for (ObjectContent objectContent : objectContents) {
        ManagedObjectReference clusterManagedObjectReference = objectContent
                .getObj();
        List<DynamicProperty> dynamicProperties = objectContent
                .getPropSet();
        for (DynamicProperty dynamicProperty : dynamicProperties) {
            if (dynamicProperty.getName().equalsIgnoreCase("name")) {
                if (dynamicProperty.getVal().toString()
                        .equalsIgnoreCase(clusterName)) {
                    return clusterManagedObjectReference;
                }
            }
        }
    }
    throw new NotFoundFaultMsg("Cluster Not Found - " + clusterName,
            new NotFound());
}
 
Example #28
Source File: VmVappPowerOps.java    From vsphere-automation-sdk-java with MIT License 4 votes vote down vote up
public VmVappPowerOps(VimPortType vimPort, ServiceContent serviceContent) {
    this.vimPort = vimPort;
    this.serviceContent = serviceContent;
    this.waitForValues = new WaitForValues(vimPort, serviceContent);
}
 
Example #29
Source File: VMwareUtil.java    From cloudstack with Apache License 2.0 3 votes vote down vote up
public static VMwareConnection getVMwareConnection(LoginInfo loginInfo) throws Exception {
    trustAllHttpsCertificates();

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

    HttpsURLConnection.setDefaultHostnameVerifier(hv);

    ManagedObjectReference serviceInstanceRef = new ManagedObjectReference();

    final String serviceInstanceName = "ServiceInstance";

    serviceInstanceRef.setType(serviceInstanceName);
    serviceInstanceRef.setValue(serviceInstanceName);

    VimService vimService = new VimService();

    VimPortType vimPortType = vimService.getVimPort();

    Map<String, Object> ctxt = ((BindingProvider)vimPortType).getRequestContext();

    ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "https://" + loginInfo.getHost() + "/sdk");
    ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);

    ServiceContent serviceContent = vimPortType.retrieveServiceContent(serviceInstanceRef);

    vimPortType.login(serviceContent.getSessionManager(), loginInfo.getUsername(), loginInfo.getPassword(), null);

    return new VMwareConnection(vimPortType, serviceContent);
}
 
Example #30
Source File: ServiceConnection.java    From development with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the service interface of the connection.
 *
 * @return the service interface
 */
public VimPortType getService() {
    return service;
}