My favorites | Sign in
Project Logo
Project hosting will be READ-ONLY Wednesday at 8am PST due to brief network maintenance.
                
Code license: New BSD License
Labels: java, vmware, sdk, toolkit
Feeds:
People details
Project owners:
  sakutz

VI Toolkit for Java

The VI Toolkit for Java is a Java library that is patterned after the VI Perl Toolkit. It makes connecting to VI, finding a VM, and getting its properties a snap! The toolkit is written in Java 6 (1.6). This toolkit uses the Apache Commons CLI library for parsing command line options and their arguments. Administrators and developers who like the ability to quickly create scripts with the VI Perl Toolkit but appreciate the depth of Java will love the VI Toolkit for Java..

Note The VI Toolkit for Java is not the same as the experimental Java client libraries that VMware engineer Steve Jin released on May 8th. Steve's libraries are brilliant, and I hope to collaborate with VMware by combining our efforts.

Note There is also a VI Toolkit for .NET.

Enjoy!

FAQ

com.lostcreations.vitoolkitforjava.server=SERVER
com.lostcreations.vitoolkitforjava.username=USERNAME
com.lostcreations.vitoolkitforjava.password=PASSWORD
com.lostcreations.vitoolkitforjava.vm=DNS_NAME_OF_VM

Documentation

Documentation for the VI Toolkit for Java.

Subroutine Reference

For a complete listing of all the toolkit's subroutines please see this project's Javadocs.

Default Options

The following options are created by default by the toolkit when a Session object is instantiated:

Option Has Argument Variable Default Value Description
--help No Display usage information for the program
--ignoresslerrors No VI_IGNORESSLERRORS False Ignore certificate mismatch errors
--password Yes VI_PASSWORD Password
--portnumber Yes VI_PORTNUMBER Port used to connect to server
--protocol Yes VI_PROTOCOL https Protocol used to connect to server
--savesessionfile Yes VI_SAVESESSIONFILE File to save session ID/cookie to utilize
--server Yes VI_SERVER 'localhost" VI server to connect to. Required if url is not present
--servicepath Yes VI_SERVICEPATH "/sdk/webService" Service path used to connect to server
--sessionfile Yes VI_SESSIONFILE File containing session ID/cookie to utilize
--url Yes VI_URL VI SDK URL to connect to. Required if server is not present
--username Yes VI_USERNAME Username
--verbose Yes VI_VERBOSE Display additional debugging information
--version Yes Display version information for the script

Example Program

The following is a short example of a command line application utilizing the toolkit:

/*
Copyright (c) 2008, Schley Andrew Kutz <akutz@lostcreations.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.
    * Neither the name of l o s t c r e a t i o n s nor the names of its 
    contributors may be used to endorse or promote products derived from this 
    software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


package com.lostcreations.vitoolkitforjava.templateapplication;

import static org.junit.Assert.fail;
import java.util.HashMap;
import com.vmware.vim25.*;
import org.apache.commons.cli.*;
import com.lostcreations.vmware.vitoolkitforjava.*;

public class Program
{
	private static class ProcessExit_Callback extends Thread
	{
		public void run()
		{
			try
			{
				if ( m_session.getIsConnected() ) m_session.disconnect();
			}
			catch ( Exception e )
			{
				System.out.println( "Error disconnecting: " + e.getMessage() );
			}
		}
	}
	
	/**
	 * The session object used to connect to the VI server.
	 */
	private static Session m_session;
	private static java.util.Properties m_props = new java.util.Properties();
	
	/**
	 * @param args
	 */
	public static void main( String[] args ) throws Exception
	{
		String cdir = new java.io.File( "." ).getCanonicalPath();
		String pfile = cdir + "/conf/UnitTests.properties";
		java.io.FileInputStream fin = new java.io.FileInputStream( pfile );
		m_props.load( fin );
		fin.close();
		
		args = new String[] {
			"--server", m_props.getProperty( 
				"com.lostcreations.vmware.vitoolkitforjava.server" ),
			"--username", m_props.getProperty( 
			"com.lostcreations.vmware.vitoolkitforjava.username" ),
			"--password", m_props.getProperty( 
			"com.lostcreations.vmware.vitoolkitforjava.password" ),
			"--verbose", "--ignoresslerrors",
			"--vmname", m_props.getProperty( 
			"com.lostcreations.vmware.vitoolkitforjava.vm" )
		};
		
		// Create a new session.
		m_session = new Session( args );

		// Define the string that is prefixed to the auto-generated output
		// when the usage statement is printed.
		m_session.setHelpPrefix( "TemplateApplication" );

		// Cleanup when the process exists.
		java.lang.Runtime.getRuntime().addShutdownHook( 
			new ProcessExit_Callback() );

		// Add a custom option.
		m_session.addOptions( new Options().addOption(
			OptionBuilder
				.withLongOpt( "vmname" )
				.withDescription( "The name of the VM to find" )
				.isRequired()
				.create() ) );

		// Validate the options.
		try
		{
			m_session.validateOptions();
		}

		// If there is an error parsing the options print out the
		// generated usage statement with the given prefix, then
		// exit the application.
		catch ( ParseException e )
		{
			System.out.println( e.getMessage() );
			m_session.printUsage( "TemplateApplication" );
			return;
		}

		// Connect to the VI server.
		m_session.connect();

		// Create a filter to find the VM.
		HashMap<String, String> filters = 
			new HashMap<String, String>();
		filters.put( "config.name", 
			m_props.getProperty( 
				"com.lostcreations.vmware.vitoolkitforjava.vm" ) );

		// Find the VM that matches the given filter.
		ManagedObjectReference vm = m_session.findEntity(
			Session.EntityTypes.VirtualMachine,
			filters );

		// Make sure we found the VM
		if ( vm == null )
		{
			System.out.println( "Could not find the VM" );
			return;
		}

		// Get all of the VM's property values.
		HashMap<String, Object> values = m_session.getProperties( vm );

		// Make sure that values were returned
		if ( values.size() == 0 )
		{
			System.out.println( "Unable to retrieve property values" );
			return;
		}

		// Print out the VM's UUID
		System.out.println( "VM UUID: " +
			( ( VirtualMachineConfigInfo ) values.get( "config" ) ).getUuid() );
	}
}

When the above program is executed it will produce the following output:

VM UUID: 5029130b-9130-4bd8-e45e-52c687ebe765

If the program was executed with the '--help' switch the following help text would be printed on the console:

usage: TemplateApplication
    --help                    Display usage information for the program
    --ignoresslerrors         Ignore certificate mismatch errors (variable
                              VI_IGNORESSLERRORS)
    --password <arg>          Password (variable VI_PASSWORD)
    --portnumber <arg>        Port used to connect to server (variable
                              VI_PORTNUMBER)
    --protocol <arg>          Protocol used to connect to server (variable
                              VI_PROTOCOL, default 'https')
    --savesessionfile <arg>   File to save session ID/cookie to utilize
                              (variable, VI_SAVESESSIONFILE)
    --server <arg>            VI server to connect to. Required if url is
                              not present (variable, VI_SERVER, default 'localhost')
    --servicepath <arg>       Service path used to connect to server
                              (variable, VI_SERVICEPATH, default '/sdk/webService')
    --sessionfile <arg>       File containg session ID/cookie to utilize
                              (variable, VI_SESSIONFILE)
    --url <arg>               VI SDK URL to connect to. Required if server
                              is not present (variable, VI_URL)
    --username <arg>          Username (variable, VI_USERNAME)
    --verbose                 Display additional debugging information
                              (variable, VI_VERBOSE)
    --version                 Display version information for the script
    --vmname                  The name of the VM to find








Hosted by Google Code