Revision 0c7524b3

View differences:

src/oca/java/build.sh
76 76
      -subpackages org.opennebula \
77 77
      -windowtitle 'OpenNebula Cloud API' \
78 78
      -doctitle 'OpenNebula Cloud API Specification' \
79
      -header '<b>OpenNebula</b><br><font size="-1">Java API</font>' \
79
      -header '<b>OpenNebula</b><br><font size="-1">Cloud API</font>' \
80 80
      -bottom 'Visit <a
81 81
href="http://opennebula.org/">OpenNebula.org</a><br>Copyright 2002-2010 &copy;
82 82
OpenNebula Project Leads (OpenNebula.org).'
src/oca/java/share/examples/SessionInit.java
24 24
        try
25 25
        {
26 26
            Client oneClient = new Client();
27
            System.out.println(" ok");
27 28
        }
28 29
        catch (Exception e)
29 30
        {
30 31
            System.out.println(e.getMessage());
31 32
        }
32 33

  
33
        System.out.println("ok");
34 34

  
35
        System.out.println("Wrong session initialization...");
35
        System.out.println("Forcing a wrong user/password initialization...");
36 36
        try
37 37
        {
38
            // The secret string should be user:password. The url is null, so it
39
            // will be set to default.
38 40
            Client oneClient = new Client("wrong_password_token",null);
39 41
        }
40 42
        catch (Exception e)
41 43
        {
42 44
            System.out.println("\t" + e.getMessage());
43 45
        }
46

  
47
        System.out.println("Forcing a wrong url initialization...");
48
        try
49
        {
50
            // The HTTP is misspelled
51
            Client oneClient = new Client(null,"HTP://localhost:2633/RPC2");
52
        }
53
        catch (Exception e)
54
        {
55
            System.out.println("\t" + e.getMessage());
56
        }
44 57
    }
