Jython
and WSADMIN scripting
Considering the scarcity of the source for Jython and WSADMIN guides available over the internet, I am initiating a new series of topics through which we will learn Jython and WSADMIN scripting. WSADMIN is a scripting tool supported by IBM WebSphere Application Server. Looking at the current requirements of any production environments, it is always preferred to have complex tasks in scripted format to avoid the delay as well as operational mistakes.
IBM websphere supports two types of language for
scripting. One is jython and second being jacl. JACL has been deprecated from
WAS version 7. Jython means python for java platform. Thus the programmers
having a little bit of knowledge of java or python will be comfortable with the
scripting. Currently there is a very little source of information available in
the market that can help us to do scripting part. Therefore we are going
through a kind of small online crash course to understand wsadmin scripting.
But let me warn you, only completing this course is not going to make you do
scripting from the first day. This will help you to take initiative for
learning wsadmin scripting.
We are going to divide the entire course in two sections.
One will take a look on jython language basics and second part will be designed
as per wsadmin and its objects’ perspective.
I assume that we all have basic knowledge of any
programming language. When I say basic, I mean knowledge of keywords, control
structures, variable handling and exceptions.
Section
1 : Jython Language Basics
Understanding
Jython and its structure
As
I mentioned earlier, Jython means python for java implementation. Saying this, Jython
makes for a best of both worlds bridge between Python world and the Java world.
Developers who work in organizations where Java is already in use can now take
advantage of the expressiveness and conciseness of Python by running their
Python programs on Jython. Jython provides easy integration and
interoperability between Python code and existing Java code. Jython also has
something to offer existing Python programmers, namely access to the very rich
ecosystem of the Java Virtual Machine.
We
will take a look at structure of the jython language.
Unlike
other programming languages, Jython does not use curly braces to define the
block of code. For example, a function in C can be defined as below :
Void
function1()
{
//Your
code here
//code
block
}
//Function ends here
Whereas
the function in jython will be defined as below:
def
function1():
function_code1
function_code2
Jython uses indention to define function block or
any code block. This means, if, for, while or similar code structures will use
indentions. Remember to use colon(:) to start the sub-block of code. Moreover,
you do not need semicolon to be used to indicate the end of statement.
Before I go deeper with jthon details, we will
first take a look at starting jython programming environment. If you do not
have the jython installed, you can use wsadmin.sh i.e. websphere application
server scripting utility. I would recommend to use wsadmin since we would be
running most of the programs under wsadmin and thus it would be necessary that
our programs abide the environment and rules of websphere.
You can start wsadmin as given below :
/opt/IBM/WebSphere/AppServer/profiles/Dmgr01/bin/wsadmin.sh –user
<user_name> -password <password> -lang jython
You need to provide the credentials that you use
to login to the admin console. Also we are using jython as a language since
wsadmin uses JACL as default language.
Chapter
1 Jython Programming Essentials
In
this section, we will go through jython expressions and operations and its
basic structions.
Keywords:
As
you all must be aware, keywords is the list of specific words that you cannot
use as variables or the identifiers. They have their own inbuilt purpose and functions.
Below is the list of keywords.
and
|
assert
|
break
|
class
|
continue
|
def
|
del
|
elif
|
else
|
except
|
exec
|
finally
|
for
|
from
|
global
|
or
|
pass
|
print
|
raise
|
return
|
try
|
while
|
with
|
yield
|
Variable
Declaraction:
In
Jython, we do not need to define data types of the variable as opposed in other
programming languages. You simply give the variable name and assign the value
and Jython will take care of the rest. (yes, there are the data types defined
implicitely. They can be categorized as string, integer and float. You do not
need to specify the data type. Just assign the value and jython will manage
data types)
For
eg.
Str=”Vishal”
Count=0
Expressions:
Expressions
are same as we had in all languages.
For
eg.
x=10
y=2
z=x/4
print z
Functions:
Function
is a piece of code that you want to reuse again and again and to save the time
as well as space. Functions are named portions of code that perform that
usually perform one or more tasks and return a value. In order to define a
function we use the def statement. Also to indicate that the
function block is started, we use colon(:)
The
common syntax goes as follows.
def function_name(parameter_list) :
implementation
code
Lets
see the actual implementation scenario for function.
def welcomeUser(user_name) :
print “Welcome
“+user_name
print “Welcome to programming world of Java”
user=”Vishal”
welcomeUser(user)
The
flow of the program is;-
1.
print “Welcome to programming world of
Java”
2.
user=”Vishal”
3.
welcomeUser(user). This line calls the
function defined earlier and copies value of variable user to user_name.
4.
print
“Welcome ”+user_name
Statements:
The
program is made up of expressions and statements. A statement is the line of
code which instructs the compiler to do some task.
Below
are statement keywords used for programming.
if-elif-else
|
for
|
while
|
continue
|
break
|
try-except-finally
|
assert
|
def
|
print
|
del
|
raise
|
import
|
Lets
take a look at each statement keyword.
1.
if-elif-else :
The if statement is used to
perform certain task depending on your requirements or conditions. The if
statement simply performs an evaluation on an expression and does different
things depending on whether it is True or False.
If the expression evaluates to True then one set of statements
will be executed, and if it evaluates to False a different set
of statements will be executed. If statements are quite often used for
branching code into one direction or another based upon certain values which
have been calculated or provided in the code.
I would like to remind again
that, in jython the code block is denoted by indention. Below few examples will
help to understand the same.
The common syntax for if loop is
as follows.
if <conditional_expression> :
Perform
an task
else :
perform another task
If loop:
The simple if loop will be used
to evaluate the condition and execute the piece of code.
x=2
y=2
if x == y :
print “x
equals to y”
The way, conditional part is
written you must have noticed the difference that there no parenthesis used to
mention the condition. You don’t need to worry, you can specify the same here
too.
if (x == y):
perform
action
if else loop :
if else loop is used when you
have two sets of actions to be performed. If condition is satisfied then
perform one action and if the condition is not satisfied then perform second action,
x=2
y=3
if x == y :
print “x
equals y.”
else :
print “x
and y are different”
if-elif-else loop:
When you have multiple
possibilities to be verified and take multiple actions, use if-elif-else loop.
For eg.
x=2
y=3
if x == y :
print “x
equals y.”
elif x < y :
print “x
is lesser than y”
else :
print “x
is greater than y”
Nested if-else:
You can use if-else loop inside
an if-else loop if you need to verify multiple conditions.
x=2
y=3
if x == y :
if x >
0 :
print
“x is a positive number and x equals y.”
else :
print “x
and y are different”
Note : Take a look at the way the
indention is maintained.
2.
For loop
This will be the statement you
will be using majorly while designing your program. Since in websphere
environment, you need to deal with lists mostly, for loop comes very handy. Jython
supports the for loop in slightly different format. It resembles to foreach
loop used in our conventional languages.
The syntax for for loop is –
for each_value in list_range :
perform
actions
The above pseudo code can be
slight confusing, below is the sample code.
arr=[1,2,3,4,5,6]
for i in arr :
print i
3.
While
While loop behaves like
conventional while loop. It checks for condition at the beginning and continues
to perform iterations until the condition is true. Below is the syntax.
while <condition> :
perform
action
The sample code is as follow :
x=5
y=2
while y<x :
print “X : %d , Y: %d” %(x,y)
y=y+1
4.
Continue and break
Continue and break statements can
be used with the same syntax and have the same usage as our other programming
languages.
5.
Try – except –
finally :
try-except-finally resembles
try-catch-finally block of other programming languages like java. Sometimes it
is likely that the program may encounter some serious error and thus can exit
abruptly. It might throw some weird exception and break your execution flow
also. Thus we need to make sure that we embed such suspicious statements in try
and then perform our tasks.
Below is the sample code :
x=7
y=0
try :
print “Divide x/y = %d” %(x/y)
except :
print
“There is an exception while performing an action.”
6.
def
def defines the function
definition. Whenever you need to define a function, you need to specify def at
the beginning of the function definition and then proceed with further details.
def <function_name> :
perform
task
Sample code :
def function1(name) :
print
“Hello “+name
7.
print
If you have observed previous
sample codes, we have been using print statement in multiple formats. Jython
supports the print command in robust format where either you can specify the
identifier place holder and then later specify the identifiers to be printed.
In the other option, you can append the variable to the string.
Sample Code :
x=1
y=2
print “X= %d” %(x)
print “X= %d, Y= %d” %(x,y)
#The same output can be obtained by below lines.
However I would always
#recommend to use the former one -
print “X= ”+x
print “X= ”+x+”, Y=”+y
#If you need to write a long sentence on a same
line, you can use comma
#operator after print. Below is the example.
print "This is going to be very long sentence.
This is going to be very long sentence.",
print "This is going to be very long sentence.
This is going to be very long sentence."
Below are formatters used to
print formatted string.
•
%s – String
•
%d – Decimal
•
%f – Float
Keyboard
Input
The Jython language has a couple
of built-in functions to take input from the keyboard as to facilitate the
process of writing applications that allow user input. Namely, raw_input(),
and input() can be used to prompt and accept user input from the
command-line. Not only is this useful for creating command-line applications
and scripts, but it also comes in handy for writing small tests into your
applications.
The raw_input() function
accepts keyboard entry and converts it to a string, stripping the trailing
newline character. Similarly, the input() *function accepts keyboard entry
as *raw_input(), but it then evaluates it as an expression. The input()
function should be used with caution as it expects a valid Python expression to
be entered. It will raise a SyntaxError if this is not the case. It is
best to steer clear of using input() in most cases and just stick to
using raw_input. Let’s take a look at using each of these functions in some
basic examples.
Sample code :
name = raw_input("Enter Your Name:")
Enter Your Name:Vish
print name
Vish
# Use the input function to evaluate an expression
entered in by the user
val = input ('Please provide an expression: ')
Please provide an expression: 9 * 3
val
27
# The input function raises an error if an
expression is not provided
val = input ('Please provide an expression: ')
Please provide an expression: My Name is Vish
Traceback (most recent call last):
File
"<stdin>", line 1, in <module>
File
"<string>", line 1
My Name is Vish
^
SyntaxError: invalid syntax
In next chapter we will see Data types and multiple type of objects supported by Jython.