Jython Script Examples

1.    Validate IP Address (from Service Catalog Sample Content)
# this script takes a field values and verifies it is a valid ip address. 
# It checks the following
# 1) Are there 4 tuples, separated by dots (.)
# 2) Each tuple is a valid number
# 3) Each tuple is between 0 and 255


errmsg = ''
rc = 1
ipList = newValue.split('.')
if len(ipList) == 4:
   for i in ipList:

      try:

         i = int(i)

      except:

         rc = 0

         errmsg = i, ' is not a valid number. IP Addresses must contain valid numbers'
         break
      if i > 255:

         rc = 0

         errmsg = i, ' is greater than 255. Valid IP Addresses are between 0 and 255.'
         break
else:
   rc = 0
   errmsg = 'IP Addresses must be in the form nn.nn.nn.nn'

print rc
print errmsg


2.    If the Install DB field is checked, automatically fill the DBDIR and DBADMIN fields (from Service Catalog Sample Content)

# automatically populate fields based on a user selecting a field
# user selects INSTALL DB2?
# fill in the DBDIR and DBADMIN fields.  
 
if (newValue == '1'):
   dbdir = offeringAttributes.getValue("DBDIR");
 
   dbadmin = offeringAttributes.getValue("DBADMIN")
   if len(dbdir) == 0:
      offeringAttributes.setNewValue("DBDIR", "c:/ibm/db2");
   if len(dbadmin) == 0:
      offeringAttributes.setNewValue("DBADMIN", "db2admin");
print True
3.    Check that the email address entered does not already exist in the EMAIL db table
# Check that the email address entered is not already in use in the system
# by checking the EMAILADDRESS values in the EMAIL db table 
 
from psdi.security import UserInfo
from psdi.mbo import MboServerInterface
 
user = scriptHome.getUserInfo();
 
mboServer = scriptHome.getMboServer();
 
emailSet= mboServer.getMboSet("EMAIL", user);
 
emailSet.setQbeExactMatch(True);
emailEntered = "\"" + newValue + "\""
emailSet.setQbe("EMAILADDRESS", emailEntered);
emailSet.reset();
 
# if the email address was found, return an error
# otherwise email address is good
count = emailSet.count();
if count == 1:
   print 0
   print 'Email address already in use'
else:
   if newValue.find('@') == -1:
      print 0
      print 'Email address is not valid, it must contain an @'
   else:   
      print 1
 
4.    Retrieve the person record for the person selected, and populate the readonly fields on the dialog (CLUSTUID, FIRSTNAME, LASTNAME)
 
# when a person is selected, 
# get information from the PERSON record to populate the CLUSTUID, FIRSTNAME and LASTNAME fields
 
from psdi.security import UserInfo
from psdi.mbo import MboServerInterface
 
personSelected = newValue
 
user = scriptHome.getUserInfo();
 
mboServer = scriptHome.getMboServer();
 
personSet = mboServer.getMboSet("PERSON", user);
 
personSet.setQbeExactMatch(True);
qp = "\"" + personSelected + "\""
personSet.setQbe("PERSONID", qp);
personSet.reset();
 
person = personSet.getMbo(0);
 
personuid = person.getInt("PERSONUID");
spersonuid = str(personuid)
offeringAttributes.setNewValue("CLUSTUID", spersonuid);
 
fname = person.getString("FIRSTNAME");
offeringAttributes.setNewValue("FIRSTNAME", fname);
 
lname = person.getString("LASTNAME");
offeringAttributes.setNewValue("LASTNAME", lname);
 
5.    Populate an int field base on a value selected from a table domain attribute
# Populate an int field based on the value selected from a table domain attribute
 
from psdi.security import UserInfo
from psdi.mbo import MboServerInterface
 
# this is the value selected on the lookup
servSelected = newValue
 
user = scriptHome.getUserInfo();
mboServer = scriptHome.getMboServer();
 
servSet = mboServer.getMboSet("SPPC_VM", user);
 
# get the servid from the servset for the VM Name passed in
servSet.setUserWhere("NAME = '"+servSelected+"'");
serv= servSet.getMbo(0);
 
# get the UUID from the mbo
uuid= serv.getString("UUID");
 
# set the uuid value into the SPPC_VM_UUID offering attribute 
offeringAttributes.setNewValue("SPPC_VM_UUID",uuid); 

6.    Verify that the 2 password fields that were entered match (add to the 2nd password attribute)
# Validate that the 2 password fields entered match
cnfmpwd = newValue
currpwd = offeringAttributes.getValue("CURRPWD");
 
if cnfmpwd == currpwd:
   print 1
else:
   print 0
   print 'Passwords do not match'
 
7.    Verify that the field entered is a valid number
 
# make sure the value specified is all valid digits
rc = True
errmsg = ''
if newValue.isdigit() == False:
   rc = False
   errmsg = ' Field must be numeric'
print rc
print errmsg
 
8.    Create a string and set the value of one field, based on the value of another