45 58
}
src/oca/java/share/examples/SessionInit.sh
1
#!/bin/bash
2

  
3
java -cp ../../lib/*:../../jar/*:. SessionInit
src/oca/java/share/examples/UserSample.java
22 22
{
23 23
    public static void main(String[] args)
24 24
    {
25
        // Let's try some of the OpenNebula Cloud API functionality.
26

  
27
        // First of all, a Client object has to be created.
28
        // Here the client will try to connect to OpenNebula using the default
29
        // options: the auth. file will be assumed to be at $ONE_AUTH, and the
30
        // endpoint will be set to the environment variable $ONE_XMLRPC.
25 31
        Client oneClient;
26 32

  
27 33
        try
......
34 40
            return;
35 41
        }
36 42

  
43
        // We will create a user pool and query some information.
44
        // The info method retrieves and saves internally the information
45
        // from OpenNebula.
37 46
        UserPool    userpool = new UserPool(oneClient);
38 47
        OneResponse rc       = userpool.info();
39 48

  
49
        // The response can be an error, in which case we have access to a
50
        // human-readable error message.
40 51
        if (rc.isError())
41 52
        {
42 53
            System.out.println(rc.getErrorMessage());
43 54
            return;
44 55
        }
45 56

  
57
        // Let's find out the current state of the users pool
46 58
        printUserPool(userpool);
47 59

  
60
        // Now we will try to allocate a new user
48 61
        System.out.println("Allocating new user (javaUser,javaPassword)...");
49 62
        rc = User.allocate(oneClient, "javaUser", "javaPassword");
50 63

  
......
54 67
            return;
55 68
        }
56 69

  
57
        User javaUser = new User(Integer.parseInt(rc.getMessage()),oneClient);
70
        // If the allocation was successful, then the response message contains
71
        // the new user's ID.
72
        int userID = Integer.parseInt( rc.getMessage() );
73
        System.out.println("The allocation request returned this ID: " + userID);
74

  
75
        // We can create a representation for the new user, using the returned
76
        // user-ID
77
        User javaUser = new User(userID, oneClient);
58 78

  
79
        // And request its information
59 80
        rc = javaUser.info();
60 81

  
82
        // Alternatively we could have requested the user's info with the
83
        // static info method:
84
        // rc = User.info(oneClient, userID);
85
        // and processed the xml returned in the message of the OneResponse.
86

  
61 87
        if (rc.isError())
62 88
        {
63 89
            System.out.println(rc.getErrorMessage());
64 90
            return;
65 91
        }
66 92

  
93
        // This is how the info returned looks like...
67 94
        System.out.println("Info for " + javaUser.xpath("name") + "...");
68 95
        System.out.println(rc.getMessage());
69 96

  
97
        // Wait a second... what was that xpath method for?
98
        // Now that we have the user's info loaded, we can use xpath expressions
99
        // without parsing and initializing any xml, as simple as
100
        // String name = javaUser.xpath("name");
101

  
102
        // The user pool information is now outdated, so we need to call the
103
        // info method again
70 104
        userpool.info();
71 105
        printUserPool(userpool);
72 106

  
107
        // Let's delete this new user, using its ID
73 108
        System.out.println("Deleting " + javaUser.getName() + "...");
74 109
        rc = javaUser.delete();
75 110

  
......
79 114
            return;
80 115
        }
81 116

  
117
        // Now the pool information is outdated again, it is time to reload it.
82 118
        userpool.info();
83 119
        printUserPool(userpool);
84 120
    }
......
89 125
        System.out.println("Number of users: " + up.getLength());
90 126
        System.out.println("User ID\t\tName\t\tEnabled");
91 127

  
128
        // You can use the for-each loops with the OpenNebula pools
92 129
        for( User user : up )
93 130
        {
94 131
            String id   = user.getId();
src/oca/java/share/examples/UserSample.sh
1
#!/bin/bash
2

  
3
java -cp ../../lib/*:../../jar/*:. UserSample
src/oca/java/share/examples/VMachineSample.java
1
/*******************************************************************************
2
 * Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org)
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *   http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 ******************************************************************************/
16

  
17
import org.opennebula.client.Client;
18
import org.opennebula.client.OneResponse;
19
import org.opennebula.client.vm.VirtualMachine;
20
import org.opennebula.client.vm.VirtualMachinePool;
21

  
22
public class VMachineSample{
23

  
24
    public static void main(String[] args)
25
    {
26
        // Let's try some of the OpenNebula Cloud API functionality for VMs.
27

  
28
        // First of all, a Client object has to be created.
29
        // Here the client will try to connect to OpenNebula using the default
30
        // options: the auth. file will be assumed to be at $ONE_AUTH, and the
31
        // endpoint will be set to the environment variable $ONE_XMLRPC.
32
        Client oneClient;
33

  
34
        try
35
        {
36
            oneClient = new Client();
37

  
38
            // We will try to create a new virtual machine. The first thing we
39
            // need is an OpenNebula virtual machine template.
40

  
41
            // This VM template is a valid one, but it will probably fail to run
42
            // if we try to deploy it; the path for the image is unlikely to
43
            // exist.
44
            String vmTemplate =
45
                  "NAME     = vm_from_java    CPU = 0.1    MEMORY = 64\n"
46
                + "DISK     = [\n"
47
                + "\tsource   = \"/home/user/vmachines/ttylinux/ttylinux.img\",\n"
48
                + "\ttarget   = \"hda\",\n"
49
                + "\treadonly = \"no\" ]\n"
50
                + "# NIC     = [ NETWORK = \"Non existing network\" ]\n"
51
                + "FEATURES = [ acpi=\"no\" ]";
52

  
53
            // You can try to uncomment the NIC line, in that case OpenNebula
54
            // won't be able to insert this machine in the database.
55

  
56
            System.out.println("Virtual Machine Template:\n" + vmTemplate);
57
            System.out.println();
58

  
59
            System.out.print("Trying to allocate the virtual machine... ");
60
            OneResponse rc = VirtualMachine.allocate(oneClient, vmTemplate);
61

  
62
            if( rc.isError() )
63
            {
64
                System.out.println( "failed!");
65
                throw new Exception( rc.getErrorMessage() );
66
            }
67

  
68
            // The response message is the new VM's ID
69
            int newVMID = Integer.parseInt(rc.getMessage());
70
            System.out.println("ok, ID " + newVMID + ".");
71

  
72
            // We can create a representation for the new VM, using the returned
73
            // VM-ID
74
            VirtualMachine vm = new VirtualMachine(newVMID, oneClient);
75

  
76
            // Let's hold the VM, so the scheduler won't try to deploy it
77
            System.out.print("Trying to hold the new VM... ");
78
            rc = vm.hold();
79

  
80
            if(rc.isError())
81
            {
82
                System.out.println("failed!");
83
                throw new Exception( rc.getErrorMessage() );
84
            }
85
            else
86
                System.out.println("ok.");
87

  
88
            // And now we can request its information.
89
            rc = vm.info();
90

  
91
            if(rc.isError())
92
                throw new Exception( rc.getErrorMessage() );
93

  
94
            System.out.println();
95
            System.out.println(
96
                    "This is the information OpenNebula stores for the new VM:");
97
            System.out.println(rc.getMessage() + "\n");
98

  
99
            // This VirtualMachine object has some helpers, so we can access its
100
            // attributes easily (remember to load the data first using the info
101
            // method).
102
            System.out.println("The new VM " +
103
                    vm.getName() + " has status: " + vm.status());
104

  
105
            // And we can also use xpath expressions
106
            System.out.println("The path of the disk is");
107
            System.out.println( "\t" + vm.xpath("template/disk/source") );
108

  
109
            // Let's delete the VirtualMachine object.
110
            vm = null;
111

  
112
            // The reference is lost, but we can ask OpenNebula about the VM
113
            // again. This time however, we are going to use the VM pool
114
            VirtualMachinePool vmPool = new VirtualMachinePool(oneClient);
115
            // Remember that we have to ask the pool to retrieve the information
116
            // from OpenNebula
117
            rc = vmPool.info();
118

  
119
            if(rc.isError())
120
                throw new Exception( rc.getErrorMessage() );
121

  
122
            System.out.println(
123
                    "\nThese are all the Virtual Machines in the pool:");
124
            for ( VirtualMachine vmachine : vmPool )
125
            {
126
                System.out.println("\tID :" + vmachine.getId() +
127
                                   ", Name :" + vmachine.getName() );
128

  
129
                // Check if we have found the VM we are looking for
130
                if ( vmachine.getId().equals( ""+newVMID ) )
131
                {
132
                    vm = vmachine;
133
                }
134
            }
135

  
136
            // We have also some useful helpers for the actions you can perform
137
            // on a virtual machine, like cancel:
138
            rc = vm.cancel();
139
            System.out.println("\nTrying to cancel the VM " + vm.getId() +
140
                                " (should fail)...");
141

  
142
            // This is all the information you can get from the OneResponse:
143
            System.out.println("\tOpenNebula response");
144
            System.out.println("\t  Error:  " + rc.isError());
145
            System.out.println("\t  Msg:    " + rc.getMessage());
146
            System.out.println("\t  ErrMsg: " + rc.getErrorMessage());
147

  
148
            rc = vm.finalizeVM();
149
            System.out.println("\nTrying to finalize (delete) the VM " +
150
                                vm.getId() + "...");
151

  
152
            System.out.println("\tOpenNebula response");
153
            System.out.println("\t  Error:  " + rc.isError());
154
            System.out.println("\t  Msg:    " + rc.getMessage());
155
            System.out.println("\t  ErrMsg: " + rc.getErrorMessage());
156

  
157

  
158
        }
159
        catch (Exception e)
160
        {
161
            System.out.println(e.getMessage());
162
        }
163

  
164

  
165
    }
166

  
167
    public static void printVMachinePool (VirtualMachinePool vmPool)
168
    {
169
        System.out.println("--------------------------------------------");
170
        System.out.println("Number of VMs: " + vmPool.getLength());
171
        System.out.println("User ID\t\tName\t\tEnabled");
172

  
173
        // You can use the for-each loops with the OpenNebula pools
174
        for( VirtualMachine vm : vmPool )
175
        {
176
            String id   = vm.getId();
177
            String name = vm.getName();
178
            String enab = vm.xpath("enabled");
179

  
180
            System.out.println(id+"\t\t"+name+"\t\t"+enab);
181
        }
182

  
183
        System.out.println("--------------------------------------------");
184
    }
185
}
src/oca/java/share/examples/VMachineSample.sh
1
#!/bin/bash
2

  
3
java -cp ../../lib/*:../../jar/*:. VMachineSample
src/oca/java/src/org/opennebula/client/Client.java
36 36
 * xml-rpc calls.
37 37
 *
38 38
 */
