Java 类com.vmware.vim25.mo.ManagedEntity 实例源码

项目:jcloud-vsphere    文件:VSphereComputeServiceAdapter.java   
private Optional<ResourcePool> tryFindResourcePool(Folder folder, String hostname) {
   Iterable<ResourcePool> resourcePools = ImmutableSet.<ResourcePool>of();
   try {
      ManagedEntity[] resourcePoolEntities = new InventoryNavigator(folder).searchManagedEntities("ResourcePool");
      resourcePools = Iterables.transform(Arrays.asList(resourcePoolEntities), new Function<ManagedEntity, ResourcePool>() {
         public ResourcePool apply(ManagedEntity input) {
            return (ResourcePool) input;
         }
      });
      Optional<ResourcePool> optionalResourcePool = Iterables.tryFind(resourcePools, VSpherePredicate.isResourcePoolOf(hostname));
      return optionalResourcePool;
   } catch (Exception e) {
      logger.error("Problem in finding a valid resource pool", e);
   }
   return Optional.absent();
}
项目:jcloud-vsphere    文件:VSphereLocationSupplier.java   
private Set<? extends Location> getClusters() {
   Set<Location> hosts = Sets.newHashSet();
   try (VSphereServiceInstance instance = serviceInstance.get();) {

      ManagedEntity[] clusterEntities = new InventoryNavigator(instance.getInstance().getRootFolder()).searchManagedEntities("ClusterComputeResource");

      for (ManagedEntity cluster : clusterEntities) {
         Location location = new LocationImpl(LocationScope.ZONE, cluster.getName(), cluster.getName(), null, ImmutableSet.of(""), Maps.<String, Object>newHashMap());
         hosts.add(location);
      }

      hosts.add(new LocationImpl(LocationScope.ZONE, "default", "default", null, ImmutableSet.of(""), Maps.<String, Object>newHashMap()));

      return hosts;
   } catch (Exception e) {
      logger.error("Problem in finding a valid cluster", e);
      Throwables.propagateIfPossible(e);
   }
   return hosts;
}
项目:primecloud-controller    文件:VmwareNetworkProcess.java   
/**
 * TODO: メソッドコメントを記述
 *
 * @param vmwareProcessClient
 * @param networkNo
 * @param instanceNo
 */
public void addNetwork(VmwareProcessClient vmwareProcessClient, Long networkNo, Long instanceNo) {
    VmwareNetwork vmwareNetwork = vmwareNetworkDao.read(networkNo);

    // HostSystemを取得
    VmwareClient vmwareClient = vmwareProcessClient.getVmwareClient();
    ManagedEntity[] hostSystems;
    if (instanceNo == null) {
        hostSystems = vmwareClient.searchByType(HostSystem.class);
    } else {
        VmwareInstance vmwareInstance = vmwareInstanceDao.read(instanceNo);
        ComputeResource computeResource = vmwareClient.search(ComputeResource.class,
                vmwareInstance.getComputeResource());
        hostSystems = vmwareClient.searchByType(computeResource, HostSystem.class);
    }

    // ネットワークを追加
    for (ManagedEntity entity : hostSystems) {
        HostSystem hostSystem = HostSystem.class.cast(entity);
        vmwareProcessClient.addNetwork(hostSystem.getName(), vmwareNetwork.getNetworkName(),
                vmwareNetwork.getVlanId(), vmwareNetwork.getVswitchName());
    }
}
项目:primecloud-controller    文件:VmwareNetworkProcess.java   
/**
 * TODO: メソッドコメントを記述
 *
 * @param vmwareProcessClient
 * @param networkNo
 * @param instanceNo
 */
public void removeNetwork(VmwareProcessClient vmwareProcessClient, Long networkNo, Long instanceNo) {
    VmwareNetwork vmwareNetwork = vmwareNetworkDao.read(networkNo);

    // HostSystemを取得
    VmwareClient vmwareClient = vmwareProcessClient.getVmwareClient();
    ManagedEntity[] hostSystems;
    if (instanceNo == null) {
        hostSystems = vmwareClient.searchByType(HostSystem.class);
    } else {
        VmwareInstance vmwareInstance = vmwareInstanceDao.read(instanceNo);
        ComputeResource computeResource = vmwareClient.search(ComputeResource.class,
                vmwareInstance.getComputeResource());
        hostSystems = vmwareClient.searchByType(computeResource, HostSystem.class);
    }

    // ネットワークを除去
    for (ManagedEntity entity : hostSystems) {
        HostSystem hostSystem = HostSystem.class.cast(entity);
        vmwareProcessClient.removeNetwork(hostSystem.getName(), vmwareNetwork.getNetworkName());
    }
}
项目:vijava    文件:RealtimePerfMonitor.java   
static PerfQuerySpec createPerfQuerySpec(ManagedEntity me, 
      PerfMetricId[] metricIds, int maxSample, int interval)
  {
    PerfQuerySpec qSpec = new PerfQuerySpec();
    qSpec.setEntity(me.getMOR());
    // set the maximum of metrics to be return
    // only appropriate in real-time performance collecting
    qSpec.setMaxSample(new Integer(maxSample));
//    qSpec.setMetricId(metricIds);
    // optionally you can set format as "normal"
    qSpec.setFormat("csv");
    // set the interval to the refresh rate for the entity
    qSpec.setIntervalId(new Integer(interval));

    return qSpec;
  }
