For the Java developer, this chapter shows how to install the Java SDKs and run example programs against vSphere APIs.

Installing the vSphere Automation SDK and Web Services SDK for Java

The vSphere Web Services SDK, along with several other VMware SDKs, is contained in the vSphere Management SDK, available for download at https://developer.broadcom.com/sdks/vsphere-management-sdk/latest/.

  • Use Java SE with JDK 11 for production environments. vCenter Server supports HTTPS connections with Java 1.8, and later, but not with Java 1.7.

  • Download and install the vSphere Management SDK from the developer site. Click the SDKs link to reach a landing page that has links to all vSphere SDKs.

    After you download and expand the vSphere Management SDK package, the Web Services SDK is in the subdirectory SDK/vsphere-ws

  • Download and install the Automation SDK from the developer site.
  • Set the JAVAHOME environment variable to the root path of the Java Runtime Environment (JRE), such as C:\Program Files\Java\jdk11.0.16_221
  • If needed, build the samples for the vSphere Web Services SDK.

    This Hello Folder example uses wssamples.jar and vim25.jar to communicate with the vSphere Web Services API.

  • Install these external dependencies:
    • slf4j-api-2.0.9.jar
    • jackson-databind-2.15.2.jar and its dependencies
    • httpcomponents-httpcore-4.4.13.jar
    • org-apache-commons-logging.jar
  • Set your runtime classpath to include the following:
    • org-apache-commons-logging.jar
    • target/classes
    • vapi-runtime-2.40.0.jar
    • vim25.jar
    • wssamples.jar
    • vapi-authentication-2.40.0.jar
    • slf4j-api-2.0.9.jar
    • jackson-databind-2.15.2.jar
    • jackson-core-2.15.2.jar
    • jackson-annotations-2.15.2.jar
    • httpclient/httpclient-4.5.6.jar
    • httpcomponents-httpcore-4.4.13.jar
    • org-apache-commons-logging.jar
    • vcenter-bindings-4.1.0.jar

Creating and Tagging a Folder Using Java

The vSphere Automation (VAPI) SDK and the vSphere Web Services (VIM) SDK can be used together to supplement each API with features present in the other API. This example shows:
  1. Authentication with both VAPI and VIM.
  2. Using VIM to create a folder as a child of the root folder in the vSphere inventory.
  3. Using VAPI to create a tag category.
  4. Using VAPI to create a tag in the tag category.
  5. Using VAPI to associate the tag with the folder.
  6. Logging out of both sessions.
Note: This code is for example purposes only. The example skips SSL verification and uses only basic authentication. In a production environment, both these practices are unsafe.
package example;

import java.security.KeyStore;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.HashSet;
import java.util.Set;

import com.vmware.vapi.bindings.StubConfiguration;
import com.vmware.vapi.protocol.HttpConfiguration;
import com.vmware.vapi.protocol.HttpConfiguration.KeyStoreConfig;
import com.vmware.vapi.protocol.HttpConfiguration.SslConfiguration;

import vmware.samples.common.authentication.VapiAuthenticationHelper;
import vmware.samples.common.authentication.VimAuthenticationHelper;
import vmware.samples.common.SslUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vmware.vapi.bindings.StubConfiguration;
import com.vmware.vapi.protocol.HttpConfiguration;
import com.vmware.vapi.protocol.HttpConfiguration.KeyStoreConfig;
import com.vmware.vapi.protocol.HttpConfiguration.SslConfiguration;

import vmware.samples.common.authentication.VapiAuthenticationHelper;
import vmware.samples.common.authentication.VimAuthenticationHelper;
import vmware.samples.common.SslUtil;
import com.vmware.connection.ConnectedVimServiceBase;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.ServiceContent;
import com.vmware.vim25.VimPortType;

import com.vmware.cis.tagging.Category;
import com.vmware.cis.tagging.CategoryModel.Cardinality;
import com.vmware.cis.tagging.CategoryTypes;
import com.vmware.cis.tagging.Tag;
import com.vmware.cis.tagging.TagAssociation;
import com.vmware.cis.tagging.TagTypes;
import com.vmware.vapi.std.DynamicID;


public class Example() extends ConnectedVimServiceBase {
  public Example() {
    this.serverName = "vc1.example.com";
    this.userName   = "[email protected]";
    this.password   = "TooSecret2C!";
  }

  // Server URL and credentials for authentication:
  protected String serverName;
  protected String userName;
  protected String password;

