Thursday, September 4, 2014

Creating cluster using Jython wsadmin

Pre requisites 
As per todays experiment what I understood is we need the following are the pre-requisites for the Cluster configuration in WebSphere Environment:
1) Cell created with a DMGR Profile
2) Nodeagents created and added to the cell.
3) Dmgr, Nodeagent must be running.

Jython Script for Cluster

 
import sys
import os
import socket

#Get the operating system line separator from the linesep method of the os object
nl = os.linesep

# Store the Cell identifier for the specified Cell
cellID = AdminConfig.list('Cell')
cellName = AdminConfig.showAttribute(cellID, 'name')

#derives the environment type from the cellName
sName = cellName.replace("Cell","")
sName = sName.replace("Demo","")

# Store the Node identifier for the specified Node
nodeIDs = AdminConfig.list('Node').split(nl)
nodeNames = AdminTask.listNodes().split(nl)
nodeNames.sort()

# Identify each node and it's purpose so we can start creating servers and clusters on the
# appropriate nodes
for nid in nodeIDs:
 nname=AdminConfig.showAttribute(nid, 'name')
 nname=nname.replace(sName, "")
 if nname == "AppSrvNode":
  NID01=nid
 elif nname == "AppSrvNode02":
  NID02=nid
 continue
# Store the node names
Node1Name = AdminConfig.showAttribute(NID01, 'name')
Node2Name = AdminConfig.showAttribute(NID02, 'name') 
 
print Node1Name,Node2Name

# Create the cluster and store the cluster name
print "\nCreating the Demo cluster"
clusterID = AdminTask.createCluster('[-clusterConfig [-clusterName Demo' + sName + 'Cluster -preferLocal true]]')
clusterName = AdminConfig.showAttribute(clusterID, 'name')


# Creates all of the cluster members on the specified nodes
print "\nCreating the cluster members for the Demo cluster"
def createClusterMembers(nn01, nn02, clustName):
 i = 1
 while i <= 2:
  if i == 1:
   AdminTask.createClusterMember('[-clusterName ' + clustName + ' -memberConfig [-memberNode ' + nn01 + ' -memberName Demo' + sName + 'CM' + str(i) + ' -memberWeight 2 -genUniquePorts true -replicatorEntry false] -firstMember [-templateName default -nodeGroup DefaultNodeGroup -coreGroup DefaultCoreGroup]]')
  elif i > 1:
   AdminTask.createClusterMember('[-clusterName ' + clustName + ' -memberConfig [-memberNode ' + nn01 + ' -memberName Demo' + sName + 'CM' + str(i) + ' -memberWeight 2 -genUniquePorts true -replicatorEntry false]]')
  i+=1
  continue
 
 while i <=4:
  AdminTask.createClusterMember('[-clusterName ' + clustName + ' -memberConfig [-memberNode ' + nn02 + ' -memberName Demo' + sName + 'CM' + str(i) + ' -memberWeight 2 -genUniquePorts true -replicatorEntry false]]')
  i+=1
  continue

createClusterMembers(Node1Name, Node2Name, clusterName)
# Gets a list of all the newly created cluster members
cmIDs = AdminConfig.list('ClusterMember', clusterID).split(nl)

#Lists all of the application servers
serverName = []
serverID = AdminTask.listServers('-serverType APPLICATION_SERVER').split(nl)
for sid in serverID:
 serverName.append(AdminConfig.showAttribute(sid, 'name'))

serverName.sort()


# This function saves any configuration changes to the master respository
def saveConfig():
 print ""
 print "Saving changes to the master repository"
 AdminConfig.save()
 print ""
 print "DONE!"

# The following function Syncs all of the nodes with an active/started nodeagent task
def syncNodes():
 nodelist = AdminConfig.list('Node').split(nl)
 print "\n\n########################################"
 print "### Synchronizing the Nodes"
 print "########################################\n"
 for n in nodelist:
  nodename = AdminConfig.showAttribute(n, 'name')
  objname = "type=NodeSync,node=" + nodename + ",*"
  Syncl = AdminControl.completeObjectName(objname)
  if Syncl != "":
   if AdminControl.invoke(Syncl, 'isNodeSynchronized') == "true":
    print "\n!! " + nodename + " is already synchronized"
   else:
    AdminControl.invoke(Syncl, 'sync')
    print "\n)) " + nodename + " synchronized"
  continue
  