项目:vmware-vsphere-monitoring-extension    文件:VMWareMonitor.java   
private void populateMetrics(Folder rootFolder, List<Map<String, Object>> hostConfigs, Map<Pattern, String> replacers, Integer hostThreads, Integer vmThreads) {

        List<ManagedEntity> hostEntities = getHostMachines(rootFolder, hostConfigs);

        if (logger.isDebugEnabled()) {
            logger.debug("Found " + hostEntities.size() + " hosts");
            StringBuilder sb = new StringBuilder();
            for (ManagedEntity managedEntity : hostEntities) {
                if (sb.length() > 0) {
                    sb.append(",");
                }
                sb.append(managedEntity.getName());
            }
            logger.debug("Host machines [ " + sb.toString() + " ]");
        }

        HostMetricCollector hostMetricCollector = new HostMetricCollector(configuration.getMetricWriter(), configuration.getMetricPrefix(), hostEntities, hostConfigs, replacers, hostThreads, vmThreads);
        hostMetricCollector.execute();
    }
项目:vmware-vsphere-monitoring-extension    文件:VMWareMonitor.java   
private List<ManagedEntity> getHostMachines(Folder rootFolder, List<Map<String, Object>> hostConfigs) {
    List<ManagedEntity> hostEntities = new ArrayList<ManagedEntity>();

    for (Map<String, Object> hostConfig : hostConfigs) {
        String hostName = (String) hostConfig.get("host");
        try {
            if ("*".equals(hostName)) {
                hostEntities = Arrays.asList(new InventoryNavigator(rootFolder).searchManagedEntities("HostSystem"));
            } else {
                ManagedEntity hostSystem = new InventoryNavigator(rootFolder).searchManagedEntity("HostSystem", hostName);
                if (hostSystem != null) {
                    hostEntities.add(hostSystem);
                } else {
                    logger.error("Could not find Host with name " + hostName);
                }
            }
        } catch (InvalidProperty invalidProperty) {
            logger.error("Unable to get the host details", invalidProperty);
        } catch (RuntimeFault runtimeFault) {
            logger.error("Unable to get the host details", runtimeFault);
        } catch (RemoteException e) {
            logger.error("Unable to get the host details", e);
        }
    }
    return hostEntities;
}
项目:jcloud-vsphere    文件:VSphereComputeServiceAdapter.java   
private Iterable<VirtualMachine> listNodes(VSphereServiceInstance instance) {
   Iterable<VirtualMachine> vms = ImmutableSet.of();
   try {
      Folder nodesFolder = instance.getInstance().getRootFolder();
      ManagedEntity[] managedEntities = new InventoryNavigator(nodesFolder).searchManagedEntities("VirtualMachine");
      vms = Iterables.transform(Arrays.asList(managedEntities), new Function<ManagedEntity, VirtualMachine>() {
         public VirtualMachine apply(ManagedEntity input) {
            return (VirtualMachine) input;
         }
      });
   } catch (Throwable e) {
      logger.error("Can't find vm", e);
   }
   return vms;
}
项目:jcloud-vsphere    文件:VSphereComputeServiceAdapter.java   
@Override
   public Iterable<VirtualMachine> listNodesByIds(Iterable<String> ids) {

      Iterable<VirtualMachine> vms = ImmutableSet.of();
      try (VSphereServiceInstance instance = serviceInstance.get();) {
         Folder nodesFolder = instance.getInstance().getRootFolder();
         List<List<String>> list = new ArrayList<List<String>>();
         Iterator<String> idsIterator = ids.iterator();

         while (idsIterator.hasNext()) {
            list.add(Lists.newArrayList("VirtualMachine", idsIterator.next()));
         }

         String[][] typeInfo = ListsUtils.ListToArray(list);

         ManagedEntity[] managedEntities = new InventoryNavigator(nodesFolder).searchManagedEntities(
                 typeInfo, true);
         vms = Iterables.transform(Arrays.asList(managedEntities), new Function<ManagedEntity, VirtualMachine>() {
            public VirtualMachine apply(ManagedEntity input) {
               return (VirtualMachine) input;
            }
         });
      } catch (Throwable e) {
         logger.error("Can't find vms ", e);
      }
      return vms;


//      Iterable<VirtualMachine> nodes = listNodes();
//      Iterable<VirtualMachine> selectedNodes = Iterables.filter(nodes, VSpherePredicate.isNodeIdInList(ids));
//      return selectedNodes;
   }
