Code Samples

Discussion about using the VirtualBox API, Tutorials, Samples.

Code Samples

Postby noteirak » 11. Feb 2015, 15:04

Place holder for exemples of API usage
Hyperbox - Virtual Infrastructure Manager - https://kamax.io/hbox/
Manage your VirtualBox infrastructure the free way!
noteirak
Site Moderator
 
Posts: 5198
Joined: 13. Jan 2012, 11:14
Primary OS: Debian other
VBox Version: OSE Debian
Guest OSses: Debian, Win 2k8, Win 7

Re: Code Samples

Postby noteirak » 13. Aug 2015, 21:32

API 5.x

5.1
List all snapshots for a VM
Code: Select all   Expand viewCollapse view
/*
 *
 * Written in 2017 by Maxime Dor
 *
 * https://kamax.io/
 *
 * To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public
 * domain worldwide. This software is distributed without any warranty. Full license can be found at http://creativecommons.org/publicdomain/zero/1.0/
 */

import org.virtualbox_5_1.IMachine;
import org.virtualbox_5_1.ISnapshot;
import org.virtualbox_5_1.IVirtualBox;
import org.virtualbox_5_1.VirtualBoxManager;

public class SnapshotList {

    private static void printChilds(ISnapshot snapshot) {
        System.out.println("\"" + snapshot.getName() + "\" {" + snapshot.getId() + "}");
        for (ISnapshot snapChild : snapshot.getChildren()) {
            printChilds(snapChild);
        }
    }

    public static void main(String[] args) {
        /*
         * WebServices info
         */
        String wsHost = "http://localhost:18083";
        String wsUser = "user";
        String wsPass = "password";

        if (args.length < 1 || args[0] == null || args[0].length() < 1) {
            System.err.println("Specify the VM name/UUID as first parameter");
            System.exit(1);
        }

        String vmName = args[0];

        VirtualBoxManager vboxManager = VirtualBoxManager.createInstance(null);
        vboxManager.connect(wsHost, wsUser, wsPass);

        try {
            IVirtualBox vbox = vboxManager.getVBox();
            IMachine vm = vbox.findMachine(vmName);
            if (vm.getSnapshotCount() < 1) {
                System.out.println("The machine + " + vmName + " has no snapshot");
                System.exit(0);
            }

            // The magic is here: null will give you the root snapshot
            printChilds(vm.findSnapshot(null));
        } finally {
            vboxManager.disconnect();
            vboxManager.cleanup();
        }
    }

}

Export a VM to a OVA appliance
Code: Select all   Expand viewCollapse view
/*
 *
 * Written in 2016 by Maxime Dor
 *
 * https://kamax.io/
 *
 * To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public
 * domain worldwide. This software is distributed without any warranty. Full license can be found at http://creativecommons.org/publicdomain/zero/1.0/
 */

import java.util.ArrayList;
import java.util.List;
import org.virtualbox_5_1.ExportOptions;
import org.virtualbox_5_1.IAppliance;
import org.virtualbox_5_1.IMachine;
import org.virtualbox_5_1.IVirtualBox;
import org.virtualbox_5_1.VirtualBoxManager;


/*
 * For more detailed, step-by-step:
 * https://www.virtualbox.org/sdkref/interface_i_appliance.html#details
 */
public class VBox_5_1_VmExport {

