Spherus.biz Home          

Scripting Basics

This is an introduction to wsadmin and the Jython scripting language. This section will give you an overview of the coding structure and some basic guidelines to follow when writing Jython scripts. We will cover code layout, function definitions, if statements, for loops, and error handling. We will also look at a few basic wsadmin commands.

The layout of a Jython script is very important. There are no opening or closing braces to denote a block of code. Because of this, we need to ensure our code is correctly structured by using tabs and spaces. In the following example, every line will be executed as they are all defined at the same indent level.

 
serverName = "MyFirstServer
nodeName = "MyFirstNode"
configPath = "/Node:%s/Server:%s/" % (nodeName, serverName)
print "Config Path: %s" % (configPath)
 

In the following code layout, the code under the if statement will only be executed if the statement is true. If the statement is false, the indented code is skipped.

 
serverName = "server1
nodeName = "node1"
if isEmpty(serverName):
configPath = "/Node:%s/" % (nodeName)
else :
configPath = "/Node:%s/Server:%s/" % (nodeName, serverName)
 
print "Config Path: %s" % (configPath)
 

In this way we define our coding blocks.

2. Variables

The Jython implementation of wsadmin makes use of two variable types, numbers and strings. This greatly simplifies the allocation of variables as we don't have to concentrate on the type of variable being used. The only extended variable supported is the array. Arrays can be one of the two simple data types.

The coding examples in the above section outline some of the uses of variables. Firstly we need to be able to allocate a value to a variable. This is done by using a simple assignment operator.

 
serverName = "server1"
 

We can also allocate numbers in a similar fashion.

 
count = 0
 

Various operations can then be performed on our new variables. Manipulation of strings follows a similar format to that of C++. The following example demonstrates how to combine variables in to a string.

 
serverName = "server1
nodeName = "node1"
configPath = "/Node:%s/Server:%s/" % (nodeName, serverName)
 

Notice the %s within the quotes of the string, followed by the % (variableName). We are able to combine numbers and strings in a similar way.

 
serverNumber = 1
serverName = "server"
completeName = "%s%d" % (serverName, serverNumber)
 

In the above example we have used both a %s and a %d to combine the two variables into our string. As we make more use of this we will discover more options available to use when formatting strings.

The last important variable that we will need to use is the Array. An array is a list of simple data types. As Jython only supports two data types, we can only have two types of Arrays. Arrays offer us a number of added functions that we can use.

An array is denoted by square brackets [ ] . Normally an array is indexed using a numeric value. Within Jython arrays can be indexed using strings. This makes the use of arrays in our scripts very useful and powerful. The following example shows how we cna define and populate an array.

 
attributes = []
attributes.append(["name", name])
attributes.append(["jndiName", "jdbc/%s" % (name)])
attributes.append(["datasourceHelperClassname", helperClass])
attributes.append(["description", description])
 

As you can see, the above code has created an array of attributes. As you can see, the indexes of the array are actually string literals.

As we have seen we can create empty arrays and populate them by using the append command. Another way to create an array is to use the split command of a string literal. If we have a list of items returned as a single string, we can convert that into an array list using the split command.

 
animalString = "Dog Cat Horse"
animalList = animalString.split(" ")
 

In the above example, we have a list of animals defined as a string literal. We have then used the split command together with a space character to create the array animalList. The split command accepts a separator character to determine where to split the string literal. As we make more use of lists and arrays we will see how useful this functionality will become.

As we develop the scripts, you will continue to learn more about how to make better use of arrays.

3. Function Definition

To make our Jython scripts more useful we need to define functions. These can then be called by our script or other scripts. It also helps us with repeatable tasks so we don't have to re-write the same code multiple times.

The simplest for of function is one with no arguments. This is defined as follows. We need to remember our code layout when we define functions.

 
def myFunction():
print "This is my Function"
 

As you can see from the code example above, we define a function by using the def keyword. A pair of empty parentheses are used to denote a function that does not have any arguments. We do not need to define a return type for our function as wsadmin only supports Strings or numbers as simple data types. The last important component of the function definition is the colon at the end of the line.