项目:jcloud-vsphere    文件:VSphereHostSupplier.java   
private HostSystem getSystemHost() {
   Iterable<HostSystem> hosts = ImmutableSet.<HostSystem>of();
   try {
      VSphereServiceInstance instance = serviceInstance.get();
      ManagedEntity[] hostEntities = new InventoryNavigator(instance.getInstance().getRootFolder()).searchManagedEntities("HostSystem");
      hosts = Iterables.transform(Arrays.asList(hostEntities), new Function<ManagedEntity, HostSystem>() {
         public HostSystem apply(ManagedEntity input) {
            return (HostSystem) input;
         }
      });

      HostSystem curHostSystem = null;
      long maxMemory = Integer.MIN_VALUE;
      for (HostSystem hostSystem : hosts) {
         int currentMemory = hostSystem.getSummary().getQuickStats().getOverallMemoryUsage();
         long currentTotalMemory = hostSystem.getConfig().getSystemResources().getConfig().getMemoryAllocation().getLimit();
         if (currentTotalMemory - currentMemory > maxMemory) {
            curHostSystem = hostSystem;
            maxMemory = currentTotalMemory - currentMemory;
         }
      }

      return curHostSystem;
   } catch (Exception e) {
      logger.error("Problem in finding a valid host: " + e.toString(), e);
   }
   return null;
}
项目:jcloud-vsphere    文件:FolderNameToFolderManagedEntity.java   
@Override
public Folder apply(final String folderName) {
   try {
      if (Strings.isNullOrEmpty(folderName))
         return (Folder) master.getParent();
      VSphereServiceInstance instance = serviceInstance.get();
      ManagedEntity entity = new InventoryNavigator(instance.getInstance().getRootFolder()).searchManagedEntity("Folder", folderName);
      return (Folder) entity;
   } catch (Exception e) {
      logger.error("Problem in finding a valid Folder with name " + folderName, e);
   }
   return (Folder) master.getParent();
}
项目:jcloud-vsphere    文件:GetRecommendedVSphereHost.java   
@Nullable
   @Override
   public VSphereHost apply(@Nullable String dataCenter) {
      try (VSphereServiceInstance instance = serviceInstance.get();) {

         ManagedEntity[] clusterEntities = new InventoryNavigator(instance.getInstance().getRootFolder()).searchManagedEntities("ClusterComputeResource");
         Iterable<ClusterComputeResource> clusterComputeResources = Iterables.transform(Arrays.asList(clusterEntities), new Function<ManagedEntity, ClusterComputeResource>() {
            public ClusterComputeResource apply(ManagedEntity input) {
               return (ClusterComputeResource) input;
            }
         });

         HostSystem curHostSystem = null;
         for (ClusterComputeResource cluster : clusterComputeResources) {
            if (cluster.getName().equals(dataCenter) || dataCenter.equals("default")) {
               HostSystem[] hostSystems = cluster.getHosts();
               long maxMemory = Integer.MIN_VALUE;
               for (HostSystem hostSystem : hostSystems) {
                  int currentMemory = hostSystem.getSummary().getQuickStats().getOverallMemoryUsage();
                  long currentTotalMemory = hostSystem.getConfig().getSystemResources().getConfig().getMemoryAllocation().getLimit();
                  if (currentTotalMemory - currentMemory > maxMemory) {
                     curHostSystem = hostSystem;
                     maxMemory = currentTotalMemory - currentMemory;
                  }
               }
               break;
            }
         }
         return new VSphereHost(curHostSystem.getName(), serviceInstance.get());
//         return this.systemHostToVSphereHost.apply(curHostSystem);
      } catch (Exception e) {
         logger.error("Problem in finding a valid host: " + e.toString(), e);
      }
      return null;
   }
