Home > vSphere API > How You Can Use VI Java API in Scala: A Quick Sample

How You Can Use VI Java API in Scala: A Quick Sample

January 25th, 2011 Leave a comment Go to comments

As I blogged before, you can use open source VI Java API in all JVM languages like Jython, Groovy, JRuby and frameworks like Grail. Today Dave Briccetti (@dcbriccetti) sent me a sample showing how to use it in Scala. Dave has been a happy user of the API since he started to work at VMware as an independent consultant more than a year ago.

Here is the code sample:

Time to learn how to "Google" and manage your VMware and clouds in a fast and secure

HTML5 App
package com.vmware.vim25.mo.samples
import java.net.URL
import org.apache.log4j.Logger
import com.vmware.vim25.mo._
object HelloVM {
  val log = Logger.getLogger(getClass)
  def sayHello(url: String, user: String, pwd: String) {
    log.info("Starting")
    val si = new ServiceInstance(new URL(url), user, pwd, true)
    log.info("ServiceInstance created")
    val rootFolder = si.getRootFolder
    log.info("Root folder: " + rootFolder.getName)
    log.info("Searching for VMs")
    getVMs(rootFolder) match {
      case firstVm :: others =>
        log.info("Hello " + firstVm.getName)
        log.info("GuestOS: " + firstVm.getConfig.getGuestFullName)
        log.info("Multiple snapshots supported: " + firstVm.getCapability.isMultipleSnapshotsSupported)
      case _ => log.warn("No VMs found")
    }
    si.getServerConnection.logout()
  }
  private def getVMs(rootFolder: Folder): List[VirtualMachine] =
    new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine") match {
      case null =>
        log.error("searchManagedEntities returned null")
        List[VirtualMachine]()
      case vms => vms map(_.asInstanceOf[VirtualMachine]) toList
    }
}


If you have not yet installed Scala, please download it here. For VI Java API, download it here. Optionally you can use Maven with the pom.xml provided in this zipped project from Dave. Thanks Dave!

BTW, please leave a comment if you find we miss a JVM language you are interested.

  1. No comments yet.
  1. No trackbacks yet.