# build and set the value of the derivedhostname field based on the PROPERTY field
property= offeringAttributes.getValue("PROPERTY");
dhostname = newValue+'.'+property+'.abc.com'
offeringAttributes.setNewValue("DERIVEDHOSTNAME",dhostname);
print True

9.    Ensure the end date is after the start date
# Check that end date comes after start date
 
from java.text import SimpleDateFormat
 
fmt = SimpleDateFormat('MM/d/yy')
 
rc = 1
errmsg = ''
 
# get the fields
startdatestr = offeringAttributes.getValue("STARTDATE");
enddatestr = offeringAttributes.getValue("PENDDATE");
 
# if both have values, format them, and ensure the enddate is after the start date
if len(startdatestr) > 0 and len(enddatestr) > 0: 
   startdate = fmt.parse(startdatestr)
   enddate = fmt.parse(enddatestr)
   if enddate.before(startdate):
      rc = 0
      errmsg = 'Start Date must be less than End Date'
 
print rc
print errmsg

10. Set the Contact field before the offering dialog is displayed
(from Service Catalog Sample Content)
# get the display name for the user logged into maximo
# if the contact field is not already set, then set it 
# with the user's display name
 
from psdi.security import UserInfo
displayName = scriptHome.getUserInfo().getDisplayName();
contact = offeringAttributes.getValue("CONTACT");
if len(contact) == 0:
   offeringAttributes.setNewValue("CONTACT", displayName);
 
11. Retrieves the SR associated with the offering, and sets the Urgency and Impact values
# Sets the urgency and impact fields on the associated SR
# run as a prepopulation script (does not return a return code value)
srs = offeringAttributes.getMboSet("SR");
sr = srs.getMbo(0);
sr.setValue("urgency", 1);
sr.setValue("impact", 1);
 
12. Set the Contact field, but set the Project field, to a generated idenitifer based on the time Make sure if the INSTMQ checkbox field is checked that the MQDIR field is filled in (from Service Catalog Sample Content)
 
# This script is the same as the PrepopUser script
# except it also generated a unique project identifier (based on time)
# and sets the Project field
 
from psdi.security import UserInfo
from java.lang import System
displayName = scriptHome.getUserInfo().getDisplayName();
offeringAttributes.setNewValue("CONTACT", displayName);
 
time = System.currentTimeMillis();
proj = 'LTE_Project_' +str(time);
offeringAttributes.setNewValue("PROJNAME",proj);
================================================
# Check the attribute, INSTMQ.  If it is selected
# then get the value of the MQDIR attribute, and make
# sure it is filled in by the user.  
rc = True
errmsg = ''
installmq = offeringAttributes.getValue("INSTMQ");
mqdir = offeringAttributes.getValue("MQDIR");
if installmq == '1':
    if len(mqdir) == 0:
        rc = False
        errmsg = 'If the Install MQ attribute is 1, then the MQ Directory Location attribute is required'
print rc
print errmsg
 
13. A script meant to run as a global submit cart script.  It checks for a specific combination of offerings in the cart, and returns an error if both are not in the cart (from Service Catalog Samplet Content)

# This script looks for the PMSC_2021A (Build Server with Middleware) offering in the cart
# If it finds it, and the INSTALL DB (INSTDB) checkbox was checked, then it 
# checks to make sure offering PMSC_@007A (Add Database to Server) offering is also in the cart
 
# This script is written to run as a global submit cart script, not an offering level submit cart
# script.  
 
rc = True
errmsg = ''
 
foundPMSC_2021A = False
foundPMSC_2007A = False
 
numItems = len(itemsInCart)
 
for i in range(numItems):
   item  = itemsInCart[i]
   if item != None:
      itemnum = item.getString("PMSCITEMNUM")
      print 'itemnum = ', itemnum
      if itemnum == 'PMSC_2021A':
         attrs = itemAttributes[i]
         dbyesno = attrs.getValue("INSTDB")
         print 'dbyesno = ', dbyesno
         if dbyesno == '1':
            foundPMSC_2021A = True
      elif itemnum == 'PMSC_2007A':
         foundPMSC_2007A = True
print 'foundPMSC_2021A = ', foundPMSC_2021A
print 'foundPMSC_2007A = ', foundPMSC_2007A
 
if foundPMSC_2021A == True and foundPMSC_2007A == False:
      rc = False
      errmsg = 'If Build New Server with Middleware is in the cart and the Install DB attribute is 1, then the Add Database To Server offering must also be included in the cart'
 
print rc
print errmsg

14. Copy the REQUESTEDFOR field from the cart to AFFECTEDPERSON and PMSCAFFECTEDPERSON fields on all the Items (SRs) in the cart. 

# for each item in the cart, set the affectedperson and pmscaffectedperson fields from the requestedfor field on the cart.
rc = True
errmsg = ''
 
numItems = len(itemsInCart)
requestedfor = cart.getString("REQUESTEDFOR")
 
for i in range(numItems):
   item = itemsInCart[i]
   if item != None:
      item.setValue("AFFECTEDPERSON", requestedfor)
      item.setValue("PMSCAFFECTEDPERSON", requestedfor)
 
print rc
print errmsg 
 
15. Add an offering to the cart