39
public class Client {
39
public class Client{
40 40

  
41 41
    //--------------------------------------------------------------------------
42 42
    //  PUBLIC INTERFACE
......
54 54
    public Client() throws Exception
55 55
    {
56 56
        setOneAuth(null);
57
        setOneEndPoint(null);        
57
        setOneEndPoint(null);
58 58
    }
59 59

  
60 60
    /**
......
160 160
            if(token.length != 2 )
161 161
            {
162 162
                throw new Exception("Wrong format for authorization string: "
163
                    + oneSecret);
163
                    + oneSecret + "\nFormat expected is user:password");
164 164
            }
165 165

  
166 166
            MessageDigest md = MessageDigest.getInstance("SHA-1");
src/oca/java/src/org/opennebula/client/OneResponse.java
20 20
 * carries a boolean indicating if it is an error. It can also contain a 
21 21
 * success message, or an error message. 
22 22
 */
23
public class OneResponse {
23
public class OneResponse{
24 24
    /**
25 25
     * Creates a new response.
26 26
     * 
......
34 34
        this.success = success;
35 35
        this.msg     = message;
36 36
    }
37
	
37

  
38 38
    /**
39 39
     * Returns true if the call resulted in error.
40 40
     * 
......
44 44
    {
45 45
        return !success;
46 46
    }
47
	
47

  
48 48
    /**
49 49
     * Returns a string containing the error message, or null
50 50
     * if the response isn't an error.
......
56 56
    {
57 57
        return success ? null : msg;
58 58
    }
59
	
59

  
60 60
    /**
61 61
     * Returns a string containing the response information, or
62 62
     * null if the response was an error. Note that the success
src/oca/java/src/org/opennebula/client/Pool.java
99 99
     */
100 100
    public PoolElement item(int index)
101 101
    {
102
        PoolElement the_element = null;
102
        PoolElement theElement = null;
103 103

  
104 104
        if (poolElements != null)
105 105
        {
......
107 107

  
108 108
            if (node != null)
109 109
            {
110
                the_element = factory(node);
110
                theElement = factory(node);
111 111
            }
112 112
        }
113 113

  
114
        return the_element;
114
        return theElement;
115 115
    }
116 116

  
117 117
    /**
......
122 122
    {
123 123
        return poolElements == null ? 0 : poolElements.getLength();
124 124
    }
125
}
125
}
src/oca/java/src/org/opennebula/client/PoolElement.java
44 44
     * Creates a new PoolElement with the specified attributes.
45 45
     * @param id Id of the element.
46 46
     * @param client XML-RPC Client.
47
     * @param root Name of the xml's root element.
48 47
     */
49 48
    protected PoolElement(int id, Client client)
50 49
    {
......
63 62
     * 
64 63
     * @param client XML-RPC Client.
65 64
     * @param xmlElement XML representation of the element.
66
     * @param root Name of the xml's root element.
67 65
     */
68 66
    protected PoolElement(Node xmlElement, Client client)
69 67
    {
src/oca/java/src/org/opennebula/client/package.html
1
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
2
<html>
3
<head>
4
</head>
5
<body bgcolor="white">
6
<p>
7
Provides the Java bindings for the OpenNebula Cloud API (OCA).
8
</p>
9
<p>
10
The included classes can be used as simple wrappers for the XML-RPC calls
11
supported by the OpenNebula core, or as objects that store the information
12
and provide useful helpers.
13
</p>
14
<h2>Requirements</h2>
15
<p>
16
Apart from this jar file, you need to add to the project's build-path the
17
<a href="http://ws.apache.org/xmlrpc/index.html">Apache XML-RPC</a> library.
18
</p>
19
<p>
20
You can download it from Apache's
21
<a href="http://www.apache.org/dyn/closer.cgi/ws/xmlrpc/">distribution directory</a>.
22
The jar files you need are xmlrpc-client-*.jar, ws-commons-util-*.jar and xmlrpc-common-*.jar.</p>
23

  
24
<h2>Related Documentation</h2>
25
<p>
26
Please visit the <a href="http://opennebula.org">OpenNebula</a> site for general information,
27
and consult the <a href="http://opennebula.org/doku.php?id=documentation">documentation section</a>
28
to find up to date references, tutorials, and more.
29
</p>
30
<p>
31
You can learn about the OpenNebula XML-RPC API <a href="http://opennebula.org/doku.php?id=documentation:rel1.4:api">here</a>.
32
</p>
33

  
34
<!-- Put @see and @since tags down here. -->
35

  
36
</body>
37
</html>
src/oca/java/src/org/opennebula/client/user/User.java
25 25
 * This class represents an OpenNebula User.
26 26
 * It also offers static XML-RPC call wrappers.
27 27
 */
28
public class User extends PoolElement {
28
public class User extends PoolElement{
29 29

  
30
private static final String ROOT_NAME = "USER";
31
	
32
	private static final String METHOD_PREFIX = "user.";
33
	private static final String ALLOCATE = METHOD_PREFIX + "allocate";
34
	private static final String INFO     = METHOD_PREFIX + "info";
35
	private static final String DELETE   = METHOD_PREFIX + "delete";
36
	
37
	/**
38
	 * Creates a new User representation.
39
	 * 
40
	 * @param id The user id (uid).
41
	 * @param client XML-RPC Client.
42
	 */
43
	public User(int id, Client client) 
44
	{
45
	    super(id, client);
46
	}
30
    private static final String METHOD_PREFIX   = "user.";
31
    private static final String ALLOCATE        = METHOD_PREFIX + "allocate";
32
    private static final String INFO            = METHOD_PREFIX + "info";
33
    private static final String DELETE          = METHOD_PREFIX + "delete";
34
    
35
    /**
36
     * Creates a new User representation.
37
     * 
38
     * @param id The user id (uid).
39
     * @param client XML-RPC Client.
40
     */
41
    public User(int id, Client client) 
42
    {
43
        super(id, client);
44
    }
47 45

  
48
	/**
49
	 * @see PoolElement 
50
	 */
51
	protected User(Node xmlElement, Client client)
52
	{
46
    /**
47
     * @see PoolElement 
48
     */
49
    protected User(Node xmlElement, Client client)
50
    {
53 51
        super(xmlElement, client);
54
	}
55
	
56
	
57
	// =================================
58
	// Static XML-RPC methods
59
	// =================================
60
	
61
	/**
62
	 * Allocates a new user in OpenNebula.
63
	 * 
64
	 * @param client XML-RPC Client.
65
	 * @param username Username for the new user.
66
	 * @param password Password for the new user 
67
	 * @return If successful the message contains
68
	 * the associated id (int uid) generated for this user.
69
	 */
70
	public static OneResponse allocate(Client client,
52
    }
53

  
54

  
55
    // =================================
56
    // Static XML-RPC methods
57
    // =================================
58

  
59
    /**
60
     * Allocates a new user in OpenNebula.
61
     * 
62
     * @param client XML-RPC Client.
63
     * @param username Username for the new user.
64
     * @param password Password for the new user 
65
     * @return If successful the message contains
66
     * the associated id (int uid) generated for this user.
67
     */
68
    public static OneResponse allocate(Client client,
71 69
                                       String username,
72 70
                                       String password)
73 71
    {
74
		return client.call(ALLOCATE, username, password);
75
	}
72
        return client.call(ALLOCATE, username, password);
73
    }
76 74

  
77
	/** Retrieves the information of the given user.
78
	 * 
79
	 * @param client XML-RPC Client.
80
	 * @param id The user id (uid) for the user to
81
	 * retrieve the information from. 
82
	 * @return if successful the message contains the
83
	 * string with the information about the user returned by OpenNebula. 
84
	 */
85
	public static OneResponse info(Client client, int id)
75
    /** Retrieves the information of the given user.
76
     * 
77
     * @param client XML-RPC Client.
78
     * @param id The user id (uid) for the user to
79
     * retrieve the information from. 
80
     * @return if successful the message contains the
81
     * string with the information about the user returned by OpenNebula. 
82
     */
83
    public static OneResponse info(Client client, int id)
86 84
    {
87
		return client.call(INFO, id);
88
	}
89
	
90
	/**
91
	 * Deletes a user from OpenNebula.
92
	 * 
93
	 * @param client XML-RPC Client.
94
	 * @param id The user id (uid) of the target user we want to delete. 
95
	 * @return If an error occurs the error message contains the reason.
96
	 */
97
	public static OneResponse delete(Client client, int id)
85
        return client.call(INFO, id);
86
    }
87
    
88
    /**
89
     * Deletes a user from OpenNebula.
90
     * 
91
     * @param client XML-RPC Client.
92
     * @param id The user id (uid) of the target user we want to delete. 
93
     * @return If an error occurs the error message contains the reason.
94
     */
95
    public static OneResponse delete(Client client, int id)
98 96
    {
99
		return client.call(DELETE, id);
100
	}
97
        return client.call(DELETE, id);
98
    }
101 99

  
102
	// =================================
103
	// Instanced object XML-RPC methods
104
	// =================================
105
	
106
	/**
107
	 * Loads the xml representation of the user.
108
	 * The info is also stored internally.
109
	 * 
110
	 * @see User#info(Client, int)
111
	 */
112
	public OneResponse info()
100
    // =================================
101
    // Instanced object XML-RPC methods
102
    // =================================
103
    
104
    /**
105
     * Loads the xml representation of the user.
106
     * The info is also stored internally.
107
     * 
108
     * @see User#info(Client, int)
109
     */
110
    public OneResponse info()
113 111
    {
114
		OneResponse response = info(client, id);
112
        OneResponse response = info(client, id);
113

  
114
        super.processInfo(response);
115 115

  
116
		super.processInfo(response);
116
        return response;
117
    }
117 118

  
118
		return response;
119
	}
120
	
121
	/**
122
	 * Deletes the user from OpenNebula.
123
	 * 
124
	 * @see User#delete(Client, int)
125
	 */
126
	public OneResponse delete()
119
    /**
120
     * Deletes the user from OpenNebula.
121
     * 
122
     * @see User#delete(Client, int)
123
     */
124
    public OneResponse delete()
127 125
    {
128
		return delete(client, id);
129
	}
126
        return delete(client, id);
127
    }
130 128
}
src/oca/java/src/org/opennebula/client/user/UserPool.java
29 29
 * This class represents an OpenNebula user pool.
30 30
 * It also offers static XML-RPC call wrappers.
31 31
 */
32
public class UserPool extends Pool implements Iterable<User>
33
{
32
public class UserPool extends Pool implements Iterable<User>{
34 33

  
35
	private static final String ELEMENT_NAME = "USER";
36
	private static final String INFO_METHOD  = "userpool.info";
37
		
38
	/**
39
	 * Creates a new user pool
40
	 * @param client XML-RPC Client.
41
	 */
42
	public UserPool(Client client)
34
    private static final String ELEMENT_NAME = "USER";
35
    private static final String INFO_METHOD  = "userpool.info";
36

  
37
    /**
38
     * Creates a new user pool
39
     * @param client XML-RPC Client.
40
     */
41
    public UserPool(Client client)
43 42
    {
44
		super(ELEMENT_NAME, client);
45
	}
43
        super(ELEMENT_NAME, client);
44
    }
46 45

  
47
	@Override
48
	public PoolElement factory(Node node)
46
    @Override
47
    public PoolElement factory(Node node)
49 48
    {
50
		return new User(node, client);
51
	}
49
        return new User(node, client);
50
    }
52 51

  
53
	/**
54
	 * Loads the xml representation of the user pool.
55
	 * 
56
	 * @see UserPool#info(Client)
57
	 */
58
	public OneResponse info()
52
    /**
53
     * Loads the xml representation of the user pool.
54
     */
55
    public OneResponse info()
59 56
    {
60
		OneResponse response = client.call(INFO_METHOD);
57
        OneResponse response = client.call(INFO_METHOD);
61 58

  
62 59
        super.processInfo(response);
63 60

  
64 61
        return response;
65
	}
62
    }
66 63

  
67
	public Iterator<User> iterator()
64
    public Iterator<User> iterator()
68 65
    {
69
		AbstractList<User> ab = new AbstractList<User>()
66
        AbstractList<User> ab = new AbstractList<User>()
70 67
        {
71
			public int size()
68
            public int size()
72 69
            {
73
				return getLength();
74
			}
70
                return getLength();
71
            }
75 72

  
76
			public User get(int index)
73
            public User get(int index)
77 74
            {
78
				return (User) item(index);
79
			}
80
		};
81
		
82
		return ab.iterator();
83
	}
75
                return (User) item(index);
76
            }