项目:jcloud-vsphere    文件:VLanNameToDistributedVirtualPortgroup.java   
@Override
public DistributedVirtualPortgroup apply(final String vlanName) {
   try {
      VSphereServiceInstance instance = serviceInstance.get();
      ManagedEntity entity = new InventoryNavigator(instance.getInstance().getRootFolder()).searchManagedEntity("DistributedVirtualPortgroup", vlanName);
      return (DistributedVirtualPortgroup) entity;
   } catch (Exception e) {
      logger.error("Problem in finding a valid DistributedVirtualPortgroup with name " + vlanName, e);
   }
   return null;
}
项目:jcloud-vsphere    文件:VSphereHost.java   
public VSphereHost(String hostName, VSphereServiceInstance serviceInstance) {
   this.serviceInstance = checkNotNull(serviceInstance, "serviceInstance");
   try {
      ManagedEntity hostEntity = new InventoryNavigator(serviceInstance.getInstance().getRootFolder()).searchManagedEntity("HostSystem", hostName);
      this.host = checkNotNull((HostSystem)hostEntity, "host");
   } catch (RemoteException e) {
      e.printStackTrace();
   }
}
项目:teamcity-vmware-plugin    文件:VmwareApiConnectorTest.java   
private <T extends ManagedEntity> T createEntity(Class<T> type, @Nullable ManagedEntity parent, String val, String name){
  final ManagedObjectReference mor = new ManagedObjectReference();
  mor.setType(type.getSimpleName());
  mor.setVal(val);
  if (type==Folder.class){
    return (T)new Folder(null, mor){
      @Override
      public ManagedEntity getParent() {
        return parent;
      }

      @Override
      public String getName() {
        return name;
      }
    };
  }
  if (type==ResourcePool.class){
    return (T)new ResourcePool(null, mor){
      @Override
      public ManagedEntity getParent() {
        return parent;
      }

      @Override
      public String getName() {
        return name;
      }
    };
  }
  throw new IllegalArgumentException("can't create instance of type " + type.getSimpleName());
}
项目:teamcity-vmware-plugin    文件:FakeFolder.java   
public <T extends ManagedEntity> void setParent(final String parentName, Class<T> parentType) {
  if (parentType.isAssignableFrom(FakeDatacenter.class)){
    setParent(FakeModel.instance().getDatacenter(parentName));
  } else if (parentType.isAssignableFrom(Folder.class)){
    setParent(FakeModel.instance().getFolder(parentName));
  }
  if (myParent == null) {
    Assert.fail(String.format("Unable to set parent %s of type %s", parentName, parentType.getSimpleName()));
  }
}
项目:teamcity-vmware-plugin    文件:VmwareCloudIntegrationTest.java   
public void handle_instances_deleted_in_the_middle_of_check() throws MalformedURLException, VmwareCheckedCloudException {
  if (true)
    throw new SkipException("Not relevant, because we now retrieve all data at once, without additional calls");
  final Set<String> instances2RemoveAfterGet = new HashSet<>();

  myFakeApi = new FakeApiConnector(TEST_SERVER_UUID, PROFILE_ID){
    @NotNull
    @Override
    protected <T extends ManagedEntity> Map<String, T> findAllEntitiesAsMapOld(final Class<T> instanceType) throws VmwareCheckedCloudException {
      final Map<String, T> entities = super.findAllEntitiesAsMapOld(instanceType);
      final Map<String, T> result = new HashMap<String, T>();
      for (Map.Entry<String, T> entry : entities.entrySet()) {
        if (instances2RemoveAfterGet.contains(entry.getKey()) && entry.getValue() instanceof FakeVirtualMachine){
          final FakeVirtualMachine fvm = (FakeVirtualMachine) entry.getValue();
          fvm.setGone(true);
        }
        result.put(entry.getKey(), entry.getValue());
      }
      return result;
    }
  };
  final VmwareCloudInstance i1 = startNewInstanceAndWait("image2");
  final VmwareCloudInstance i2 = startNewInstanceAndWait("image2");
  final VmwareCloudInstance i3 = startNewInstanceAndWait("image2");

  instances2RemoveAfterGet.add(i1.getInstanceId());
  instances2RemoveAfterGet.add(i2.getInstanceId());

  final Map<String, AbstractInstance> image2Instances = myFakeApi.fetchInstances(getImageByName("image2"));
  assertEquals(1, image2Instances.size());
}
项目:vmstats    文件:statsGrabber.java   
private static PerfQuerySpec createPerfQuerySpec(ManagedEntity me, PerfMetricId[] metricIds, int maxSample, int interval) {
    PerfQuerySpec qSpec = new PerfQuerySpec();
    qSpec.setEntity(me.getMOR());
    // set the maximum of metrics to be return
    // only appropriate in real-time performance collecting
    qSpec.setMaxSample(new Integer(maxSample));
    //    qSpec.setMetricId(metricIds);
    // optionally you can set format as "normal"
    qSpec.setFormat("normal");
    // set the interval to the refresh rate for the entity
    qSpec.setIntervalId(new Integer(interval));

    return qSpec;
}
项目:primecloud-controller    文件:VmwareDescribeServiceImpl.java   
/**
 * {@inheritDoc}
 */
@Override
public List<ComputeResource> getComputeResources(Long platformNo) {
    PlatformVmware platformVmware = platformVmwareDao.read(platformNo);

    VmwareClientFactory factory = new VmwareClientFactory();
    factory.setUrl(platformVmware.getUrl());
    factory.setUsername(platformVmware.getUsername());
    factory.setPassword(platformVmware.getPassword());
    factory.setDatacenterName(platformVmware.getDatacenter());
    factory.setIgnoreCert(true);
    VmwareClient vmwareClient = factory.createVmwareClient();

    List<ComputeResource> computeResources = new ArrayList<ComputeResource>();

    ManagedEntity[] entities = vmwareClient.searchByType(ComputeResource.class);
    for (ManagedEntity entity : entities) {
        ComputeResource computeResource = ComputeResource.class.cast(entity);
        if (StringUtils.isNotEmpty(platformVmware.getComputeResource())
                && !StringUtils.equals(computeResource.getName(), platformVmware.getComputeResource())) {
            continue;
        }
        computeResources.add(computeResource);
    }

    // ソート
    Collections.sort(computeResources, Comparators.COMPARATOR_COMPUTE_RESOURCE);

    return computeResources;
}
项目:primecloud-controller    文件:VmwareClient.java   
/**
 * TODO: メソッドコメントを記述
 *
 * @return
 */
