Monday, June 1, 2009

Use definitions for Reuse [WLST scripting Best Practices (Part-4)]

This post is a continuation of my previous post - in a series of posts about WLST scripting best practices. When you are authoring WLST scripts for automating WebLogic administration tasks, you can reuse or extend an existing logic written in WLST or Jython scripts. You can also leverage or extend logic written in Java which I will discuss later in a different post. Definition are reusable code blocks in Jython. Think of definitions as methods or functions. You can pass parameters into definitions. You can reuse definitions from the same script or from a different script. A script that contains definitions for other scripts to use is usually called as a 'Module'. If you are using a definition from a module then you should import it in your script. The definition should be defined before they get called in the script.

Let us see an example of a using definition in the same script.

#Definition for connecting to a server
def connectToServer():
username = 'weblogic'
password = 'weblogic'
url = 't3://egAdm:7001'
connect(username, password, url)

#Definition to print a running servers heap details
def printHeapDetails(server_name):
hf = float(get('HeapFreeCurrent'))/1024
hs = float(get('HeapSizeCurrent'))/1024
hf = hf/1024
hs = hs/1024
print 'HeapFreeCurrent - ' + `hf` + 'MB'
print 'HeapSizeCurrent - ' + `hs` + 'MB'

#Definition to disconnect from a server
def disconnectFromServer():

#Calling connectToServer definition with no arguments

#Calling printHeapDetails with arguments

#Calling disconnectFromServer definition with no arguments

In the above script we are connecting to the administration server of a domain and then printing the heap details for the admin server and 2 other managed servers. The logic to navigate to the respective runtime mbean and printing the heap related attributes is being defined as reusable definition and called multiple times.

WLST-BP-4 Use definitions for Reuse