  /**
   * Builds the SSL configuration to be applied for the connection to the
   * server
   * 
   * Note: Below code circumvents SSL trust if "skip-server-verification" is
   * specified. Circumventing SSL trust is unsafe and should not be used
   * in production software. It is ONLY FOR THE PURPOSE OF DEVELOPMENT
   * ENVIRONMENTS.
   */
  protected SslConfiguration buildSslConfiguration() throws Exception {
      SslConfiguration sslConfig;
      /*
       * Below code enables all VIM & vAPI connections to the server
       * without validating the server certificates..
       *
       * Note: Below code is to be used ONLY IN DEVELOPMENT ENVIRONMENTS.
       * Circumventing SSL trust is unsafe and should not be used in
       * production software.
       */
      SslUtil.trustAllHttpsCertificates();
      sslConfig = new SslConfiguration.Builder()
                     .disableCertificateValidation()
                     .disableHostnameVerification()
                     .getConfig();
      return sslConfig;
  }

  protected HttpConfiguration buildHttpConfiguration() throws Exception {
    HttpConfiguration httpConfig =
            new HttpConfiguration.Builder()
            .setSslConfiguration(buildSslConfiguration())
            .getConfig();
    return httpConfig;
  }

  /**
   * Creates dual sessions with server for VIM & VAPI, using username/password.
   * @throws Exception
   */
  protected VapiAuthenticationHelper vapiAuthHelper;
  protected VimAuthenticationHelper vimAuthHelper;
  protected StubConfiguration sessionStubConfig;

  protected void login() throws Exception {
    this.vapiAuthHelper = new VapiAuthenticationHelper();
    this.vimAuthHelper = new VimAuthenticationHelper();
    HttpConfiguration httpConfig = buildHttpConfiguration();
    this.sessionStubConfig =
            vapiAuthHelper.loginByUsernameAndPassword(
                this.server, this.username, this.password, httpConfig);
    this.vimAuthHelper.loginByUsernameAndPassword(
                this.server, this.username, this.password);
  }
  
  protected void logout() throws Exception {
    this.vapiAuthHelper.logout();
    this.vimAuthHelper.logout();
  }

  protected ManagedObjectReference createHelloFolder() throws Exception {
    System.out.println("Use VIM API to create a Hello Folder.");
    ServiceContent content = this.vimAuthHelper.getServiceContent();
    ManagedObjectReference folderMoRef = content.getRootFolder();
    VimPortType vimPort = this.vimAuthHelper.getVimPort();
    ManagedObjectReference hello =
       vimPort.createFolder(folderMoRef, "Hello Folder");
    System.out.println("Sucessfully created Hello Folder.");
    return hello;
  }

  protected String createTagCategory() throws Exception {
    System.out.println("VAPI creating a tag category.");
    Category categoryStub =    
       this.vapiAuthHelper.getStubFactory().createStub(Category.class,
                                                 sessionStubConfig);
    CategoryTypes.CreateSpec createSpec = new CategoryTypes.CreateSpec();
    createSpec.setName("hello_category");
    createSpec.setDescription("example of tagging category from Java");
    createSpec.setCardinality(Cardinality.SINGLE);
    Set<String> set = new HashSet<>();
    set.add("Folder");
    createSpec.setAssociableTypes(set);
    String newCategoryId = categoryStub.create(createSpec);
    System.out.println("Created \"hello_category\".");
    return newCategoryId;
  }

  protected String createTag(String cat) throws Exception {
    System.out.println("VAPI creating a tag.");
    Tag tagStub =
       this.vapiAuthHelper.getStubFactory().createStub(Tag.class,
                                                 sessionStubConfig);
    TagTypes.CreateSpec createSpec = new TagTypes.CreateSpec();
    createSpec.setName("hello_tag");
    createSpec.setDescription("example of a tag from Automation API");
    createSpec.setCategoryId(cat);
    String newTagId = tagStub.create(createSpec);
    System.out.println("Created \"hello_tag\".");
    return newTagId;    
  }

  protected void associateTag(String tag, DynamicID folder) throws Exception {
    System.out.println("Using Java to associate a tag to a folder.");
    TagAssociation assocStub =
       this.vapiAuthHelper.getStubFactory().createStub(TagAssociation.class,
                                                 sessionStubConfig);
    assocStub.attach(tag, folder);
    System.out.println("Associated \"hello_tag\" with \"Hello Folder\".");
  } 

  public static void main(String[] args) throws Exception {
    Example example = new Example();
    example.login();
    System.out.println("Logged in to VIM and to VAPI.");   
    ManagedObjectReference helloFolder = example.createHelloFolder();
    String cat = example.createTagCategory();   
    String tag = example.createTag(cat);  
    DynamicID folder =
                new DynamicID(helloFolder.getType(),
                              helloFolder.getValue());
    example.associateTag(tag, folder);     
    example.logout();
  }
}