public ManagedEntity getRootEntity() {
    if (serviceInstance == null) {
        initialize();
    }
    if (datacenter != null) {
        return datacenter;
    } else {
        return serviceInstance.getRootFolder();
    }
}
项目:primecloud-controller    文件:VmwareClient.java   
/**
 * TODO: メソッドコメントを記述
 *
 * @param <T>
 * @param rootEntity
 * @param type
 * @param name
 * @return
 */
public <T extends ManagedEntity> T search(ManagedEntity rootEntity, Class<T> type, String name) {
    InventoryNavigator navigator = new InventoryNavigator(rootEntity);
    ManagedEntity entity;
    try {
        entity = navigator.searchManagedEntity(type.getSimpleName(), name);
    } catch (RemoteException e) {
        throw new RuntimeException(e);
    }
    return type.cast(entity);
}
项目:primecloud-controller    文件:VmwareClient.java   
/**
 * TODO: メソッドコメントを記述
 *
 * @param rootEntity
 * @param name
 * @return
 */
public ManagedEntity searchByName(ManagedEntity rootEntity, String name) {
    InventoryNavigator navigator = new InventoryNavigator(rootEntity);
    ManagedEntity entity;
    try {
        entity = navigator.searchManagedEntity("ManagedEntity", name);
    } catch (RemoteException e) {
        throw new RuntimeException(e);
    }
    return entity;
}
项目:primecloud-controller    文件:VmwareClient.java   
/**
 * TODO: メソッドコメントを記述
 *
 * @param <T>
 * @param rootEntity
 * @param type
 * @return
 */
public <T extends ManagedEntity> ManagedEntity[] searchByType(ManagedEntity rootEntity, Class<T> type) {
    InventoryNavigator navigator = new InventoryNavigator(rootEntity);
    ManagedEntity[] entities;
    try {
        entities = navigator.searchManagedEntities(type.getSimpleName());
    } catch (RemoteException e) {
        throw new RuntimeException(e);
    }
    return entities;
}
项目:primecloud-controller    文件:VmwareClient.java   
/**
 * TODO: メソッドコメントを記述
 *
 * @param rootEntity
 * @return
 */