77
        };
78

  
79
        return ab.iterator();
80
    }
84 81
}
src/oca/java/src/org/opennebula/client/virtualMachine/VirtualMachine.java
1
/*******************************************************************************
2
 * Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org)
3
 * 
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 * 
8
 *   http://www.apache.org/licenses/LICENSE-2.0
9
 * 
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 ******************************************************************************/
16
package org.opennebula.client.virtualMachine;
17

  
18

  
19
import org.opennebula.client.Client;
20
import org.opennebula.client.OneResponse;
21
import org.opennebula.client.PoolElement;
22
import org.w3c.dom.Node;
23

  
24
/**
25
 * This class represents an OpenNebula VM.
26
 * It also offers static XML-RPC call wrappers.
27
 */
28
public class VirtualMachine extends PoolElement{
29

  
30
    private static final String METHOD_PREFIX = "vm.";
31
    private static final String ALLOCATE = METHOD_PREFIX + "allocate";
32
    private static final String INFO     = METHOD_PREFIX + "info";
33
    private static final String DEPLOY   = METHOD_PREFIX + "deploy";
34
    private static final String ACTION   = METHOD_PREFIX + "action";
35
    private static final String MIGRATE  = METHOD_PREFIX + "migrate";
36

  
37
    private static final String[] VM_STATES =
38
    {
39
        "INIT",
40
        "PENDING",
41
        "HOLD",
42
        "ACTIVE",
43
        "STOPPED",
44
        "SUSPENDED",
45
        "DONE",
46
        "FAILED" };
47

  
48
    private static final String[] SHORT_VM_STATES =
49
    {
50
        "init",
51
        "pend",
52
        "hold",
53
        "actv",
54
        "stop",
55
        "susp",
56
        "done",
57
        "fail" };
58

  
59
    private static final String[] LCM_STATE =
60
    {
61
        "LCM_INIT",
62
        "PROLOG",
63
        "BOOT",
64
        "RUNNING",
65
        "MIGRATE",
66
        "SAVE_STOP",
67
        "SAVE_SUSPEND",
68
        "SAVE_MIGRATE",
69
        "PROLOG_MIGRATE",
70
        "PROLOG_RESUME",
71
        "EPILOG_STOP",
72
        "EPILOG",
73
        "SHUTDOWN",
74
        "CANCEL",
75
        "FAILURE",
76
        "DELETE",
77
        "UNKNOWN" };
78

  
79
    private static final String[] SHORT_LCM_STATES =
80
    {
81
        null,
82
        "prol",
83
        "boot",
84
        "runn",
85
        "migr",
86
        "save",
87
        "save",
88
        "save",
89
        "migr",
90
        "prol",
91
        "epil",
92
        "epil",
93
        "shut",
94
        "shut",
95
        "fail",
96
        "dele",
97
        "unkn" };
98

  
99
    /**
100
     * Creates a new VM representation.
101
     * 
102
     * @param id The virtual machine Id (vid).
103
     * @param client XML-RPC Client.
104
     */
105
    public VirtualMachine(int id, Client client)
106
    {
107
        super(id, client);
108
    }
109

  
110
    /**
111
     * @see PoolElement
112
     */
113
    protected VirtualMachine(Node xmlElement, Client client)
114
    {
115
        super(xmlElement, client);
116
    }
117

  
118

  
119
    // =================================
120
    // Static XML-RPC methods
121
    // =================================
122

  
123
    /**
124
     * Allocates a new VM in OpenNebula.
125
     * 
126
     * @param client XML-RPC Client.
127
     * @param description A string containing the template of the vm. 
128
     * @return If successful the message contains the associated
129
     * id generated for this VM.
130
     */
131
    public static OneResponse allocate(Client client, String description)
132
    {
133
        return client.call(ALLOCATE, description);
134
    }
135
    
136
    /**
137
     * Retrieves the information of the given VM.
138
     * 
139
     * @param client XML-RPC Client.
140
     * @param id The virtual machine id (vid) of the target instance. 
141
     * @return If successful the message contains the string
142
     * with the information returned by OpenNebula.
143
     */
144
    public static OneResponse info(Client client, int id)
145
    {
146
        return client.call(INFO, id);
147
    }
148

  
149

  
150
    // =================================
151
    // Instanced object XML-RPC methods
152
    // =================================
153

  
154
    /**
155
     * Loads the xml representation of the virtual machine.
156
     * The info is also stored internally.
157
     * 
158
     * @see VirtualMachine#info(Client, int)
159
     */
160
    public OneResponse info()
161
    {
162
        OneResponse response = info(client, id);
163
        super.processInfo(response);
164
        return response;
165
    }
166

  
167
    /**
168
     * Initiates the instance of the VM on the target host.
169
     *   
170
     * @param hostId The host id (hid) of the target host where
171
     * the VM will be instantiated. 
172
     * @return If an error occurs the error message contains the reason.
173
     */
174
    public OneResponse deploy(int hostId)
175
    {
176
        return client.call(DEPLOY, id, hostId);
177
    }
178

  
179
    /**
180
     * Submits an action to be performed on the virtual machine.
181
     * <br/>
182
     * It is recommended to use the helper methods instead:
183
     * <ul>
184
     * <li>{@link VirtualMachine#shutdown()}</li>
185
     * <li>{@link VirtualMachine#cancel()}</li>
186
     * <li>{@link VirtualMachine#hold()}</li>
187
     * <li>{@link VirtualMachine#release()}</li>
188
     * <li>{@link VirtualMachine#stop()}</li>
189
     * <li>{@link VirtualMachine#suspend()}</li>
190
     * <li>{@link VirtualMachine#resume()}</li>
191
     * <li>{@link VirtualMachine#finalizeVM()}</li>
192
     * <li>{@link VirtualMachine#restart()}</li>
193
     * </ul>
194
     * 
195
     * @param action The action name to be performed, can be:<br/>
196
     * "shutdown", "hold", "release", "stop", "cancel", "suspend",
197
     * "resume", "restart", "finalize". 
198
     * @return If an error occurs the error message contains the reason.
199
     */
200
    protected OneResponse action(String action)
201
    {
202
        return client.call(ACTION, action, id);
203
    }
204

  
205
    /**
206
     * Migrates the virtual machine to the target host (hid).
207
     * 
208
     * @param hostId The target host id (hid) where we want to migrate
209
     * the vm.
210
     * @param live If true we are indicating that we want livemigration,
211
     * otherwise false. 
212
     * @return If an error occurs the error message contains the reason.
213
     */
214
    public OneResponse migrate(int hostId, boolean live)
215
    {
216
        return client.call(MIGRATE, id, hostId, live);
217
    }
218

  
219

  
220
    // =================================
221
    // Helpers
222
    // =================================
223

  
224
    /**
225
     * Shuts down the already deployed VM.
226
     * @return If an error occurs the error message contains the reason.
227
     */
228
    public OneResponse shutdown()
229
    {
230
        return action("shutdown");
231
    }
232

  
233
    /**
234
     * Cancels the running VM.
235
     * @return If an error occurs the error message contains the reason.
236
     */
237
    public OneResponse cancel()
238
    {
239
        return action("cancel");
240
    }
241

  
242
    /**
243
     * Sets the VM to hold state. The VM will not be scheduled until it is
244
     * released.
245
     * @return If an error occurs the error message contains the reason.
246
     */
247
    public OneResponse hold()
248
    {
249
        return action("hold");
250
    }
251

  
252
    /**
253
     * Releases a virtual machine from hold state.
254
     * @return If an error occurs the error message contains the reason.
255
     */
256
    public OneResponse release()
257
    {
258
        return action("release");
259
    }
260

  
261
    /**
262
     * Stops the virtual machine. The virtual machine state is transferred back
263
     * to OpenNebula for a possible reschedule.
264
     * @return If an error occurs the error message contains the reason.
265
     */
266
    public OneResponse stop()
267
    {
268
        return action("stop");
269
    }
270

  
271
    /**
272
     * Suspends the virtual machine. The virtual machine state is left in the
273
     * cluster node for resuming.
274
     * @return If an error occurs the error message contains the reason.
275
     */
276
    public OneResponse suspend()
277
    {
278
        return action("suspend");
279
    }
280

  
281
    /**
282
     * Resumes the execution of a saved VM.
283
     * @return If an error occurs the error message contains the reason.
284
     */
285
    public OneResponse resume()
286
    {
287
        return action("resume");
288
    }
289

  
290
    /**
291
     * Deletes the VM from the pool and database.
292
     * @return If an error occurs the error message contains the reason.
293
     */
294
    public OneResponse finalizeVM()
295
    {
296
        return action("finalize");
297
    }
298

  
299
    /**
300
     * Resubmits the virtual machine after failure.
301
     * @return If an error occurs the error message contains the reason.
302
     */
303
    public OneResponse restart()
304
    {
305
        return action("shutdown");
306
    }
307

  
308

  
309
    /**
310
     * Migrates the virtual machine to the target host (hid).
311
     * <br/>
312
     * It does the same as {@link VirtualMachine#migrate(int, boolean)}
313
     * with live set to false.
314
     * 
315
     * @param hostId The target host id (hid) where we want to migrate
316
     * the vm.
317
     * @return If an error occurs the error message contains the reason.
318
     */
319
    public OneResponse migrate(int hostId)
320
    {
321
        return migrate(hostId, false);
322
    }
323

  
324
    /**
325
     * Performs a live migration of the virtual machine to the
326
     * target host (hid).
327
     * <br/>
328
     * It does the same as {@link VirtualMachine#migrate(int, boolean)}
329
     * with live set to true.
330
     * 
331
     * @param hostId The target host id (hid) where we want to migrate
332
     * the vm.
333
     * @return If an error occurs the error message contains the reason.
334
     */
335
    public OneResponse liveMigrate(int hostId)
336
    {
337
        return migrate(hostId, true);
338
    }
339

  
340
    public int state()
341
    {
342
        return super.state();
343
    }
344

  
345
    /**
346
     * Returns the VM state of the VirtualMachine (string value).
347
     * @return The VM state of the VirtualMachine (string value).
348
     */
349
    public String stateStr()
350
    {
351
        int state = state();
352
        return state != -1 ? VM_STATES[state()] : null;
353
    }
354

  
355
    /**
356
     * Returns the LCM state of the VirtualMachine (numeric value).
357
     * @return The LCM state of the VirtualMachine (numeric value).
358
     */
359
    public int lcmState()
360
    {
361
        String state = xpath("LCM_STATE");
362
        return state != null ? Integer.parseInt(state) : -1;
363
    }
364

  
365
    /**
366
     * Returns the LCM state of the VirtualMachine (string value).
367
     * @return The LCM state of the VirtualMachine (string value).
368
     */
369
    public String lcmStateStr()
370
    {
371
        int state = lcmState();
372
        return state != -1 ? LCM_STATE[state] : null; 
373
    }
374

  
375
    /**
376
     * Returns the short status string for the VirtualMachine.
377
     * @return The short status string for the VirtualMachine.
378
     */
379
    public String status()
380
    {
381
        int state = state();
382
        String shortStateStr = null;
383
        if(state != -1)
384
        {
385
            shortStateStr = SHORT_VM_STATES[state];
386
            if(shortStateStr.equals("actv"))
387
            {
388
                int lcmState = lcmState();
389
                if(lcmState != -1)
390
                    shortStateStr = SHORT_LCM_STATES[lcmState];
391
            }
392
        }
393
        return shortStateStr;
394
    }
395
}
src/oca/java/src/org/opennebula/client/virtualMachine/VirtualMachinePool.java
1
/*******************************************************************************
2
 * Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org)
3
 * 
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 * 
8
 *   http://www.apache.org/licenses/LICENSE-2.0
9
 * 
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 ******************************************************************************/
16
package org.opennebula.client.virtualMachine;
17

  
18
import java.util.AbstractList;
19
import java.util.Iterator;
20

  
21

  
22
import org.opennebula.client.Client;
23
import org.opennebula.client.OneResponse;
24
import org.opennebula.client.Pool;
25
import org.opennebula.client.PoolElement;
26
import org.w3c.dom.Node;
27

  
28
/**
29
 * This class represents an OpenNebula VM pool.
30
 * It also offers static XML-RPC call wrappers.
31
 */