    public static void main(String[] args) {
        /*
         * WebServices info
         */
        String wsHost = "http://localhost:18083";
        String wsUser = "user";
        String wsPass = "password";

        /*
         * VM to export
         */
        String vmToExport = "test";

        /*
         * Available formats are:
         * - ovf-0.9
         * - ovf-1.0
         * - ovf-2.0
         *
         * For more details: http://www.dmtf.org/standards/ovf
         */
        String exportFormat = "ovf-2.0";

        /*
         * Path where to write the appliance.
         * Filename extension will decide the expected appliance format on disk.
         * If ending in .ova, a single OVA file is created at the path given, which is a TAR archive with all files within.
         * If ending in .ovf, all files are written to disk directly in the same folder as the appliance file.
         */
        String exportPath = "/tmp/test-export.ova";

        /*
         * This is used as the base filename of the exported VM disks.
         * In this case, if the VM had 3 disks, the following files would be created within the OVA:
         * - test-disk1.vmdk
         * - test-disk2.vmdk
         * - test-disk3.vmdk
         */
        String exportDiskBasename = vmToExport;

        /*
         * Add whatever options you want for the export. By default, there is no need of special options.
         * See https://www.virtualbox.org/sdkref/_virtual_box_8idl.html#adcba962dac19e8095de80a2a792402aa for the list
         */
        List<ExportOptions> opts = new ArrayList<>();


        System.out.println("Started");
        VirtualBoxManager vboxManager = VirtualBoxManager.createInstance(null);
        vboxManager.connect(wsHost, wsUser, wsPass); // only if you are using Web Services
        System.out.println("Connected");

        try {
            IVirtualBox vbox = vboxManager.getVBox();
            IMachine vm = vbox.findMachine(vmToExport);
            IAppliance app = vbox.createAppliance();

            System.out.println("Writting VM to appliance");
            vm.exportTo(app, exportDiskBasename);

            System.out.println("Writting appliance to disk");
            app.write(exportFormat, opts, exportPath);

            System.out.println("Done");
        } finally {
            vboxManager.disconnect(); // only if you are using Web Services
            vboxManager.cleanup();
            System.out.println("Disconnected");
        }

        System.out.println("Finished");
    }

}

5.0
Detach a disk from one VM and attach to another - Java
Code: Select all   Expand viewCollapse view
/*
 *
 * Written in 2015 by Maxime Dor
 *
 * http://kamax.io/
 *
 * To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public
 * domain worldwide. This software is distributed without any warranty. Full license can be found at http://creativecommons.org/publicdomain/zero/1.0/
 */

import org.virtualbox_5_0.DeviceType;
import org.virtualbox_5_0.IMachine;
import org.virtualbox_5_0.IMedium;
import org.virtualbox_5_0.ISession;
import org.virtualbox_5_0.IVirtualBox;
import org.virtualbox_5_0.LockType;
import org.virtualbox_5_0.VirtualBoxManager;


public class VBox_5_0_MoveDriveBetweenVM {

    public static void main(String[] args) throws InterruptedException {
        String vmSourceName = "sourceMachine";
        String vmDestName = "sourceMachine";
        String controllerSourceName = "SATA";
        String controllerDestName = "SATA";
        int controllerSourcePortIndex = 0;
        int controllerSourceDeviceIndex = 0;
        int controllerDestPortIndex = 0;
        int controllerDestDeviceIndex = 0;

        System.out.println("Started");
        VirtualBoxManager vboxManager = VirtualBoxManager.createInstance(null);
        vboxManager.connect("http://localhost:18083", "user", "password"); // only if you are using Web Services
        System.out.println("Connected");
        try {
            IVirtualBox vbox = vboxManager.getVBox();
            IMachine vmSource = vbox.findMachine(vmSourceName);
            ISession sessionSource = vboxManager.getSessionObject();
            vmSource.lockMachine(sessionSource, LockType.Write); // We ensure VM is not in use
            try {
                IMachine vmDest = vbox.findMachine(vmDestName);
                ISession sessionDest = vboxManager.getSessionObject();
                vmDest.lockMachine(sessionDest, LockType.Shared); // only if controller support hotplug, else use Write
                try {
                    IMedium medium = sessionSource.getMachine().getMedium(controllerSourceName, controllerSourcePortIndex, controllerSourceDeviceIndex);
                    sessionSource.getMachine().detachDevice(controllerSourceName, controllerSourcePortIndex, controllerSourceDeviceIndex);
                    sessionSource.getMachine().saveSettings();

                    sessionDest.getMachine().attachDevice(controllerDestName, controllerDestPortIndex, controllerDestDeviceIndex, DeviceType.HardDisk, medium);
                    sessionDest.getMachine().saveSettings();
                } finally {
                    sessionDest.unlockMachine();
                }
            } finally {
                sessionSource.unlockMachine();
            }
        } finally {
            vboxManager.disconnect(); // only if you are using Web Services
            vboxManager.cleanup();
            System.out.println("Disconnected");
        }

        System.out.println("Finished");
    }

}