print "Save the configuration changes?\n\n"

saveConfig()

syncNodes()
This was given me great learning oppurtunity the output makes me THRILLED!! O/P
 

wsadmin>execfile('/home/krish/jython/cluster.py')
AppSrvNode AppSrvNode02

Creating the Demo cluster
Creating the cluster members for the Demo cluster
Save the configuration changes?

Saving changes to the master repository

DONE!

########################################
### Synchronizing the nodes
########################################

)) AppSrvNode synchronized

)) AppSrvNode02 synchronized

Saturday, August 30, 2014

Creating New Server using Jython

In this learning and sharing today created a server using Jython script.
The basic needs to create a App Server in WebSphere environemnt is to have Node and it should be added to the Cell.

The script would perormed with the help of the NodeID to create the server. create is the simple command method on the AdminConfig object.

CreateServer.py

import sys  # import system libraries

#interactive method, type server & node name

servername=raw_input("Enter server name:")
nodename=raw_input("Enter Node name:")
# get the config id of the node
print "getting config id of node .."
nodeid=AdminConfig.getid('/Node:'+nodename+'/')

# verify whether the entered node exist or not
try :
 if nodeid=='':
  print "entered correct node", nodename
except:
 print " the node does not exist, please enter a valid node"

# get the config id of the node
#print "getting config id of node .."
#nodeid=AdminConfig.getid('/Node:'+nodename+'/')

#define attributes like servername & etc
print "defining attributes .."
att=[['name' , servername]]
print "creating servers .."
print AdminConfig.create('Server' , nodeid , att )
print "saving config .."
AdminConfig.save()


This above script has print statement that actually calling AdminConfig.create() method. As we have discussed in the previous post that a Jython function/method that has return statement that can be called in assignment, expression, or in a output statement liek print. In this case last option selected. Ofcourse this print is optional. now lets evaluate our script by executing as follows:

wsadmin>execfile('/home/krish/jython/createServer.py')
Enter server name:server2
Enter Node name:AppSrvNode
getting config id of node ..
defining attributes ..
creating servers ..
server2(cells/DmgrCell05/nodes/AppSrvNode/servers/server2|server.xml#Server_1409381645239)
saving config ..

Validation of Script


Validating the script configuration on the Admin console given me as follows:







Friday, August 29, 2014

Getting Node id, Cell ID, Server ID of Mbean in wsadmin

Basic understanding of wsadmin objects
  • Node – an individual system, either physical or virtual
  • Node Manager – the process controlling the individual node and all servers in all cells, it executes the commands of the Deployment Manager
  • Profile – a WebSphere entity similar to a node concept wise
  • Application Server – a Java Virtual Machine (JVM) process
  • Application – a Java enterprise application it could be .ear file with some modules
  • Cluster – a group of Servers, all running the same applications
  • Cell – an administrative domain of one or more servers
  • Deployment Manager (DM) – the administration application for a cell
How do all these pieces work together? 
 “Multiple Nodes in a Cell run Servers that contain Applications. All pieces are controlled via the Deployment Manager”
 

How to retrieving  Node ID in wsadmin?

This task is very much required for most of the create method executions. When you create servers, when you construct Cluster Member servers your script need Node id. Ofcourse if you wish to Sync the differe!!nt members of a node also requird the Node id.

wsadmin>AdminConfig.getid('/Node:DmgrNode05')
'DmgrNode05(cells/DmgrCell05/nodes/DmgrNode05|node.xml#Node_1)'

How to retrieving Cell Name in wsadmin?

wsadmin>CellName=AdminControl.getCell()

What is the command to Retrieving Cell ID in wsadmin?

wsadmin>AdminConfig.getid('/Cell:'+CellName)
'DmgrCell05(cells/DmgrCell05|cell.xml#Cell_1)'

How can I retrieving the Servers list in wsadmin?

wsadmin>AdminTask.listServers('[-serverType APPLICATION_SERVER]')
'server1(cells/DmgrCell05/nodes/AppSrvNode/servers/server1|server.xml)'

How to fetch the Server ID on wsadmin?

wsadmin>AdminConfig.getid('/Server:server1')
'server1(cells/DmgrCell05/nodes/AppSrvNode/servers/server1|server.xml#Server_1407376951191)'
wsadmin>

Different automation scripts requires the wsadmin provided MBean values. so that we can store in the Jython variables like list and use them.

Hoping this post helped you in doing simple command exections on your wsadmin prompt. Keep writing your comments and thoughts on this blog 

Administration objects and their help in wsadmin

Welcome to Jython exclusive blog developed for the WebSphere Admins only. Here in this post we can explore more about the real-time wsadmin Objects. Which are most critical to develop the automate WebSphere server side. 

wsadmin management objects


wsadmin>print AdminConfig.help()

WASX7053I: The AdminConfig object communicates with the Config Service in a
        WebSphere server to manipulate configuration data for a WebSphere
        installation.  AdminConfig has commands to list, create, remove,
        display, and modify configuration data, as well as commands to display
        information about configuration data types.

        Most of the commands supported by AdminConfig operate in two modes:
        the default mode is one in which AdminConfig communicates with the
        WebSphere server to accomplish its tasks.  A local mode is also
        possible, in which no server communication takes place.  The local
        mode of operation is invoked by bringing up the scripting client with
        no server connected using the command line "-conntype NONE" option
        or setting the "com.ibm.ws.scripting.connectionType=NONE" property in
        the wsadmin.properties.

        The following commands are supported by AdminConfig; more detailed
        information about each of these commands is available by using the
        "help" command of AdminConfig and supplying the name of the command
        as an argument.

attributes      Shows the attributes for a given type
checkin         Checks a file into the the configuration repository
convertToCluster
                Converts a server to be the first member of a new ServerCluster
create          Creates a configuration object, given a type, a parent, and
                a list of attributes, and optionally an attribute name for the
                new object
createClusterMember
                Creates a new server that is a member of an existing cluster
createDocument  Creates a new document in the configuration repository
createUsingTemplate
                Creates an object using a particular template type
defaults        Displays the default values for attributes of a given type
deleteDocument  Deletes a document from the configuration repository
existsDocument  Tests for the existence of a document in the configuration
                repository
extract         Extracts a file from the configuration repository
getCrossDocumentValidationEnabled
                Returns true if cross-document validation is enabled
getid           Shows the configuration ID of an object, given a string version
                of its containment
getObjectName   Given a configuration ID, returns a string version of the
                ObjectName for the corresponding running MBean, if any
getObjectType   Given a configuration ID, returns a string version of the
                object type
getSaveMode     Returns the mode used when "save" is invoked
getValidationLevel
                Returns the validation used when files are extracted from the
                repository.
getValidationSeverityResult
                Returns the number of messages of a given severity from the
                most recent validation
hasChanges      Returns true if unsaved configuration changes exist
help            Shows help information
installResourceAdapter
                Installs a J2C resource adapter with the given rar file name
                and an option string in the node
list            Lists all configuration objects of a given type
listTemplates   Lists all available configuration templates of a given type
modify          Changes specified attributes of a given configuration object
parents         Shows the objects which contain a given type
queryChanges    Returns a list of unsaved files
remove          Removes the specified configuration object
required        Displays the required attributes of a given type.
reset           Discards unsaved configuration changes
resetAttributes Resets value of the specified attributes.
save            Commits unsaved changes to the configuration repository
setCrossDocumentValidationEnabled
                Sets the cross-document validation enabled mode.
setSaveMode     Changes the mode used when "save" is invoked
setValidationLevel
                Sets the validation used when files are extracted from the
                repository.
show            Shows the attributes of a given configuration object
showall         Recursively shows the attributes of a given configuration
                object, and all the objects contained within each attribute.
showAttribute   Displays only the value for the single attribute specified.
types           Shows the possible types for configuration
uninstallResourceAdapter
                Uninstalls a J2C resource adapter with the given resource
                adapter configuration ID.
unsetAttributes Unsets value of the specified attributes.
validate        Invokes validation

wsadmin>print AdminConfig.getid


wsadmin>print AdminConfig.getid()
WASX7015E: Exception running command: "AdminConfig.getid()"; exception information:
com.ibm.ws.scripting.ScriptingException: WASX7352E: Wrong number of arguments for "getid" command.  Help information follows:
 WASX7085I: Method: getid

        Arguments: containment path

        Description: Returns the configuration ID for an object described by the
        given containment path -- for example, /Node:myNode/Server:s1/JDBCProvider:jdbc1/

wsadmin>print AdminConfig.getid('/Node:Dmgr05')

wsadmin>print AdminConfig.getid('/Node:DmgrNode05'
Traceback (innermost last):
  (no code object) at line 0
  File "", line 1
SyntaxError: invalid syntax

wsadmin>print AdminConfig.getid('/Node:DmgrNode05')

DmgrNode05(cells/DmgrCell05/nodes/DmgrNode05|node.xml#Node_1)
wsadmin>print AdminControl.help()
WASX7027I: The AdminControl object enables the manipulation of MBeans running
        in a WebSphere server process.  The number and type of MBeans available
        to the scripting client depends on the server to which the client is
        connected.  If the client is connected to a Deployment Manager, then
        all the MBeans running in the Deployment Manager are visible as are all
        the MBeans running in the Node Agents connected to this Deployment
        Manager, and all the MBeans running in the application servers on those
        nodes.

        The following commands are supported by AdminControl; more detailed
        information about each of these commands is available by using the
        "help" command of AdminControl and supplying the name of the command
        as an argument.

        Note that many of these commands support two different sets of
        signatures: one that accepts and returns strings, and one low-level
        set that works with JMX objects like ObjectName and AttributeList.
        In most situations, the string signatures are likely to be more useful,
        but JMX-object signature versions are supplied as well.  Each of these
        JMX-object signature commands has "_jmx" appended to the command name.
        Hence there is an "invoke" command, as well as a "invoke_jmx" command.

completeObjectName
                Returns a String version of an object name given a template
                name
getAttribute_jmx
                Given ObjectName and name of attribute, returns value of
                attribute
getAttribute    Given String version of ObjectName and name of attribute,
                returns value of attribute
getAttributes_jmx
                Given ObjectName and array of attribute names, returns
                AttributeList.
getAttributes   Given String version of ObjectName and attribute names,
                returns String of name value pairs. Given String version
                of ObjectName, returns String of all name value pairs.
getCell         Returns the cell name of the connected server
getConfigId     Given String version of ObjectName, return a configuration
                ID for the corresponding configuration object, if any
getDefaultDomain
                Returns "WebSphere"
getDomainName   Returns "WebSphere"
getHost         Returns String representation of connected host
getMBeanCount   Returns number of registered beans
getMBeanInfo_jmx
                Given ObjectName, returns MBeanInfo structure for MBean
getNode         Returns the node name of the connected server
getObjectInstance
                Given String version of ObjectName, returns ObjectInstance
                object that match.
getPort         Returns String representation of port in use
getType         Returns String representation of connection type in use
help            Shows help information
invoke_jmx      Given ObjectName, name of method, array of parameters and
                signature, invokes method on MBean specified
invoke          Invokes a method on the specified MBean
isRegistered_jmx
                Returns true if supplied ObjectName is registered
isRegistered    Returns true if supplied String version of ObjectName is
                registered
makeObjectName  Returns an ObjectName built with the given string
queryNames_jmx  Given ObjectName and QueryExp, retrieves set of ObjectNames
                that match.
queryNames      Given String version of ObjectName, retrieves String of
                ObjectNames that match
queryMBeans     Given String version of ObjectName, returns a set of
                ObjectInstances object that match
reconnect       Reconnects with server
setAttribute_jmx
                Given ObjectName and Attribute object, sets attribute for MBean
                specified
setAttribute    Given String version of ObjectName, attribute name and
                attribute value, sets attribute for MBean specified
setAttributes_jmx
                Given ObjectName and AttributeList object, sets attributes for
                the MBean specified
setAttributes   Given String version of ObjectName, attribute name
                and value pairs, sets attributes for the MBean specified
startServer     Given the name of a server, starts that server
stopServer      Given the name of a server, stops that server
testConnection  Tests the connection to a DataSource object
trace           Sets the wsadmin trace specification


wsadmin>print AdminApp.help()
WASX7095I: The AdminApp object allows application objects to be manipulated
        -- this includes installing, uninstalling, editing, and listing. Most
        of the commands supported by AdminApp operate in two modes: the default
        mode is one in which AdminApp communicates with the WebSphere server to
        accomplish its tasks.  A local mode is also possible, in which no
        server communication takes place.  The local mode operation is invoked
        by bringing up the scripting client with no server connected using the
        command line "-conntype NONE" option tor setting the
        "com.ibm.ws.scripting.connectionType=NONE" property in the
        wsadmin.properties.

        The following commands are supported by AdminApp; more detailed
        information about each of these commands is available by using the
        "help" command of AdminApp and supplying the name of the command
        as an argument.

deleteUserAndGroupEntries
                Deletes all the user/group information for all the roles and
                all the user name/password information for RunAs roles for a
                given application
edit            Edits the properties of an application
editInteractive Edits the properties of an application interactively
export          Exports application to a file
exportDDL       Exports DDL from application to a directory
exportFile      Exports content of a single file from an application to a file
getDeployStatus Returns the combined Deployment status of the application
help            Shows help information
install         Installs an application, given a file name and an option string
installInteractive
                Installs an application in interactive mode, given a file name
                and an option string
isAppReady      Checks whether the application is ready to be run
list            Lists all installed applications
listModules     Lists the modules in a specified application
options         Shows the options available, for a given file, application,
                or in general
renameApplication       Rename a given application
publishWSDL     Publishs WSDL files for a given application
searchJNDIReferences
                Lists application that refers to the given JNDIName on a given
                node
taskInfo        Shows detailed information pertaining to a given install task
                for a given file
uninstall       Uninstalls an application, given an application name and
                an option string
update          Updates an installed application
updateAccessIDs Updates the user/group binding information with accessID
                from user registry for a given application
updateInteractive       Updates an installed application interactively
view            Views an application or module, given an application or
                module name


wsadmin>print AdminTask.help()

WASX8001I: The AdminTask object enables the execution of available admin
        commands.  AdminTask commands operate in two modes:
        the default mode is one which AdminTask communicates with the WebSphere
        server to accomplish its task. A local mode is also available, in which
        no server communication takes place. The local mode of operation is
        invoked by bringing up the scripting client using the command line
        "-conntype NONE" option or setting the
        "com.ibm.ws.scripting.connectiontype=NONE" property in
        wsadmin.properties file.

The number of admin commands varies and depends on your WebSphere
install. Use the following help commands to obtain a list of supported
commands and their parameters:

help -commands                  Lists all the admin commands
help -commands         Lists admin commands matching with wildcard
                                "pattern"
help -commandGroups             Lists all the admin command groups
help -commandGroups    Lists admin command groups matching with
                                wildcard "pattern"
help commandName                Displays detailed information for the
                                specified command
help commandName stepName       Displays detailed information for the specified
                                step belonging to the specified command
help commandGroupName           Displays detailed information for the specified
                                command group

There are various flavors to invoke an admin command. They are

commandName                     Invokes an admin command that does not require
                                any argument.

commandName targetObject        Invokes an admin command with the specified
                                target object string, for example, the
                                configuration object name of a resource
                                adapter. The expected target object varies
                                with the admin command invoked. Use help
                                command to get information on the target
                                object of an admin command.

commandName options             Invokes an admin command with the specified
                                option strings. This invocation syntax is
                                used to invoke an admin command that does
                                not require a target object. It is also
                                used to enter interactive mode if
                                "-interactive" mode is included in the
                                options string.

commandName targetObject options        Invokes an admin command with the
                                        specified target object and options
                                        strings.  If "-interactive" is included
                                        in the options string, then interactive
                                        mode is entered.  The target object and
                                        options strings vary depending on the
                                        admin command invoked. Use help command
                                        to get information on the target object
                                        and options.

Sunday, August 24, 2014

Functions and Procedures in Jython wsadmin

Modular programming is the need in the every scripting language it will tear down the bigger problem statement into small pieces and easy to resolve. We can get the strategy in building the Jython Functions and Procedures for different tasks.



The are different ways to create the function body structure. A function is a sub program, which takes inputs as arguments, you can pass multiple arguments, same kind of data as agreements. A Function can return a value then that function call can be called in assignment statement, output statement, it can be in the expression.


  • Functions can be created to reduce the complexity in the scripts 
  • It  is easy to read and reuse them
  • Function definition became a procedure when there are no return statement in it


 

The function definition in Jython

The defining a new function starts with 'def' keyword. the function block begins with a name of the function and colon and followed by the Jython program control statement or JMX methods which are accessible on Admin Objects. At the end of the function you can have a return statement. If there is a need of validation to exit the function then we can use 'if-else' construct with different return expressions.

Function Definition in Jython




def add(x=1,y=2):  # default arguments
 z=x+y
 return z

def mul(x,y):
 return x*y

def greet():  # procedure  don't returns
 print 'Welcome to VybhavaTechnologies'

#==== main ====
a=100
b=200
print add(a,b) # function in output statement
c=add(a,b)+200 # function call in expression
print c
d=mul(a,b)  # function call in assignment
. print d
greet()

print 'Default args function:',add()
print 'Positional args:', add(y=240, x=300)

x= lambda a,b : a+b
print x(10, 30)

kb2mb=lambda kb: str(kb/1024)+'MB'


Output of the above example function in Jython as follows:

wsadmin>execfile('/home/krish/jython/functions.py')
300
500
Welcome to VybhavaTechnologies
Default args function: 3
Positional args: 540
40
2MB


Introspection in Jython functions


Using docStrings when a new function is defined. Any new user wish to modify it will give the description about how the function is constructed number of arguments and also tells how to use it. The docString can be accessible with __doc__ or func_doc function.

# This is illustrates functions

# Simple procedure definition
def cls():
        print "\n" * 50

def add(x, y):
        "This function takes two int args returns sum of them."
        z= x+y
        return z

def sub(x, y):
        "This will substract y from x and return it"
        z=x-y
        return z

def mul(x=1, y=10):
 """
 The mul function takes 2 int args and returns product of them.
 This function illustrates default values for arguments
 """
 z = x * y
 return z

#=== Main ====
cls()
a, b= input("Enter two numbers:")
result = add(a, b)
print result
result = add(a, b) + sub(a, b)
print result

if add(a,b) > 0:
        print "addition of a, b is positive"

result = mul(10)
print result, " 10 argument"

result = mul(10, 30)
print result, "10, 30 are arguments"

result = mul()
print result, " no args"

result = mul(y=40)
print result, " y arg passed"

#print z  scope of variables expires within the function only

Sample Jython Functions : functionEx.py 
Execution of functions in Jython, Lambda functions, introspection of function
Introspection of Jython docString comments sample for function definitions

Function calling in Jython


You can call the function in the following ways:

  1. Assignment statement
  2. Expression statement
  3. In the program controls
  4. print statements

In the above sample script we have function calls as following in the main program.
result = add(a, b)
print result
result = add(a, b) + sub(a, b)
print result

if add(a,b) > 0:
        print "addition of a, b is positive"



Errors and Exceptions in Jython

Welcome to Jython4wsadmin blog!! This post is intended to collect all Errors and Exceptions that can occur when you work on WebSphere administration using wsadmin scripting. As you are aware that Jython is inherited from Python. We can categories the Errors and Exceptions as per their inheriting languages.

  1. Errors defined in Python
  2. Exception from Java
  3. Script based Exceptions depends on WASXShell


When you start woking on the WebSphere Admin scripts you might encounter many types of Errors and Exceptions. Here you must focus on Python based Errors to make syntatic correct code.



wsadmin>execfile('/home/krish/jython/while.py')
WASX7015E: Exception running command: "execfile('/home/krish/jython/while.py')"; exception information:
com.ibm.bsf.BSFException: exception from Jython:
Traceback (innermost last):
  File "<input>", line 1, in ?
  File "/home/krish/jython/while.py", line 11
        while x>=0
                  ^
SyntaxError: invalid syntax

colon missing
Here it is simple syntax error  where its fix is appending the colon for the while loop. Same could be possible error in function definitions class definitions, if-else or for loop program controls. So you need to double check the code syntax is structured in right format or not.


wsadmin>execfile('/home/krish/jython/while.py')
WASX7015E: Exception running command: "execfile('/home/krish/jython/while.py')"; exception information:
com.ibm.bsf.BSFException: exception from Jython:
Traceback (innermost last):
  File "<input>", line 1, in ?
  File "/home/krish/jython/while.py", line 12
        print x
        ^
SyntaxError: invalid syntax


invalid indundation problem corrected with space.


Exception Handling in Jython


Lets see the simple interactive try-except sample in wsadmin shell. Here I am trying to access the method which does not exist in the AdminTask object.

wsadmin>try: AdminTask.test()
wsadmin>except: print 'catch exception'
wsadmin>
catch exception

Handling with sys.exc_info() dictionary

Sample Exception handling script that uses except block with the sys.exc_info() method which returns a dictionary. You can collect the necessary information out of it using list slice and using dictionary key, value pair of second element.
# Illustration of Simple Exception example

try:
        cellname=AdminControl.getCell()
        print "CellName: ", cellname
        print AdminConfig.list(Cell)
except Exception:
        print "in the Exception block..."
        (k, v)=sys.exc_info()[:2]
        print "Type :", k, "\n", "error reason :", v


Execution of the above script gives the following output:
wsadmin>execfile('/home/vagrant/scripts/except1.py')
CellName:  ubuntu-was8Node01Cell
in the Exception block...
Type : exceptions.NameError
error reason : Cell

The pass statement


This 'pass' statement could be used in the initial state of script. It is going to tell 'DO NOTHING' block. Normally it would be used in the except block.
try:
 # do here some task

except:
 pass 


Raise Exception


The raise keyword is used to propagate a exception when you are using multiple functional calls. Final calling function need the exception details then raise will be used in the except block of called function.
try:
 # Do wsadmin task here

except Exception, e:
 raise "Error Message"


Template for Exception handling


If you keep this template you can build robust script very easily.
try:
 # Do some wsadmin statement execution here

except Exception, e:
 print "Exception catch..."
finally:
 print "In the finally..."
 # Do something 

Please share your comment while you execute these samples on your project automations.

Tuesday, August 19, 2014

Dictionary Accessing


Dictionary Accessing 

Jython provides many sequqnces and datastructures. Here is a map type where it is a combination of key and value pair or elements in a list.

Diectonary in Jython script
Lets do the experiment with Dictonary objects in Jython.
Example of Dicttionary objects in Jython


#This script is for adding, deleting, modifying,itrating.

D={'dmgr':'10.12.13.14:80','app1':'10.0.0.12:90','app2':'10.0.0.15:100'}

#Adding a element to dictionary D.

D['app3']='10.1.1.12:85'
#Update with New dictionary
D2={'app4':'10.0.0.0:95'}
D.update(D2)
for k,v in D.items(): print k,'->',v

#modifying dictionary element

print 'modifying the dictionary app2'

D['app2']='10.0.0.15:98'
for k,v in D.items(): print k,'->',v

keylist=D.keys()

k=keylist.sort()

print keylist

for k in keylist: print k,'->',D[k]


O/P

wsadmin>execfile('/home/krish/jython/dict.acc.py')
app4 -> 10.0.0.0:95
dmgr -> 10.12.13.14:80
app3 -> 10.1.1.12:85
app2 -> 10.0.0.15:100
app1 -> 10.0.0.12:90
modifying the dictionary app2
app4 -> 10.0.0.0:95
dmgr -> 10.12.13.14:80
app3 -> 10.1.1.12:85
app2 -> 10.0.0.15:98
app1 -> 10.0.0.12:90
['app1', 'app2', 'app3', 'app4', 'dmgr']
app1 -> 10.0.0.12:90
app2 -> 10.0.0.15:98
app3 -> 10.1.1.12:85
app4 -> 10.0.0.0:95
dmgr -> 10.12.13.14:80


Dictionary Data type in Jython wsadmin


Dictionary Data type

Now I have to evaluate dictionaries in the sequences types.  It is the combination of (Key, Value) pairs forms as elements in the dictionary type. We can extract each one as separate list that is keys list, values list. See my examples given in the below:

Diectionary type in Jython


# items is list of tuples and list variables, list variables in#This script will be sample for the dictionary type

D1={}
print D1

D2={'app1':'192.168.11.129:80', 'app2':'192.168.11.130:81$


print D2

print D2['app2']

print D2.keys()

print D2.values()

print D2.items()

$variables in square brackets and tuples in round bracket$ square brackets and tuples in round brackets.


O/P


{}
{'app2': '192.168.11.130:81', 'app1': '192.168.11.129:80'}
192.168.11.130:81
['app2', 'app1']
['192.168.11.130:81', '192.168.11.129:80']
[('app2', '192.168.11.130:81'), ('app1', '192.168.11.129:80')]


Tuesday, August 12, 2014

Jython variables in wsadmin

A warm Welcome to my jython4wsadmin blog!!

Variables in programming languages we need to declare on the top of the function or program. When we declare it we need to tell about what type of data we would like to store in the variable. Where as in Scripting languages you don't need to do so. Jython is a scripting language so you don't need to declare the variable.

Like any programming language Jython also support variables but these variables looks like scripting variables, they are dynamic.
The value that assigned to a variable is going to have an id and label internally it is one of the Python Object type as well.

Let me experiment with my simple Jython script to understand more how the variables can be created and used in multi variants. Here the values can be integer, float, long types in numeric data types.

Jython Variable inside wsadmin

	# This program will illustrate the variables of jython.
	# Integer variable
	x=5
	print 'x=', x, type(x), id(x)

	# Multiple Variables can be assigned with multiple values respectively
	y, z=10, 30
	print 'y=',y, 'z=',z

	# Float number
	f=10.45
	print "f=", f, type(f), id(f)

	# Boolean value
	b=10<40 and="" assert="" b=",b, type(b), id(b)

	# String value
	cellName=" cellname:="" cellname="" democell="" pre="" print="" t="">
The script execution can be done using execfile function that takes the path for the Jython script.<br /> Better to have the all Jython scripts at one common place, I"> Output of the above script looks like this...

Best practice: Avoid the keyword in the namespaces

How do I know what all the keywords available in Jython? It is easy to determine that, from the keyword module you can get keyword list as shown below:
wsadmin>import keyword
wsadmin>keyword.kwlist
['and', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while']

Note: Don't use any of these keywords in the function names, class name or variable names.

How the type Casting works in Jython?

Unlike any other programming languages we have typecasting allowed in Jython script. What do you mean by casting? It is simple converting from one type of data to another type. Following illustrates a float value casting to int type.
	wsadmin>f=10/3.0
	wsadmin>print f
	3.3333333333333335
	wsadmin>cast2int = int(f)
	wsadmin>print cast2int
	3

Casting a int value to str type
	wsadmin>str(cast2int)
	'3'

Converting a int value to chr type
	wsadmin>chr(65)
	'A'

Hope you enjoyed this post please write your comment where did you use the post. Information is wealth!! keep sharing this knowledge article.

Containerization with Docker

Containerization with Docker
Learn modern microservices containers grow