public ManagedEntity[] searchAll(ManagedEntity rootEntity) {
    InventoryNavigator navigator = new InventoryNavigator(rootEntity);
    ManagedEntity[] entities;
    try {
        entities = navigator.searchManagedEntities(true);
    } catch (RemoteException e) {
        throw new RuntimeException(e);
    }
    return entities;
}
项目:primecloud-controller    文件:VmwareProcessClient.java   
public void deleteDisk(String datastoreName, String fileName) {
    // Datacenter
    ManagedEntity datacenter = vmwareClient.getRootEntity();

    // Datastore
    Datastore datastore = vmwareClient.search(Datastore.class, datastoreName);
    if (datastore == null) {
        // データストアが見つからない場合
        throw new AutoException("EPROCESS-000505", datastoreName);
    }

    // ディスクの削除
    FileManager fileManager = vmwareClient.getServiceInstance().getFileManager();
    if (fileManager == null) {
        // fileManagerが利用できない場合
        throw new AutoException("EPROCESS-000533");
    }

    try {
        // ディスク削除
        fileManager.deleteDatastoreFile_Task(fileName, (Datacenter) datacenter);
        // ディスク削除後にごみができ、再度アタッチするとエラーになるので削除
        String flatname;
        flatname = fileName.substring(0, fileName.length() - 5) + "-flat.vmdk";
        fileManager.deleteDatastoreFile_Task(flatname, (Datacenter) datacenter);
    } catch (RemoteException e) {
        throw new AutoException("EPROCESS-000522", e, fileName);
    }

    if (log.isInfoEnabled()) {
        log.info(MessageUtils.getMessage("IPROCESS-100455", fileName));
    }
}
项目:primecloud-controller    文件:VmwareMachineProcess.java   
protected String selectDatastore(VmwareProcessClient vmwareProcessClient, VmwareInstance vmwareInstance) {
    // データストアフォルダ内のデータストアのうち、アクセス可能で空き容量が最も大きいものを用いる
    Datastore datastore = null;
    long freeSpace = 0L;

    // ComputeResourceごとのフォルダがあれば、その中のデータストアを用いる
    String datastoreFolderName = vmwareInstance.getComputeResource() + "-storage";
    Folder datastoreFolder = vmwareProcessClient.getVmwareClient().search(Folder.class, datastoreFolderName);
    if (datastoreFolder == null) {
        // ComputeResourceごとのフォルダがなければ、"storage"フォルダの中のデータストアを用いる
        datastoreFolder = vmwareProcessClient.getVmwareClient().search(Folder.class, "storage");
    }

    if (datastoreFolder != null) {
        ManagedEntity[] entities = vmwareProcessClient.getVmwareClient().searchByType(datastoreFolder,
                Datastore.class);
        for (ManagedEntity entity : entities) {
            Datastore datastore2 = Datastore.class.cast(entity);
            DatastoreSummary summary2 = datastore2.getSummary();

            if (summary2.isAccessible() && freeSpace < summary2.getFreeSpace()) {
                datastore = datastore2;
                freeSpace = summary2.getFreeSpace();
            }
        }
    }

    if (datastore == null) {
        // 利用可能なデータストアがない場合
        throw new AutoException("EPROCESS-000528", vmwareInstance.getComputeResource());
    }

    return datastore.getName();
}
项目:contrail-vcenter-plugin    文件:VCenterDB.java   
private void findHostsInFolder(Folder hostsFolder, List<HostSystem> hostsList)
        throws IOException, Exception {
    for (ManagedEntity e : hostsFolder.getChildEntity()) {
        if (e instanceof HostSystem) {
            hostsList.add((HostSystem)e);
        }

        // This is a cluster resource. Delve deeper to
        // find more hosts.
        if (e instanceof ComputeResource) {
            ComputeResource cr = (ComputeResource) e;
            if (e instanceof ClusterComputeResource) {
                ClusterComputeResource cluster = (ClusterComputeResource) e;
                if ((contrailClusterName != null) && 
                     (cluster.getName().equals(contrailClusterName) != true)) {
                   continue;
               }
            }
            for(HostSystem host : cr.getHosts()) {
                hostsList.add((HostSystem)host);
            }
        }

        if (e instanceof Folder) {
            findHostsInFolder((Folder)e, hostsList);
        }
    }
}
项目:vijava    文件:CacheFrameworkSample.java   
public static void main(String[] args) throws Exception
{
  ServiceInstance si = new ServiceInstance(new URL("http://10.20.143.205/sdk"), "root", "password", true); 
  Folder rootFolder = si.getRootFolder();
  ManagedEntity[] vms = new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine");
  ManagedEntity[] hosts = new InventoryNavigator(rootFolder).searchManagedEntities("HostSystem");

  CacheInstance vicf = new CacheInstance(si);
  vicf.watch(vms, new String[] {"name", "runtime.powerState", "summary"});
  vicf.watch(hosts, new String[] {"name", "summary"});
  vicf.start();

  //check if the caching is ready to use; otherwise wait
  while(!vicf.isReady()) 
  {
    Thread.sleep(1000);
  }

  Thread[] vrs = new VimReader[2];

  for(int i=0; i<vrs.length; i++)
  {
    vrs[i] = new VimReader("Thread " + i, vicf, vms, hosts);
    vrs[i].start();
  }

  for(int i=0; i<vrs.length; i++)
  {
    vrs[i].join();
  }
  si.getServerConnection().logout();
}
项目:vijava    文件:CacheFrameworkSample.java   
public VimReader(String name, CacheInstance vicf, ManagedEntity[] vms, ManagedEntity[] hosts)
{
  super(name);
  this.vicf = vicf;
  this.vms = vms;
  this.hosts = hosts;
}
项目:vijava    文件:TaskHistoryMonitor.java   
static TaskFilterSpec createTaskFilterSpec(ManagedEntity ent)
{
  TaskFilterSpec tfs = new TaskFilterSpec();

  // only the root initiated tasks
  TaskFilterSpecByUsername nameFilter 
    = new TaskFilterSpecByUsername();
  nameFilter.setUserList(new String[] {"Administrator"});
  // include tasks initiated by non-users, 
  // for example, by ScheduledTaskManager.
  nameFilter.setSystemUser(true);
  tfs.setUserName(nameFilter);

  // only the tasks with one entity itself
  TaskFilterSpecByEntity entFilter = 
    new TaskFilterSpecByEntity();
  entFilter.setEntity(ent.getMOR());
  entFilter.setRecursion(TaskFilterSpecRecursionOption.all);
  tfs.setEntity(entFilter);

  // only successfully finished tasks
  tfs.setState(new TaskInfoState[]{TaskInfoState.success });

  // only tasks started within last one month
  // strictly speaking, time should be retrieved from server
  TaskFilterSpecByTime tFilter =new TaskFilterSpecByTime();
  Calendar cal = Calendar.getInstance();
  cal.roll(Calendar.MONTH, -1);
  tFilter.setBeginTime(cal); 
  //we ignore the end time here so it gets the latest.
  tFilter.setTimeType(TaskFilterSpecTimeOption.startedTime);
  tfs.setTime(tFilter);

  // Optionally, you limits tasks initiated by scheduled task
  // with the setScheduledTask() method. 
  return tfs;
}
项目:vijava    文件:TestServlet.java   
protected void service(
    HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException 
{
  PrintWriter out = response.getWriter();

  String morStr = request.getParameter(MOREF);
  String type = morStr.substring(0, morStr.indexOf(":"));
  String value = morStr.substring(morStr.indexOf(":")+1);

  ManagedObjectReference mor = new ManagedObjectReference();
  mor.setType(type);
  mor.set_value(value);

  String sessionStr = "vmware_soap_session=\"" 
    + request.getParameter(SESSION_ID) + "\"";

  System.out.println("morStr:" + morStr);
  System.out.println("serviceUrl" 
      + request.getParameter(SERVICE_URL) );
  System.out.println("session:" + sessionStr);

  ServiceInstance si = new ServiceInstance(new URL(
      request.getParameter(SERVICE_URL)),sessionStr, true);

  ManagedEntity me = MorUtil.createExactManagedEntity(
      si.getServerConnection(), mor);

  String name = me.getName();
  out.println("name:" + name);
  out.println(DateFormat.getDateTimeInstance().format(
      new Date()));
}
项目:opennmszh    文件:VmwareViJavaAccess.java   
/**
 * Returns a managed entitiy for a given managed object Id.
 *
 * @param managedObjectId the managed object Id
 * @return the managed entity
 */
public ManagedEntity getManagedEntityByManagedObjectId(String managedObjectId) {
    ManagedObjectReference managedObjectReference = new ManagedObjectReference();

    managedObjectReference.setType("ManagedEntity");
    managedObjectReference.setVal(managedObjectId);

    ManagedEntity managedEntity = MorUtil.createExactManagedEntity(m_serviceInstance.getServerConnection(), managedObjectReference);

    return managedEntity;
}
项目:vmware-vsphere-monitoring-extension    文件:HostMetricCollector.java   
public HostMetricCollector(MetricWriteHelper metricWriter, String metricPrefix, List<ManagedEntity> hostEntities, List<Map<String, Object>> hostConfig, Map<Pattern, String> replacers, Integer hostThreads, Integer vmThreads) {
    super(metricWriter, metricPrefix);
    this.hostEntities = hostEntities;
    this.replacers = replacers;
    this.hostConfig = hostConfig;
    hostCountDown = new CountDownLatch(hostEntities.size());
    vmMetricCollector = new VMMetricCollector(metricWriter, metricPrefix, replacers, vmThreads, hostCountDown);
    executorService = Executors.newFixedThreadPool(hostThreads);
}
项目:jcloud-vsphere    文件:VSphereFileManager.java   
private String getDatacenterName(ManagedEntity managedEntity) {
   if (managedEntity.getMOR().getType().equals("Datacenter"))
      return managedEntity.getName();
   else
      return getDatacenterName(managedEntity.getParent());
}
项目:teamcity-vmware-plugin    文件:VMWareApiConnector.java   
<T extends ManagedEntity> boolean hasPrivilegeOnResource(@NotNull final String entityId,
@NotNull final Class<T> instanceType,
@NotNull final String permission) throws VmwareCheckedCloudException;
项目:teamcity-vmware-plugin    文件:VmwarePooledUpdateInstanceTaskTest.java   
public void check_called_once() throws MalformedURLException {
  final AtomicBoolean listAllCanBeCalled = new AtomicBoolean();
  final AtomicBoolean listAllCalledOnce = new AtomicBoolean();

  final AtomicBoolean getByNameCanBeCalled = new AtomicBoolean();
  final AtomicBoolean getByNameCalledOnce = new AtomicBoolean();

  myFakeApiConnector = new FakeApiConnector(TEST_SERVER_UUID, PROFILE_ID, null) {

    @Override
    protected <T extends ManagedEntity> Map<String, T> findAllEntitiesAsMapOld(final Class<T> instanceType) throws VmwareCheckedCloudException {
      if (!listAllCanBeCalled.get()) {
        fail("Shouldn't be called");
      }
      assertFalse(listAllCalledOnce.get());
      listAllCalledOnce.set(true);
      return super.findAllEntitiesAsMapOld(instanceType);
    }

    @Override
    protected Map<String, VirtualMachine> searchVMsByNames(@NotNull final Collection<String> names, @Nullable final Datacenter dc) throws VmwareCheckedCloudException {
      if (!getByNameCanBeCalled.get()) {
        fail("Shouldn't be called");
      }
      assertFalse(getByNameCalledOnce.get());
      getByNameCalledOnce.set(true);
      return super.searchVMsByNames(names, dc);
    }
  };

  final CloudClientParameters clientParameters1 = new CloudClientParametersImpl(
    Collections.emptyMap(), CloudProfileUtil.collectionFromJson("[{sourceVmName:'image1', behaviour:'START_STOP'}]", PROJECT_ID));
  final VMWareCloudClient client1 = new MyClient(clientParameters1, null);


  final CloudClientParameters clientParameters2 = new CloudClientParametersImpl(
    Collections.emptyMap(), CloudProfileUtil.collectionFromJson(
    "[{sourceVmName:'image2',snapshot:'snap*',folder:'cf',pool:'rp'," +
    "maxInstances:3,behaviour:'ON_DEMAND_CLONE',customizationSpec:'someCustomization'}]", PROJECT_ID));
  final VMWareCloudClient client2 = new MyClient(clientParameters2, null);

  final CloudClientParameters clientParameters3 = new CloudClientParametersImpl(
    Collections.emptyMap(), CloudProfileUtil.collectionFromJson(
    "[{'source-id':'image_template',sourceVmName:'image_template', snapshot:'" + VmwareConstants.CURRENT_STATE +
    "',folder:'cf',pool:'rp',maxInstances:3,behaviour:'FRESH_CLONE', customizationSpec: 'linux'}]",
    PROJECT_ID));
  final VMWareCloudClient client3 = new MyClient(clientParameters3, null);

  final VmwareUpdateInstanceTask task1 = myTaskManager.createUpdateTask(myFakeApiConnector, client1);
  final VmwareUpdateInstanceTask task2 = myTaskManager.createUpdateTask(myFakeApiConnector, client2);
  final VmwareUpdateInstanceTask task3 = myTaskManager.createUpdateTask(myFakeApiConnector, client3);

  listAllCanBeCalled.set(true);
  listAllCalledOnce.set(false);
  getByNameCalledOnce.set(false);
  getByNameCanBeCalled.set(true);
  task1.run();
  task2.run();
  task3.run();
  assertTrue(listAllCalledOnce.get());
  assertTrue(getByNameCalledOnce.get());
}
项目:teamcity-vmware-plugin    文件:VmwarePooledUpdateInstanceTaskTest.java   
public void check_cleared_after_dispose_2() throws MalformedURLException {
  final AtomicBoolean canBeCalled = new AtomicBoolean();
  final AtomicInteger callsCount = new AtomicInteger();

  myFakeApiConnector = new FakeApiConnector(TEST_SERVER_UUID, PROFILE_ID, null) {
    @Override
    protected <T extends ManagedEntity> Map<String, T> findAllEntitiesAsMapOld(final Class<T> instanceType) throws VmwareCheckedCloudException {
      processChecks();
      return Collections.emptyMap();
    }

    private void processChecks() {
      if (!canBeCalled.get()) {
        fail("Shouldn't be called");
      }
      assertTrue(callsCount.get() < 2);
      callsCount.incrementAndGet();
    }

    @Override
    protected Map<String, VirtualMachine> searchVMsByNames(@NotNull final Collection<String> names, @Nullable final Datacenter dc) throws VmwareCheckedCloudException {
      processChecks();
      return Collections.emptyMap();
    }
  };

  final CloudClientParameters clientParameters1 = new CloudClientParametersImpl(
    Collections.emptyMap(), CloudProfileUtil.collectionFromJson("[{sourceVmName:'image1', behaviour:'START_STOP'}]", PROJECT_ID));
  final VMWareCloudClient client1 = new MyClient(clientParameters1, null);


  final CloudClientParameters clientParameters2 = new CloudClientParametersImpl(
    Collections.emptyMap(), CloudProfileUtil.collectionFromJson(
    "[{sourceVmName:'image2',snapshot:'snap*',folder:'cf',pool:'rp'," +
    "maxInstances:3,behaviour:'ON_DEMAND_CLONE',customizationSpec:'someCustomization'}]", PROJECT_ID));

  final VMWareCloudClient client2 = new MyClient(clientParameters2, null);
  final VmwareUpdateInstanceTask task1 = myTaskManager.createUpdateTask(myFakeApiConnector, client1);


  canBeCalled.set(true);
  callsCount.set(0);
  task1.run();
  assertTrue(callsCount.get() > 0);

  client1.dispose();
  final VmwareUpdateInstanceTask task2 = myTaskManager.createUpdateTask(myFakeApiConnector, client2);
  canBeCalled.set(true);
  callsCount.set(0);
  task2.run();
  assertTrue(callsCount.get() > 0);


}
项目:teamcity-vmware-plugin    文件:FakeFolder.java   
@Override
public ManagedEntity getParent() {
  return myParent;
}
项目:teamcity-vmware-plugin    文件:FakeFolder.java   
public void setParent(final ManagedEntity parent) {
  myParent = parent;
}