Catch events using passive mode - Java
Code: Select all   Expand viewCollapse view
/*
 * Copyright (c) 2017 Maxime Dor
 *
 * https://max.kamax.io/
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package io.kamax.vbox5_1;

import org.virtualbox_5_1.*;

import java.util.Arrays;
import java.util.List;


public class CatchEvents_5_1 {

    static VirtualBoxManager mgr;
    static Thread listener;

    public static void main(String args[]) {
        String vmName = Long.toString(System.currentTimeMillis()); // get a random VM name to use later

        System.out.println("Creating VirtualBox client instance");
        mgr = VirtualBoxManager.createInstance(null);
        try {
            /*
             * This line is only required if you are using the WebServices to connect.
             * Also, change "user" and "password" to local credentials on the machine running the web services, or set authentication to null.
             * To do so, you can start vboxwevsrv with "-A null" argument or use vboxmanage to make it permanent.
             */
            System.out.println("Connecting to VirtualBox using Web Services");
            mgr.connect("http://localhost:18083", "user", "password"); // only if you are using WebServices Bindings
            System.out.println("Connected to VirtualBox using Web Services");

            /*
             * We will run the event worker in a separate thread like it would normally be done.
             */
            listener = new EventWorker();
            listener.start();

            try {
                /*
                 * We create an empty machine, we save its settings to disk (to actually make it really exist) than we register it.
                 * This will trigger IMachineRegisteredEvent.
                 */
                IMachine vm = mgr.getVBox().createMachine(null, vmName, null, "Other", null);
                vm.saveSettings();
                mgr.getVBox().registerMachine(vm);

                vm = mgr.getVBox().findMachine(vmName); // we fetch the machine object again just to be safe
                ISession session = mgr.getSessionObject();
                IProgress p = vm.launchVMProcess(session, "headless", null);
                p.waitForCompletion(-1); // we wait until the starting process has finished
                try {
                    if (p.getResultCode() != 0) { // error when starting the VM, we don't continue further
                        throw new RuntimeException(p.getErrorInfo().getText());
                    } else { // VM got started, OnMachineStateChanged triggered two times at this point
                        // let's now power down the VM
                        p = session.getConsole().powerDown();
                        p.waitForCompletion(-1);
                        if (p.getResultCode() != 0) { // we failed to stop the VM
                            throw new RuntimeException(p.getErrorInfo().getText());
                        } else {
                            // VM got stopped, OnMachineStateChanged triggered several times at this point
                        }
                    }
                } finally {
                    // we do not need the lock any further and is required for for IMachine::unregister()
                    session.unlockMachine();

                    // since unlock is not instant, we need to wait until the unlock is done or unregister() will fail.
                    while (!SessionState.Unlocked.equals(vm.getSessionState())) {
                        try {
                            System.out.println("Waiting for session unlock...");
                            Thread.sleep(1000L);
                        } catch (InterruptedException e) {
                            System.err.println("Interrupted while waiting for session to be unlocked");
                        }
                    }

                    // vm.unregister() will trigger IMachineRegisteredEvent.
                    System.out.println("Deleting machine");
                    vm.deleteConfig(vm.unregister(CleanupMode.DetachAllReturnHardDisksOnly));
                }
            } finally { // we instruct the Event Worker to stop and wait 5 sec for it to do so
                listener.interrupt();
                try {
                    listener.join(5000); // we wait on the thread
                } catch (InterruptedException e) {
                    System.err.println("Interrupted while waiting for EventWorker to stop");
                }

                if (listener.isAlive()) {
                    System.err.println("Event worked did not stop in a timely fashion");
                } else {
                    System.out.println("Event worked stopped");
                }
            }
        } finally {
            mgr.disconnect(); // only if you are using WebServices Bindings
            mgr.cleanup();
            System.out.println("Disconnected from VirtualBox - bye bye!");
        }
    }

    static class EventWorker extends Thread {

        IEventListener el;

        @Override
        public void run() {
            System.out.println("EventWorker started");
            el = mgr.getVBox().getEventSource().createListener(); // we create the object that will fetch and queue the events for us

            /*
             * We register for the events that we are interested in.
             * If we wanted all of them, we would use VBoxEventType.Any
             *
             * Not all events will be visible here. If we want events for a specific machine (like Clipboard mode change),
             * we need to use the event source of that specific machine - see IMachine::getEventSource()
             */
            List<VBoxEventType> types = Arrays.asList(VBoxEventType.OnSessionStateChanged, VBoxEventType.OnMachineStateChanged,
                    VBoxEventType.OnMachineRegistered);
            mgr.getVBox().getEventSource().registerListener(el, types, false);

            try {
                while (!isInterrupted()) {
                    mgr.waitForEvents(0); // Needed to clear the internal event queue, see https://www.virtualbox.org/ticket/13647
                    IEvent rawEvent = mgr.getVBox().getEventSource().getEvent(el, 1000);
                    if (rawEvent == null) { // we waited but no event came
                        continue; // we loop again and skip the code below
                    }

                    try {
                        System.out.println("Got event of type " + rawEvent.getType());

                        if (VBoxEventType.OnSessionStateChanged.equals(rawEvent.getType())) {
                            // It is important to use the queryInterface() on the expected class, simple casting will not work.
                            ISessionStateChangedEvent event = ISessionStateChangedEvent.queryInterface(rawEvent);
                            System.out.println("Session state changed to " + event.getState() + " for machine " + event.getMachineId());
                        }

                        if (VBoxEventType.OnMachineRegistered.equals(rawEvent.getType())) { // we check the event type
                            // It is important to use the queryInterface() on the expected class, simple casting will not work.
                            IMachineRegisteredEvent event = IMachineRegisteredEvent.queryInterface(rawEvent);
                            System.out.println("Machine " + event.getMachineId() + " has been " + (event.getRegistered() ? "registered" : "unregistered"));
                        }

                        if (VBoxEventType.OnMachineStateChanged.equals(rawEvent.getType())) {
                            // It is important to use the queryInterface() on the expected class, simple casting will not work.
                            IMachineStateChangedEvent event = IMachineStateChangedEvent.queryInterface(rawEvent);
                            System.out.println("Machine " + event.getMachineId() + " state changed to " + event.getState());
                        }
                    } finally {
                        // We mark the event as processed so ressources can be released. We do this in a finally block to ensure it is done no matter what.
                        mgr.getVBox().getEventSource().eventProcessed(el, rawEvent);
                    }
                }
            } catch (Throwable t) {
                t.printStackTrace();
            } finally {
                mgr.getVBox().getEventSource().unregisterListener(el); // we are done fetching events, so we free the listener
                System.out.println("EventWorker finished");
            }
        }

    }

}
Last edited by noteirak on 28. Sep 2017, 16:04, edited 7 times in total.
Reason: Included the code locally.
Hyperbox - Virtual Infrastructure Manager - https://kamax.io/hbox/
Manage your VirtualBox infrastructure the free way!
noteirak
Site Moderator
 