# used as an add to cart script
 
from psdi.security import UserInfo
from psdi.mbo import MboServerInterface
 
user = scriptHome.getUserInfo();
print 'user = ', user
 
mboServer = scriptHome.getMboServer();
print 'mboServer = ', mboServer
 
# get the offering set
offerings = mboServer.getMboSet("PMSCOFFERING", user);
print 'offerings = ', offerings
 
# get the desired offering to add to the cart
offering = offerings.getMboForUniqueId(441);
itemnum = offering.getString("ITEMNUM");
print  'offering itemnum = ', itemnum
 
# get the catalogs
catalogs = mboServer.getMboSet("PMSCCATALOG", user);
catalog = catalogs.getMbo(0);
print 'catalog = ',catalog
 
# find the draft cart for this user
catalog.openLastCR(None, None);
cr = catalog.createCRInfo(offering);
print 'cr = ', cr

16. If a specific offering is found in the cart, add an additional offering to the cart
# used as a submit cart script
 
from psdi.security import UserInfo
from psdi.mbo import MboServerInterface
 
rc = False
errmsg = ''
gsb = False
foundITD_PREBUILD = 0
foundITD_POSTBUILD = 0
 
# Get the user info
user = scriptHome.getUserInfo();
 
# Get the server info
mboServer = scriptHome.getMboServer();
 
# get the catalog map
catalogmaps = mboServer.getMboSet("PMSCCATALOGOFFMAP", user);
catalogmaps.setUserWhere("ITEMNUM = 'GLOBAL SERVER BUILD'");
numoff = catalogmaps.count();
 
# Initialisation of the Array
itemnum1= []
for i in range(numoff):
       catalogmap = catalogmaps.getMbo(i);
       itemnum1.append(catalogmap.getString("OFFERINGNUM"));
 
numItems = len(itemsInCart)
 
for i in range(numItems):
       item  = itemsInCart[i]
       if item != None:
                    itemnum = item.getString("PMSCITEMNUM")
                    for i in range(numoff):
                                if itemnum == itemnum1[i]:
                                            gsb = True
                                if itemnum == 'ITD_PREBUILD':
                                            foundITD_PREBUILD = foundITD_PREBUILD + 1
                                elif itemnum == 'ITD_POSTBUILD':
                                            foundITD_POSTBUILD = foundITD_POSTBUILD + 1
 
if gsb == True:
       if (foundITD_PREBUILD > 0 or foundITD_POSTBUILD > 0):
                    rc = False
                    errmsg = 'You can not add a Pre or Post build offering to the cart.'
                    print rc
                    print errmsg
 
       # get the catalog
       catalogs = mboServer.getMboSet("PMSCCATALOG", user);
       catalogs.setUserWhere("ITEMNUM = 'GLOBAL SERVER BUILD'");
       catalog = catalogs.getMbo(0);
 
       # get the offering set for ITD_PREBUILD
       offerings = mboServer.getMboSet("PMSCOFFERING", user);
       offerings.setUserWhere("ITEMNUM = 'ITD_PREBUILD'");
 
       # add the desired offering to add to the cart
       offering = offerings.getMbo(0);
       itemnum = offering.getString("ITEMNUM");
 
       # find the draft cart for this user
       catalog.openLastCR(None, None);
       cr = catalog.createCRInfo(offering);
 
       # get the offering set for ITD_POSTBUILD
       offerings = mboServer.getMboSet("PMSCOFFERING", user);
       offerings.setUserWhere("ITEMNUM = 'ITD_POSTBUILD'");
 
       offering = offerings.getMbo(0);
       itemnum = offering.getString("ITEMNUM");
 
       # find the draft cart for this user
       catalog.openLastCR(None, None);
       cr = catalog.createCRInfo(offering);
 
 
 
17. Script calling another jython script
 
# This script executes another script called 'HELLO1' 
print "Beginning of Test"
 
print scriptHome.getUniqueIDValue()
 
x=10
 
 
scriptMbos = scriptHome.getMboSet("$scripts", "AUTOSCRIPT", "autoscript = 'HELLO1' ")
scriptMbo = scriptMbos.getMbo(0)
script = scriptMbo.getString("SOURCE")
exec (script) 
print x
 
print "End of Test"
 
18. Date validation
 
To check whether the spec attribute string is a valid date - 
 
#print 0
from java.util import Date
from java.text import DateFormat;
 
rc = 1
errmsg = ''
datefld =''
 
# Get user's current Locale
userLocale = scriptHome.getUserInfo().getLocale();
 
# Get user's date format
userDateFormat = DateFormat.getDateInstance(DateFormat.SHORT, userLocale);
 
# Set Date Time Parser to Strict 
# DateFormat still has a limitation. Year can be any number of digits or even negative.
userDateFormat.setLenient(0);
 
# Check to see if the date converts to a valid Date value
try:
 datefld = userDateFormat.parse(newValue)
except:
 rc = 0
 print rc
 print 'Invalid date. Please enter date in month/day/year format or use the Lookup icon to select a date'
 

Popular posts from this blog

Skip fields during duplication