def myFunction() :

We can also see the body of the function has been indented. As we do not have a brace to denote the end of the function, it is assumed that the function has ended if the next line of text is at a lower indent level.

To make our functions more useful we may want to pass a number of parameters, as in the following example:

 
def myFunction(name):
print "Your name is %s" % (name)
 

In this example we have passed in the variable name and used that in our print function.

We may wish to specify more than one parameter to our function. In this case we use a comma to separate our parameters. We can also supply a default value for the paramenter. If the function is called by supplying less parameters than the defined by the function, those parameters will be given the default value. Default values have to be supplied to all parameters to the right of the initial parameter supplied with a default value.

 
def myFunction(name, age = 0):
print "Your name is %s and your supplied age is %d" % (name, age)
 

In this example we have set the default value of the age parameter to 0. This will be assigned if the argument has not been set to the function.

The last requirement of our function is the ability to return a value to the calling code. We do this by using the return keyword at the end of our function or at a logical section in our function.

 
def add(num1, num2):
result = num1 + num2
return result
 

Now that we can define functions, we need to look at ways to control the flow of code. The next sections discuss if statements and for loops.

4. If statements

In order to make our scripts more functional, we need to b able to control the flow of the script. We can use if statements to achieve this goal.

The following example is the simplest form of the if statement:

 
if serverName == "":
print "No server Name has been given"
 

We can then extend this statement to include some further control by using an else statement. Also notice the indentation used to denote the body of the if statement. There is also a trailing colon at the end of the statement.

 
if serverName == "":
print "No server Name has been given"
else:
print "Server Name given: %s" % (serverName)
 

We can further enhance our control by adding in more options by using an elif statement. This follows the same structure of the if statement, but must follow an initial if statement. The following example demonstrates the use of the elif statement.

 
if serverName == "":
print "No server Name has been given"
elif serverName == "server1":
print "We cannot use server1 in this example"
else:
print "Server Name given: %s" % (serverName)
 

As you can see, this makes for very easy and powerful flow control where multiple options are involved. As we develop our scripts throughout these tutorials, using the above code will become second nature.

5. For Loops

The for loop used in Jython scripts does not resemble a for loop in either Java or C++. The for loop in Jython makes use of a range. This ensures greater flexibility in the use of the for loop. The following code example shows how to use a simple loop to run the same bit of code multiple times.

 
for i in range (5):
print "Loop number: %d" % (i)
 

The above code will loop from zero to the number specified less 1. We can also set the starting point for our loop. This will then loop from our start number to our end number less 1.

 
for i in range (1, 5):
print "Loop number: %d" % (i)
 

The above example will print the number 1 through 4, whereas the previous example will print the numbers 0 through 4. The main difference is our starting point. The ending point is the same for both loops.

We can also use a for loop to loop through a list of items stored in an array. When we want to use this method of looping, we do not need to use the range keyword.

 
animalString = "Dog Cat Horse"
animalList = animalString.split(" ")
for animal in animalList:
print "Loop number: %s" % (animal)
 

This demonstrates how versatile the for loop can been. This functionality will be come very clear when we start looking at more WebSphere Application Server specific functions. A number of configuration objects are returned as either lists or string literals that can be converted into lists. We need this functionality in order to develop useful Jython scripts that we can use to configure our Websphere Application Server environments.

6. Error Handling

wsadmin Has be written in java and as such makes use of a similar error handling mechanism by way of Exceptions. In order to make use of this facility, you need to surround your code with a try - except block. You can then use the raise command to force the exception. Here is an example of using an exception:

try:
if isEmpty(serverName):
raise StandardError("serverName has not been specified")
 
serverID = getContainmentPath("none", nodeName, serverName)
..
..
..
except:
_trace("An Error occurred during this function")
 
    

The next tutorial will cover the basic utility functions we will use throughout the course. You can download the complete utilities.py if you wish to skip ahead to the Application Server Tutorial.