32
public class VirtualMachinePool extends Pool implements Iterable<VirtualMachine>{
33

  
34
    private static final String ELEMENT_NAME = "VM";
35
    private static final String INFO_METHOD  = "vmpool.info";
36

  
37
    private int filter;
38
    
39
    /**
40
     * Creates a new VM pool with the default filter flag value
41
     * set to 0 (VMs belonging to user with UID 0)
42
     * 
43
     * @param client XML-RPC Client.
44
     * 
45
     * @see VirtualMachinePool#VirtualMachinePool(Client, int)
46
     */
47
    public VirtualMachinePool(Client client)
48
    {
49
        super(ELEMENT_NAME, client);
50
        this.filter = 0;        
51
    }
52

  
53
    /**
54
     * Creates a new VM pool.
55
     * 
56
     * @param client XML-RPC Client.
57
     * @param filter Filter flag used by default in the method
58
     * {@link VirtualMachinePool#info()}. Possible values:
59
     * <ul>
60
     * <li><= -2: All VMs</li>
61
     * <li>-1: Connected user's VMs</li>
62
     * <li>>= 0: UID User's VMs</li>
63
     * </ul>
64
     */
65
    public VirtualMachinePool(Client client, int filter)
66
    {
67
        super(ELEMENT_NAME, client);
68
        this.filter = filter;
69
    }
70

  
71
    @Override
72
    public PoolElement factory(Node node)
73
    {
74
        return new VirtualMachine(node, client);
75
    }
76

  
77
    /**
78
     * Retrieves all or part of the VMs in the pool.
79
     *  
80
     * @param client XML-RPC Client.
81
     * @param filter Filter flag. Possible values:
82
     * <ul>
83
     * <li><= -2: All VMs</li>
84
     * <li>-1: Connected user's VMs</li>
85
     * <li>>= 0: UID User's VMs</li>
86
     * </ul>
87
     * @return If successful the message contains the string
88
     * with the information returned by OpenNebula.
89
     */
90
    public static OneResponse info(Client client, int filter)
91
    {
92
        return client.call(INFO_METHOD, filter);
93
    }
94

  
95
    /**
96
     * Loads the xml representation of all or part of the
97
     * VMs in the pool. The filter used is the one set in
98
     * the constructor.
99
     * 
100
     * @see VirtualMachinePool#info(Client, int)
101
     * 
102
     * @return If successful the message contains the string
103
     * with the information returned by OpenNebula.
104
     */
105
    public OneResponse info()
106
    {
107
        OneResponse response = info(client, filter);
108
        super.processInfo(response);
109
        return response;
110
    }
111

  
112
    public Iterator<VirtualMachine> iterator()
113
    {
114
        AbstractList<VirtualMachine> ab = new AbstractList<VirtualMachine>()
115
        {
116
            public int size()
117
            {
118
                return getLength();
119
            }
120

  
121
            public VirtualMachine get(int index)
122
            {
123
                return (VirtualMachine) item(index);
124
            }
125
        };
126

  
127
        return ab.iterator();
128
    }
129
}
src/oca/java/src/org/opennebula/client/virtualNetwork/VirtualNetwork.java
1
/*******************************************************************************
2
 * Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org)
3
 * 
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 * 
8
 *   http://www.apache.org/licenses/LICENSE-2.0
9
 * 
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 ******************************************************************************/
16
package org.opennebula.client.virtualNetwork;
17

  
18

  
19
import org.opennebula.client.Client;
20
import org.opennebula.client.OneResponse;
21
import org.opennebula.client.PoolElement;
22
import org.w3c.dom.Node;
23

  
24
/**
25
 * This class represents an OpenNebula virtual network.
26
 * It also offers static XML-RPC call wrappers.
27
 */