Posts: 5198
Joined: 13. Jan 2012, 11:14
Primary OS: Debian other
VBox Version: OSE Debian
Guest OSses: Debian, Win 2k8, Win 7

Re: Code Samples

Postby noteirak » 13. Aug 2015, 21:35

API 4.x

4.3

List running VMs - Java
Code: Select all   Expand viewCollapse view
/*
 * DO WHAT THE SPAM_SEARCH YOU WANT TO PUBLIC LICENSE
 * Version 2, December 2004
 *
 * Everyone is permitted to copy and distribute verbatim or modified
 * copies of this license document, and changing it is allowed as long
 * as the name is changed.
 *
 * DO WHAT THE SPAM_SEARCH YOU WANT TO PUBLIC LICENSE
 * TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 *
 * 0. You just DO WHAT THE SPAM_SEARCH YOU WANT TO.
 */

public class ListRunningVms {
   
   public static void main(String[] args) {
     
      VirtualBoxManager vboxManager = VirtualBoxManager.createInstance(null);
      try {
         vboxManager.connect("http://localhost:18083", "user", "password"); // only if you are using WebServices Bindings
         IVirtualBox vbox = vboxManager.getVBox();
         for (IMachine vm : vbox.getMachines()) {
            if (MachineState.Running.equals(vm.getState())) {
               System.out.println(vm.getName()+ " "+vm.getId());
            }
         }
      } finally {
         vboxManager.disconnect(); // only if you are using WebServices Bindings
         vboxManager.cleanup();
      }
   }
   
}

Start VM in Headless mode - Java
Code: Select all   Expand viewCollapse view
/*
 * DO WHAT THE SPAM_SEARCH YOU WANT TO PUBLIC LICENSE
 * Version 2, December 2004
 *
 * Everyone is permitted to copy and distribute verbatim or modified
 * copies of this license document, and changing it is allowed as long
 * as the name is changed.
 *
 * DO WHAT THE SPAM_SEARCH YOU WANT TO PUBLIC LICENSE
 * TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 *
 * 0. You just DO WHAT THE SPAM_SEARCH YOU WANT TO.
 */

import org.virtualbox_4_3.IMachine;
import org.virtualbox_4_3.IProgress;
import org.virtualbox_4_3.ISession;
import org.virtualbox_4_3.VirtualBoxManager;

/**
 * The following piece of code assume that
 * - WebServices server is running
 * - Authentication is disabled
 *
 * To disable authentication, run on the host before starting the server:
 *
 * vboxmanage setproperty websrvauthlibrary null
 *
 */
public class StartVM {

   public static void main(String[] args) {
      VirtualBoxManager vboxManager = VirtualBoxManager.createInstance(null);
      vboxManager.connect("http://localhost:18083", "", "");

      try {
         IMachine machine = vboxManager.getVBox().findMachine("machineName");
         ISession session = vboxManager.getSessionObject();
         IProgress p = machine.launchVMProcess(session, "headless", null);
         try {
            p.waitForCompletion(-1);
            if (p.getResultCode() != 0) {
               System.out.println("Machine failed to start: " + p.getErrorInfo().getText());
            }
         } finally {
            session.unlockMachine();
         }
      } finally {
         vboxManager.disconnect();
         vboxManager.cleanup();
      }
   }

}

Run Guest Process and Read Stdout - Java
Code: Select all   Expand viewCollapse view
/*
 *            DO WHAT THE SPAM_SEARCH YOU WANT TO PUBLIC LICENSE
 *                     Version 2, December 2004
 *
 * Everyone is permitted to copy and distribute verbatim or modified
 *  copies of this license document, and changing it is allowed as long
 * as the name is changed.
 *
 *            DO WHAT THE SPAM_SEARCH YOU WANT TO PUBLIC LICENSE
 *   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 *
 *  0. You just DO WHAT THE SPAM_SEARCH YOU WANT TO.
 */

import java.util.Arrays;
import org.virtualbox_4_3.GuestSessionStatus;
import org.virtualbox_4_3.IEvent;
import org.virtualbox_4_3.IEventListener;
import org.virtualbox_4_3.IEventSource;
import org.virtualbox_4_3.IGuestProcess;
import org.virtualbox_4_3.IGuestSession;
import org.virtualbox_4_3.IMachine;
import org.virtualbox_4_3.ISession;
import org.virtualbox_4_3.LockType;
import org.virtualbox_4_3.ProcessCreateFlag;
import org.virtualbox_4_3.ProcessWaitForFlag;
import org.virtualbox_4_3.ProcessWaitResult;
import org.virtualbox_4_3.VBoxEventType;
import org.virtualbox_4_3.VirtualBoxManager;

public class GuestSessionProcess {

   private static String errorIfNull(String systemProperty) {
      String value = System.getProperty(systemProperty);
      if (value != null) {
         return value;
      } else {
         throw new RuntimeException(systemProperty + " is not set");
      }
   }
   
   public static void main(String[] args) {
      String vmId = errorIfNull("vbox.vm");
      String guestUser = errorIfNull("vbox.guest.user");
      String guestPass = errorIfNull("vbox.guest.pass");
      String exec = errorIfNull("vbox.guest.exec");
     
      System.out.println("Starting");
      VirtualBoxManager vboxManager = VirtualBoxManager.createInstance(null);
      try {
         if (System.getProperty("vbox.ws") != null) {
            String host = System.getProperty("vbox.ws.host", "http://localhost:18083");
            String user = System.getProperty("vbox.ws.user", "");
            String pass = System.getProperty("vbox.ws.pass", "");
            vboxManager.connect(host, user, pass);
         }
         System.out.println("Connected");
         try {
            ISession session = vboxManager.getSessionObject();
            IMachine vm = vboxManager.getVBox().findMachine(vmId);
            vm.lockMachine(session, LockType.Shared);
            try {
               System.out.println("Machine locked");
               IGuestSession guestSess = session.getConsole().getGuest().createSession(guestUser, guestPass, null, null);
               try {
                  System.out.println("Session created");

                  guestSess.waitFor(1L, 30 * 1000L);
                  if (!guestSess.getStatus().equals(GuestSessionStatus.Started)) {
                     throw new RuntimeException("Guest session did not start after 30 sec");
                  }
                  IGuestProcess process = guestSess.processCreate(exec, null, null, Arrays.asList(ProcessCreateFlag.WaitForStdOut), 0L);

                  IEventSource es = process.getEventSource();
                  IEventListener el = es.createListener();
                  es.registerListener(el, Arrays.asList(VBoxEventType.Any), false);

                  try {
                     System.out.println("Guest process created");
                     ProcessWaitResult pwr = process.waitFor((long) ProcessWaitForFlag.Start.value(), 30 * 1000L);
                     System.out.println("Process wait result: " + pwr);
                     boolean keepLooping = true;
                     do {
                        IEvent ev = es.getEvent(el, 200);
                        if (ev != null) {
                           es.eventProcessed(el, ev);
                        }
                        /* This is how you should normally do it, but waiting for Stdout is not currently implemented - see http://hyperbox.altherian.org/kb/guessProcessHandling.txt
                        ProcessWaitResult wr = process.waitForArray(Arrays.asList(ProcessWaitForFlag.StdOut, ProcessWaitForFlag.Terminate), 200L);
                        System.out.println("Process wait result: " + wr);
                         */
                        byte[] stdOut = process.read(1L, 64L, 0L);
                        System.out.print(new String(stdOut));
                        keepLooping = !process.getStatus().toString().contains("Terminated");
                     } while (keepLooping);
                     System.out.println("Process exit code: " + process.getExitCode());
                  } finally {
                     es.unregisterListener(el);
                     if (!process.getStatus().toString().contains("Terminated")) {
                        process.terminate();
                     }
                  }
               } finally {
                  System.out.println("Session close");
                  guestSess.close();
               }
            } catch (Throwable t) {
               t.printStackTrace();
            } finally {
               System.out.println("Machine unlock");
               session.unlockMachine();
            }
         } finally {
            if (System.getProperty("vbox.ws") != null) {
               vboxManager.disconnect();
            }
            System.out.println("Disconnected");
         }
      } finally {
         vboxManager.cleanup();
         System.out.println("Closing");
      }
   }
   
}

Catch events using passive mode - Java
Code: Select all   Expand viewCollapse view
/*
 *
 *  Written in 2015 by Maxime Dor
 *
 *  http://kamax.io/
 *
 *  To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
 *  Full license can be found at http://creativecommons.org/publicdomain/zero/1.0/
 *
 */


import java.util.Arrays;
import java.util.List;
import org.virtualbox_4_3.CleanupMode;
import org.virtualbox_4_3.IEvent;
import org.virtualbox_4_3.IEventListener;
import org.virtualbox_4_3.IMachine;
import org.virtualbox_4_3.IMachineRegisteredEvent;
import org.virtualbox_4_3.IMachineStateChangedEvent;
import org.virtualbox_4_3.IProgress;
import org.virtualbox_4_3.ISession;
import org.virtualbox_4_3.ISessionStateChangedEvent;
import org.virtualbox_4_3.SessionState;
import org.virtualbox_4_3.VBoxEventType;
import org.virtualbox_4_3.VirtualBoxManager;


public class CatchEvents_4_3 {

    static VirtualBoxManager mgr;
    static Thread listener;

    public static void main(String args[]) {
        String vmName = Long.toString(System.currentTimeMillis()); // get a random VM name to use later

        System.out.println("Creating VirtualBox client instance");
        mgr = VirtualBoxManager.createInstance(null);
        try {
            /*
             * This line is only required if you are using the WebServices to connect.
             * Also, change "user" and "password" to local credentials on the machine running the web services, or set authentication to null.
             * To do so, you can start vboxwevsrv with "-A null" argument or use vboxmanage to make it permanent.
             */
            System.out.println("Connecting to VirtualBox using Web Services");
            mgr.connect("http://localhost:18083", "user", "password"); // only if you are using WebServices Bindings
            System.out.println("Connected to VirtualBox using Web Services");

            /*
             * We will run the event worker in a separate thread like it would normally be done.
             */
            listener = new EventWorker();
            listener.start();

            try {
                /*
                 * We create an empty machine, we save its settings to disk (to actually make it really exist) than we register it.
                 * This will trigger IMachineRegisteredEvent.
                 */
                IMachine vm = mgr.getVBox().createMachine(null, vmName, null, "Other", null);
                vm.saveSettings();
                mgr.getVBox().registerMachine(vm);

                vm = mgr.getVBox().findMachine(vmName); // we fetch the machine object again just to be safe
                ISession session = mgr.getSessionObject();
                IProgress p = vm.launchVMProcess(session, "headless", null);
                p.waitForCompletion(-1); // we wait until the starting process has finished
                try {
                    if (p.getResultCode() != 0) { // error when starting the VM, we don't continue further
                        throw new RuntimeException(p.getErrorInfo().getText());
                    } else { // VM got started, OnMachineStateChanged triggered two times at this point
                        // let's now power down the VM
                        p = session.getConsole().powerDown();
                        p.waitForCompletion(-1);
                        if (p.getResultCode() != 0) { // we failed to stop the VM
                            throw new RuntimeException(p.getErrorInfo().getText());
                        } else {
                            // VM got stopped, OnMachineStateChanged triggered several times at this point
                        }
                    }
                } finally {
                    // we do not need the lock any further and is required for for IMachine::unregister()
                    session.unlockMachine();

                    // since unlock is not instant, we need to wait until the unlock is done or unregister() will fail.
                    while (!SessionState.Unlocked.equals(vm.getSessionState())) {
                        try {
                            System.out.println("Waiting for session unlock...");
                            Thread.sleep(1000L);
                        } catch (InterruptedException e) {
                            System.err.println("Interrupted while waiting for session to be unlocked");
                        }
                    }

                    // vm.unregister() will trigger IMachineRegisteredEvent.
                    System.out.println("Deleting machine");
                    vm.deleteConfig(vm.unregister(CleanupMode.DetachAllReturnHardDisksOnly));
                }
            } finally { // we instruct the Event Worker to stop and wait 5 sec for it to do so
                listener.interrupt();
                try {
                    listener.join(5000); // we wait on the thread
                } catch (InterruptedException e) {
                    System.err.println("Interrupted while waiting for EventWorker to stop");
                }

                if (listener.isAlive()) {
                    System.err.println("Event worked did not stop in a timely fashion");
                } else {
                    System.out.println("Event worked stopped");
                }
            }
        } finally {
            mgr.disconnect(); // only if you are using WebServices Bindings
            mgr.cleanup();
            System.out.println("Disconnected from VirtualBox - bye bye!");
        }
    }

    static class EventWorker extends Thread {

        IEventListener el;

        @Override
        public void run() {
            System.out.println("EventWorker started");
            el = mgr.getVBox().getEventSource().createListener(); // we create the object that will fetch and queue the events for us

            /*
             * We register for the events that we are interested in.
             * If we wanted all of them, we would use VBoxEventType.Any
             *
             * Not all events will be visible here. If we want events for a specific machine (like Clipboard mode change),
             * we need to use the event source of that specific machine - see IMachine::getEventSource()
             */
            List<VBoxEventType> types = Arrays.asList(VBoxEventType.OnSessionStateChanged, VBoxEventType.OnMachineStateChanged,
                    VBoxEventType.OnMachineRegistered);
            mgr.getVBox().getEventSource().registerListener(el, types, false);

            try {
                while(!isInterrupted()) {
                    mgr.waitForEvents(0); // Needed to clear the internal event queue, see https://www.virtualbox.org/ticket/13647
                    IEvent rawEvent = mgr.getVBox().getEventSource().getEvent(el, 1000);
                    if (rawEvent == null) { // we waited but no event came
                        continue; // we loop again and skip the code below
                    }

                    try {
                        System.out.println("Got event of type " + rawEvent.getType());

                        if (VBoxEventType.OnSessionStateChanged.equals(rawEvent.getType())) {
                            // It is important to use the queryInterface() on the expected class, simple casting will not work.
                            ISessionStateChangedEvent event = ISessionStateChangedEvent.queryInterface(rawEvent);
                            System.out.println("Session state changed to " + event.getState() + " for machine " + event.getMachineId());
                        }

                        if (VBoxEventType.OnMachineRegistered.equals(rawEvent.getType())) { // we check the event type
                            // It is important to use the queryInterface() on the expected class, simple casting will not work.
                            IMachineRegisteredEvent event = IMachineRegisteredEvent.queryInterface(rawEvent);
                            System.out.println("Machine " + event.getMachineId() + " has been " + (event.getRegistered() ? "registered" : "unregistered"));
                        }

                        if (VBoxEventType.OnMachineStateChanged.equals(rawEvent.getType())) {
                            // It is important to use the queryInterface() on the expected class, simple casting will not work.
                            IMachineStateChangedEvent event = IMachineStateChangedEvent.queryInterface(rawEvent);
                            System.out.println("Machine " + event.getMachineId() + " state changed to " + event.getState());
                        }
                    } finally {
                        // We mark the event as processed so ressources can be released. We do this in a finally block to ensure it is done no matter what.
                        mgr.getVBox().getEventSource().eventProcessed(el, rawEvent);
                    }
                }
            } catch (Throwable t) {
                t.printStackTrace();
            } finally {
                mgr.getVBox().getEventSource().unregisterListener(el); // we are done fetching events, so we free the listener
                System.out.println("EventWorker finished");
            }
        }

    }

}
Last edited by socratis on 8. Nov 2016, 07:47, edited 1 time in total.
Reason: Included the code locally.
Hyperbox - Virtual Infrastructure Manager - https://kamax.io/hbox/
Manage your VirtualBox infrastructure the free way!
noteirak
Site Moderator
 
Posts: 5198
Joined: 13. Jan 2012, 11:14
Primary OS: Debian other
VBox Version: OSE Debian
Guest OSses: Debian, Win 2k8, Win 7

Re: Code Samples

Postby AdityaM » 8. Nov 2016, 06:36

Hello,
I am not able to access the Link for Code samples listed here. Can you share the code samples through updated links or let me know if there is any other means to get the Code samples. It would be more helpful to get some sample codes for using SDK APIs in C++.
Thanks
AdityaM
 
Posts: 31
Joined: 8. Nov 2016, 06:12

Re: Code Samples

Postby socratis » 8. Nov 2016, 07:52

I had no problem accessing the code (since I just copied/pasted here), but, you're right in a way. The code should be here, not in a 3rd party site. I edited the posts to make it so. I left the links in case there is an update to the code.

AdityaM wrote:It would be more helpful to get some sample codes for using SDK APIs in C++.
This is a user discussion site, so I guess that the only contributor felt more comfortable in Java. If you manage to get something working in C++, please feel free to include your sample code here as well. The more "generic", the better.
Do NOT send me Personal Messages (PMs) for troubleshooting, they are simply deleted.
Do NOT reply with the "QUOTE" button, please use the "POST REPLY", at the bottom of the form.
If you obfuscate any information requested, I will obfuscate my response. These are virtual UUIDs, not real ones.
socratis
Site Moderator
 
Posts: 26876
Joined: 22. Oct 2010, 11:03
Location: Greece
Primary OS: Mac OS X other
VBox Version: PUEL
Guest OSses: Win(*>98), Linux*, OSX>10.5


Return to The VirtualBox API

Who is online

Users browsing this forum: No registered users and 3 guests