28
public class VirtualNetwork extends PoolElement{
29

  
30
    private static final String METHOD_PREFIX   = "vn.";
31
    private static final String ALLOCATE        = METHOD_PREFIX + "allocate";
32
    private static final String INFO            = METHOD_PREFIX + "info";
33
    private static final String DELETE          = METHOD_PREFIX + "delete";
34

  
35

  
36
    /**
37
     * Creates a new virtual network representation.
38
     * 
39
     * @param id The virtual network id (nid) .
40
     * @param client XML-RPC Client.
41
     */
42
    public VirtualNetwork(int id, Client client)
43
    {
44
        super(id, client);
45
    }
46

  
47
    /**
48
     * @see PoolElement
49
     */
50
    protected VirtualNetwork(Node xmlElement, Client client)
51
    {
52
        super(xmlElement, client);
53
    }
54

  
55
    // =================================
56
    // Static XML-RPC methods
57
    // =================================
58

  
59
    /**
60
     * Allocates a new virtual network in OpenNebula.
61
     * 
62
     * @param client XML-RPC Client.
63
     * @param description A string containing the template
64
     * of the virtual network. 
65
     * @return If successful the message contains the associated
66
     * id generated for this virtual network.
67
     */
68
    public static OneResponse allocate(Client client, String description)
69
    {
70
        return client.call(ALLOCATE, description);
71
    }
72

  
73
    /**
74
     * Retrieves the information of the given virtual network
75
     * 
76
     * @param client XML-RPC Client.
77
     * @param id the virtual network id (nid) for the network to
78
     * retrieve the information from. 
79
     * @return If successful the message contains the string
80
     * with the information returned by OpenNebula.
81
     */
82
    public static OneResponse info(Client client, int id)
83
    {
84
        return client.call(INFO, id);
85
    }
86

  
87
    /**
88
     * Deletes a network from OpenNebula.
89
     * 
90
     * @param client XML-RPC Client.
91
     * @param id The virtual network id (nid) of the target network.
92
     * @return A encapsulated response.
93
     */
94
    public static OneResponse delete(Client client, int id)
95
    {
96
        return client.call(DELETE, id);
97
    }
98

  
99

  
100
    // =================================
101
    // Instanced object XML-RPC methods
102
    // =================================
103

  
104
    /**
105
     * Loads the xml representation of the virtual network.
106
     * The info is also stored internally.
107
     * 
108
     * @see VirtualNetwork#info(Client, int)
109
     */
110
    public OneResponse info()
111
    {
112
        OneResponse response = info(client, id);
113
        super.processInfo(response);
114
        return response;
115
    }
116

  
117
    /**
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff