# %I% %W% %G% %U%
# Licensed Materials - Property of IBM
#
# 5724-F71 5724-J10
#
# (C) Copyright IBM Corporation 2004, 2005 All Rights Reserved
#
# US Government Users Restricted Rights- Use, duplication or
# disclosure restricted by GSA ADP Schedule Contract with IBM
# Corp.
#
# This is sample code made available for use in accordance with
# terms set forth in the license agreement document for the IBM
# Integrated Runtime.

#---------------------------------------------------
# Config procs
#---------------------------------------------------
#  The purpose of this example is to demonstrate the creation of a
#  JDBCProvider, DataSource and CMPConnectorFactory objects.
#
#  This script can be included in the wsadmin command invocation like this:
#
#     wsadmin -lang jython -f ex9.py mynode "DB2 JDBC Provider (XA)" c:/SQLLIB/java/db2java.zip myds mycf sampleDB
#
#  The script expects 7 parameters:
#    node name
#    template name for JDBCProvider
#    fully-qualified path to the driver
#    jdbc provider name to be created
#    datasource name to be created
#    CMP Connection factory name to be created
#    name of database
#
#  This example demonstrates many wsadmin features:
#
#   - The use of the AdminConfig object to locate configuration objects
#   - The use of the AdminConfig object to modify configuration objects
#   - The use of the AdminConfig object to create configuration objects
#   - The use of the AdminConfig object to remove configuration objects
#-----------------------------------------------------------------
#

def time():
    print "Current Time is " + java.util.Calendar.getInstance().getTime().toString()
#enddef

def replaceVariableMapEntry(nodeName, symName, value): 
   #---------------------------------------------------------
   # Get the config id for the node's variable map
   #---------------------------------------------------------
   print "getting the config id for the variable map object on node " + nodeName
   varmap = AdminConfig.getid("/Node:" + nodeName + "/VariableMap:/")
   if len(varmap) == 0:
      print "could not find a VariableMap object in node " + nodeName
      return
      
   entries = AdminConfig.list('VariableSubstitutionEntry', varmap)

   if (entries != ""):
       entries = entries.split((java.lang.System.getProperty('line.separator')))
       for entry in entries:
          entryName = AdminConfig.showAttribute(entry,  'symbolicName')
          if (symName == entryName):
              print "Removing variableMap entry", entryName
              AdminConfig.remove(entry)
            
   #---------------------------------------------------------
   # Create a mapping 
   #---------------------------------------------------------
   print "create a variable in the variable map" 
   nameAttr = ["symbolicName", symName] 
   #valAttr = ["value", "\${WAS_INSTALL_ROOT}/classes"] 
   valAttr = ["value", value] 
   attrs = []
   attrs.append(nameAttr)
   attrs.append(valAttr)
   
   AdminConfig.modify(varmap,[['entries',[attrs]]])
   print "end replaceVariableMapEntry"



# Create a JDBC Provider
#    If serverName is non-empty, this is DB2 and dbname, serverName, and port are what they say they are.
#    If serverName is the empty string, dbname is the Oracle URL, and serverName and port are ignored.
#
def createJDBCProviderDataSource(nodeName, templateName, jdbcname, jndiname, dsname, dbname, serverName, port, authAliasName, cmpds):

   #---------------------------------------------------------
   # Get the config id for a JDBC Template
   # Use "lindex" in case there is more than one matching templates -- we
   # just get the first one.
   #---------------------------------------------------------
   print ""
   print "createJDBCProviderDataSource: getting the JDBCProvider template whose name is " +  templateName
   template = AdminConfig.listTemplates("JDBCProvider", templateName).split(lineSeparator)[0]
   if len(template) == 0:
      print "createJDBCProviderDataSource: could not find a JDBCProvider template using " + templateName
      return

   #---------------------------------------------------------
   # Get the config id for the node
   #---------------------------------------------------------
   print "createJDBCProviderDataSource: getting the confid id for node " + nodeName
   node = AdminConfig.getid("/Node:" + nodeName + "/")
   if len(node) == 0:
      print "createJDBCProviderDataSource: could not find node " + nodeName
      return

   #---------------------------------------------------------
   # Create a new JDBCProvider using this template
   #---------------------------------------------------------
   print "createJDBCProviderDataSource: create a new JDBCProvider object named " + jdbcname
   #classpathAttr = ["classpath", driverPath]
   classpathAttr = ["classpath", "${ORACLE_JDBC_DRIVER_PATH}/ojdbc8.jar"]
   nameAttr = ["name", jdbcname]
   attrs = []
   attrs.append(nameAttr)
   attrs.append(classpathAttr)
   new1 = AdminConfig.createUsingTemplate("JDBCProvider", node, attrs, template)

   #---------------------------------------------------------
   # For this example, we do not need the WAS40DataSource object, but
   # we do want to modify the DataSource object.
   # Note that the template for this JDBCProvider does not give
   # names to the WAS40DataSource and DataSource objects associated with
   # it.  We can use "getid" to retrieve ids for objects that do not have
   # names as shown below.
   #---------------------------------------------------------
   print "createJDBCProviderDataSource: remove the WAS40DataSource object created via the template"
   was40ds = AdminConfig.getid("/JDBCProvider:" + jdbcname + "/WAS40DataSource:/")
   AdminConfig.remove(was40ds)

   #--------------------------------------------------------------
   # Modify the DataSource - give it a name and a jndiName, and remove
   # existing properties created by the template
   # A collection of objects (such as the resourceProperties attribute of the
   # propertySet attribute) can only be added to.  To completely replace
   # the collection you need to delete the old one first.
   #--------------------------------------------------------------
   print "createJDBCProviderDataSource: modify the datasource object -- name, jndiName; remove old properties."
   ds = AdminConfig.getid("/JDBCProvider:" + jdbcname + "/DataSource:/")
   nameAttr = ["name", dsname]

   #--------------------------------------------------------------
   # Set up a relational resource adapter if a CMP datasource.
   #--------------------------------------------------------------
   rra = AdminConfig.getid("/Node:" + nodeName + "/J2CResourceAdapter:WebSphere Relational Resource Adapter/")
   rraAttr = ["relationalResourceAdapter" , rra]
   jndiNameAttr = ["jndiName", jndiname]
   authAliasAttr = ["authDataAlias", authAliasName]
   xaRecoveryAliasAttr = ["xaRecoveryAuthAlias", authAliasName]
   psAttr = ["propertySet", []]
   mappingAttr = ["mapping", [
                    ["authDataAlias", authAliasName],
                    ["mappingConfigAlias", "DefaultPrincipalMapping"] ]]
   attrs = []
   attrs.append(nameAttr)
   attrs.append(jndiNameAttr)
   attrs.append(authAliasAttr)
   attrs.append(xaRecoveryAliasAttr)
   attrs.append(psAttr)
   attrs.append(mappingAttr)
   attrs.append(rraAttr)
   AdminConfig.modify(ds, attrs)

   #--------------------------------------------------------------
   # Add desired properties to the DataSource.
   #--------------------------------------------------------------
   print "createJDBCProviderDataSource: modify the datasource properties."
   newsprops = []
   if (serverName != ""):
      # This is DB2, need lots of arguments
      dbnameAttr = [["name", "databaseName"], ["value", dbname], ["type", "java.lang.String"], ["description", "This is a required property"]]
      serverAttr = [["name", "serverName"], ["value", serverName], ["type", "java.lang.String"]]
      portAttr = [["name", "portNumber"], ["value", port], ["type", "java.lang.Integer"]]
      typeAttr = [["name", "driverType"], ["value", 4], ["type", "java.lang.Integer"]]
      newsprops.append(dbnameAttr)
      newsprops.append(serverAttr)
      newsprops.append(portAttr)
      newsprops.append(typeAttr)
   else:
      # This is Oracle, need only URL in the dbname
      dbnameAttr = [["name", "URL"], ["value", dbname], ["type", "java.lang.String"], ["description", "This is a required property"]]
      newsprops.append(dbnameAttr)
   #endif

   # For SCR 40603 - extra setting to work around a bug.
   rraSetEquals = [["name", "useRRASetEquals"], ["value", "true"], ["type", "java.lang.String"], ["description", "See IBM APAR PK75897"]]
   newsprops.append(rraSetEquals)

   # Finish setting the optional properties.  The nesting of these lists is insane.
   psAttr = ["propertySet", [["resourceProperties", newsprops]]]
   attrs = [psAttr]
   AdminConfig.modify(ds, attrs)

   # Now let everyone know what I did.  The output format isn't great.
   print "JDBCProviderDataSource", jdbcname, " Properties:"
   #print AdminConfig.showall(ds)

   #--------------------------------------------------------------
   # Now create the CMPConnectorFactory.
   #--------------------------------------------------------------
   if (cmpds == "true"):
     print "createJDBCProviderDataSource: create CMPConnectorFactory"
     cfNameAttr = ["name", dsname + "_CF"]
     cfauthMech = ["authMechanismPreference", "BASIC_PASSWORD"]
     cfDsAttr = ["cmpDatasource", ds]
     cfAttrs = []
     cfAttrs.append(cfNameAttr)
     cfAttrs.append(cfauthMech)
     cfAttrs.append(authAliasAttr)
     cfAttrs.append(mappingAttr)
     cfAttrs.append(xaRecoveryAliasAttr)
     cfAttrs.append(cfDsAttr)
     conFactory = AdminConfig.create("CMPConnectorFactory", rra, cfAttrs)
     print "CMPConnectorFactory", conFactory, " Properties:"
     print AdminConfig.showall(conFactory)

#---------------------------------------------------------
# createJAASDataAuth - this is used for connection to the
#                   database and authorization for the database
#
# JAASDataAuth attributes are:
#  "alias String"
#  "description String"
#  "password String"
#  "userId String"
#---------------------------------------------------------
def createJAASDataAuth (aliasName, user, pw, desc):

    #---------------------------------------------------------
    # Get the config id for the Cell's Security object
    #---------------------------------------------------------

    print "createJAASDataAuth: get the cell's Security object"
    cell = AdminControl.getCell()
    sec = AdminConfig.getid("/Cell:" + cell + "/Security:/")

    #---------------------------------------------------------
    # Create a JAASAuthData object for component-managed authentication
    #---------------------------------------------------------
    print "createJAASDataAuth: create JAASAuthData object for component-managed authentication"

    aliasAttr = ["alias", aliasName]
    descAttr = ["description", desc]
    useridAttr = ["userId", user]
    passwordAttr = ["password", pw]
    attrs = []
    attrs.append(aliasAttr)
    attrs.append(descAttr)
    attrs.append(useridAttr)
    attrs.append(passwordAttr)

    # create special attributes to be logged - we do not want to log the password
    pw_attr_log = ["password", "********"]
    jaas_attrs_log = []
    jaas_attrs_log.append(aliasAttr)
    jaas_attrs_log.append(useridAttr)
    jaas_attrs_log.append(pw_attr_log)
    jaas_attrs_log.append(descAttr)
    print " "
    print "ConfigProcs: AdminConfig create JAASAuthData"
    print "sec=", sec
    print "jaas_atttrs_log=" , jaas_attrs_log
    print " "
    try:
        AdminConfig.create("JAASAuthData", sec, attrs)
    except:
         print "createJAASDataAuth EXCEPTION: ", sys.exc_type, sys.exc_value

    print "End createJAASDataAuth"

#---------------------------------------------------
#
# save Configuration
#---------------------------------------------------
def saveConfiguration():
    print "\nConfigProcs: Saving the configuration"
    AdminConfig.save()


#-----------------------------------------------------------------
# installWar - Install the specified application war file if an
#            application with the same name does not exist.
#-----------------------------------------------------------------
def installWar (appName, war, context, deployejb, deployws, defaultBindings, dbType, target):
   #    appName         - application name
   #    war             - war file
   #    context         - context
   #    deployejb       - deploy ejb (true|false)
   #    deployws        - deploy webservices (true|false)
   #    defaultBindings - use default binding (true|false)
   #    dbType          - ejb deploy db type
   #    target[0]       - node name or cluster name
   #    target[1]       - server name


   print ""
   print "Installing application {appName}..."

   # Check if the application already exists


   appsList = AdminApp.list().split(java.lang.System.getProperty('line.separator'))

   result = "APP_DOES_NOT_EXIST"

   for installedAppName in appsList:
       if (installedAppName == appName):
           result = "APP_EXISTS"
           app = ""
           break


   if (result == "APP_DOES_NOT_EXIST"):
      print "  Application Name:      " + appName
      print "  War file:              " + war
      print "  Context:               " + context
      if (len(target) == 1):
         print "  Target Cluster:        "+ target[0]
      else:
         print "  Target Node:           "+ target[0]
         print "  Target Server:         "+ target[1]
      print "  Deploy EJB:            " + deployejb
      print "  Deploy WebServices:    " + deployws
      print "  Use default bindings:  " + defaultBindings
      print "  Deployed DB Type:      " + dbType

      appOptions = []
      nameOpt = ["-appname", appName]
      appOptions.extend(nameOpt)
      contextOpt = ["-contextroot", context]
      appOptions.extend(contextOpt)

      if (deployejb == "true"):
         deployOpt = ["-deployejb", "-deployejb.dbtype", dbType]
         appOptions.extend(deployOpt)
      if (deployws == "true"):
         wsOpt = [" -deployws"]
         appOptions.extend(wsOpt)
      if (defaultBindings == "true"):
#         defaultBindingsOpt = [" -usedefaultbindings"]
         defaultBindingsOpt = [" -noprocessEmbeddedConfig"]
         appOptions.extend(defaultBindingsOpt)

#      if (len(target) == 1):
#         mainOpt = [" -cluster ", target[0]]
#      else:
#         mainOpt = [" -node ", target[0], " -server ", target[1]]
#      appOptions.extend(mainOpt)

      print "Starting application install..."

      app = AdminApp.install(war, appOptions)

      print "Install completed successfully!"

   else:
      print appName + " already exists!"

   return app

#-----------------------------------------------------------------
# installEar - Install the specified application war file if an
#            application with the same name does not exist.
#-----------------------------------------------------------------
def installEar (appName, ear):
   #    appName         - application name
   #    ear             - ear file

   print ""
   print "Installing application " + appName + " ..."

   # Check if the application already exists

   appsList = AdminApp.list().split(java.lang.System.getProperty('line.separator'))

   result = "APP_DOES_NOT_EXIST"

   for installedAppName in appsList:
       if (installedAppName == appName):
           result = "APP_EXISTS"
           app = ""
           break

   if result == 'APP_EXISTS':
       # Need to uninstall so can re-install
       print "Uninstalling " + appName + " ...."
       AdminApp.uninstall(appName)
       AdminConfig.save()
       print "Uninstall completed."
       result = "APP_DOES_NOT_EXIST"

   if (result == "APP_DOES_NOT_EXIST"):
      print "Installing Application " + appName
      print "  Ear file: " + ear

      # Set up deploy options
      appOptions = '[ -appname ' +  appName

      if param['ACS_SECURITY'] == '2' or param['ACS_SECURITY'] == '3':
          appOptions += ' -MapRunAsRolesToUsers [[ fiperuser ' + param['SEE_USER'] + ' "' + param['SEE_USER_PW'] + '" ]] '
          appOptions += ' -MapRolesToUsers [' + \
              '[ fiperuser AppDeploymentOption.No AppDeploymentOption.Yes "" "" AppDeploymentOption.No "" "" ]' + \
              '[ fiperstation AppDeploymentOption.No AppDeploymentOption.Yes "" "" AppDeploymentOption.No "" "" ]'
          if param['ACS_SECURITY'] == '2':
              appOptions += '[ fiperadmin AppDeploymentOption.No AppDeploymentOption.No ' + \
                    param['SEE_USER'] + ' "" AppDeploymentOption.No ' + \
                    'user:defaultWIMFileBasedRealm/uid=' + param['SEE_USER'] + ',o=defaultWIMFileBasedRealm "" ]'
          else:
              # Security level 3 - fiperAdmin needs to be Domain user.  Don't know how to configure that yet.
              #TODO change this to the domain user 'fiperacs', not the local user.
              appOptions += '[ fiperadmin AppDeploymentOption.No AppDeploymentOption.No ' + \
                    param['SEE_USER'] + ' "" AppDeploymentOption.No ' + \
                    'user:defaultWIMFileBasedRealm/uid=' + param['SEE_USER'] + ',o=defaultWIMFileBasedRealm "" ]'
          appOptions += '] '

      if param['DB_TYPE'] == 'ORACLE':
          appOptions += ' -BackendIdSelection [' + \
              '[ SMAFIPlibrary.jar SMAFIPlibrary.jar,META-INF/ejb-jar.xml ORACLE_V9_1 ]' + \
              '[ LabBook SMAFIPlabbook.jar,META-INF/ejb-jar.xml ORACLE_V9_1 ]' + \
              '[ frapiejb SMAFIPfrapi.jar,META-INF/ejb-jar.xml ORACLE_V9_1 ]' + \
              '[ SMAFIPpse.jar SMAFIPpse.jar,META-INF/ejb-jar.xml ORACLE_V9_1 ]]'
     
      # Following sets up shared lib during deploy.  Config does this differently and it works (I think!)
      #    ' -MapSharedLibForMod [[ FiperOra META-INF/application.xml fipercommon ]]] ]'

      appOptions += ']'

      print "  Install options = " + appOptions

      print "Starting application install..."
      app = AdminApp.install(ear, appOptions)
      print "Install completed successfully!"
   else:
      print appName + " already exists!"

   return app


#-----------------------------------------------------------------
# Modify classLoader Mode for application to PARENT_LAST
#
#-----------------------------------------------------------------
def modifyClassloader (appName, target):
    print "Modifying classloader for application " + appName
    # Check to ensure the application exists

    appsList = AdminApp.list().split(java.lang.System.getProperty('line.separator'))
    result = "APP_DOES_NOT_EXIST"

    for installedAppName in appsList:
        if (installedAppName == appName):
            result = "APP_EXISTS"
            break
        #endif
    #endfor

    if (result == "APP_DOES_NOT_EXIST"):
        print "App " + appName + " was not found.  Could not modify classloader"
    else:
        AdminConfig.modify(AdminConfig.showAttribute(AdminConfig.showAttribute(AdminConfig.getid("/Deployment:"+appName+"/"), 'deployedObject'), 'classloader'), [['mode', 'PARENT_LAST']])
        #Stop/Start the app
        print "App " + appName + " modified."
   #endif    
#enddef       

# Modify ESI Cache Size
def modifyWebServerESICache (webServer, cacheSize):
    print "ConfigProcs: modifyWebServerESICache new size is ", cacheSize, "MB for server ", webServer
    servers = AdminConfig.list('Server').split(java.lang.System.getProperty('line.separator'))
    print "Got servers"
    for server in servers:
        print "Server is ", server
        name = AdminConfig.show(server, 'name')
        name = name[len('[name '):len(name)-1]
        print "Server name is ", name
        if (name == webServer):
            print "Found Webserver name is ", name
            component = AdminConfig.show(server, 'components')
            webserver = component[len('[components ['):len(component)-2]
            print "Webserver component is ", webserver
            plugin = AdminConfig.show(webserver, 'pluginProperties')
            plugin = plugin[len('[pluginProperties ['):len(plugin)-2]
            print "Webserver Plugin is ", plugin
            AdminConfig.modify(plugin, [['ESIMaxCacheSize', cacheSize]])
            print "Webserver ESI Cache Size updated."
        #endif
    #endfor
#enddef    
           
#-----------------------------------------------------------------
# Start an installed application
#-----------------------------------------------------------------
def startApp (myApplication, server):
    print "ConfigProcs: startApp ", myApplication, server
    appManager = AdminControl.queryNames("type=ApplicationManager,process=" + server + ",*")
    AdminControl.invoke(appManager, "startApplication", myApplication)

#-----------------------------------------------------------------
# Stop an installed application
#-----------------------------------------------------------------
def stopApp (myApplication, server):
    print "ConfigProcs: stopApp " + myApplication , server
    appManager = AdminControl.queryNames("type=ApplicationManager,process=" + server + ",*")
    AdminControl.invoke(appManager, "stopApplication", myApplication)

#-----------------------------------------------------------------
# createSIBus - Create a new SIBus if one does not exist. Otherwise,
#            return the existing SIBus.
#-----------------------------------------------------------------
def createSIBus (busName, authAlias):
   #    busName    - SIBus name
   #    authAlias  - authentication alias name


   print " "
   print "Creating SIBus "+busName+"..."

   # Check if the SIBus already exists

   SIBus = AdminConfig.getid("/SIBus:" + busName + "/")

   if (SIBus == ""):
      try:
         # VPVP SIBus = AdminTask.createSIBus('[ -bus '+busName+' -protocol InboundBasicMessaging -interEngineAuthAlias '+authAlias+']')
         SIBus = AdminTask.createSIBus('[ -bus '+busName+' -protocol InboundBasicMessaging -secure false -highMessageThreshold 200000 ' + ']')
      except:
         print "WSADMIN EXCEPTION:", sys.exc_type, sys.exc_value
         print "Terminating due to exception!"
      else:
         print busName + "created successfully!"
   else:
      print busName +" already exists!"

   return busName



#-----------------------------------------------------------------
# addSIBusMember - Add the specified server or cluster to the
#            SIBus if it does not already exist. Assumes that the
#            specified SIBus already exists.
#-----------------------------------------------------------------
def addSIBusMember (busName, defaultDS, dsJndi, optArgs):
   #    busName    - SIBus name
   #    defaultDS  - create default DS (true|false)
   #    dsJndi     - jndi name of the datasource (only used if defaultDS = false)
   #    optArgs[0] - cluster name or node name
   #    optArgs[1] - server name

   print " "
   if (len(optArgs) == 1):
      clusterName = optArgs[0]
      print "Adding SIBus member "+clusterName+"..."
   else:
      clusterName = "none"
      nodeName = optArgs[0]
      serverName = optArgs[1]
      print "Adding SIBus member " + nodeName + " - " + serverName + "..."

   print "  Default DataSource:    " + defaultDS
   if (defaultDS == "false"):
      print "  Datasource JNDI Name:  "+dsJndi

   # Check if the bus member already exists

   busMembers = AdminTask.listSIBusMembers('[-bus '+ busName+']')
   print 'before createSIBusMember busMembers=', busMembers

   member = "DOES_NOT_EXIST"
   if (busMembers != ""):
       busMembers = busMembers.split((java.lang.System.getProperty('line.separator')))
       for busMemberName in busMembers:
            if (busMemberName == ""):
                break
            cluster = AdminConfig.showAttribute(busMemberName, 'cluster')
            node = AdminConfig.showAttribute(busMemberName, 'node')
            server = AdminConfig.showAttribute(busMemberName, 'server')
            print "  Bus busMemberName=" + busMemberName + "  cluster=" + clusterName + "  server=" + serverName + " node=" + nodeName
            if (cluster == clusterName or (server == serverName and node == nodeName)):
                member = busMemberName
                print "Found bus busMemberName=" + busMemberName + "   requested name=" + busName
                break

   if (len(optArgs) == 1):
      busMemOpt = '[-bus ' + busName + " -cluster " + clusterName
   else:
      busMemOpt = '[-bus ' + busName + " -node " + nodeName + " -server " + serverName

   if (defaultDS == "false"):
      busMemOpt += ' -datasourceJndiName ' + dsJndi + " -createDefaultDatasource " + defaultDS
   else:
      busMemOpt += ' -fileStore true -logSize 500 -minTemporaryStoreSize 500 -unlimitedTemporaryStoreSize true -minPermanentStoreSize 500 -unlimitedPermanentStoreSize true'

   busMemOpt += ' ]'

   if (member == "DOES_NOT_EXIST"):
      try:
         # addSIBusMember is SUPPOSED to return the bus member name.  It actually returns an empty string.
         # So I have to look up the bus member name afterwords.  I'm ASSUMING there is only one.
         AdminTask.addSIBusMember(busMemOpt)
         member = AdminTask.listSIBusMembers('[-bus '+ busName+']')
         member = member.strip()
         # actually, member is an ID, need string form of bus member.
         mm=AdminConfig.showAttribute(member, 'target')
         mm2=mm[1:-1]       # strip off square brackets
         memberName = AdminConfig.showAttribute(mm2, 'engineName')
      except:
         print "addSIBusMember EXCEPTION: ", sys.exc_type, sys.exc_value
         print "Terminating due to exception!"
      else:
         print "SIBus member added successfully!   member=" + member + ";"
   else:
      print "Bus member already exists!"

   return memberName

#-----------------------------------------------------------------
# createSIBDestination - Create a new SIB Destination if one with the same
#            name does not exist on the specified SIBus. Otherwise,
#            return the existing Destination.
#-----------------------------------------------------------------
def createSIBDestination (SIBus, destName, destType, optArgs):
   #    SIBus       - SIBus name
   #    destName    - destination name
   #    destType    - destination type
   #    #reliability - reliability
   #    optArgs[0]  - cluster name or node name
   #    optArgs[1]  - server name


   if (len(optArgs) == 1):
      clusterName = optArgs[0]
   else:
      nodeName = optArgs[0]
      serverName = optArgs[1]

   print " "
   print "Creating SIB Destination "+destName+"..."

   # Check if the SIB Destination already exists

   sibDestList = AdminTask.listSIBDestinations('[-bus '+ SIBus+']')

   dest = "DOES_NOT_EXIST"

   if (sibDestList != ""):
       sibDestList = sibDestList.split((java.lang.System.getProperty('line.separator')))
       for sibDest in sibDestList:
          ident = AdminConfig.showAttribute(sibDest, 'identifier')
          if (ident == destName):
             dest = sibDest
             break

   if (dest == "DOES_NOT_EXIST"):
      print "  Destination Name:  " + destName
      print "  Destination Type:  " + destType
      print "  Reliability:       " + reliability
      if (destType == "Queue"):
         if (len(optArgs) == 1):
            print "  Cluster Name:      " + clusterName
         else:
            print "  Node Name:         " + nodeName
            print "  Server Name:       " + serverName

      sibDestOpt = '[-bus ' + SIBus + " -name " + destName + " -type " + destType 
      		# + " -reliability " + reliability
      if (destType == "Queue" and len(optArgs) == 1):
         sibDestOpt += " -cluster " + clusterName
      elif (destType == "Queue"):
         sibDestOpt += " -node " + nodeName + " -server " + serverName

      sibDestOpt += ' ]'

      try:
         dest = AdminTask.createSIBDestination(sibDestOpt)
      except:
         print "WSADMIN EXCEPTION: ", sys.exc_type, sys.exc_value
         print "Terminating due to exception!"
      else:
         print destName + " created successfully!"
   else:
      print destName + " already exists!"

   return dest



#-----------------------------------------------------------------
# createJMSConnectionFactory - Create a new JMS Connection Factory
#            if one with the same name does not exist on the SIBus.
#            Otherwise, return the existing Connection Factory.
#-----------------------------------------------------------------
def createJMSConnectionFactory (SIBus, cfName, cfType, jndiName, authAlias, scope, providerEndPoint, busMemberName):
   # Create JMS Connection Factory
   #    SIBus      - SIBus name
   #    cfName     - connection factory name
   #    cfType     - connection factory type
   #    jndiName   - connection factory jndi name
   #    authAlias  - authentication alias name
   #    scope      - scope
   #    providerEndPoint - provider endpoint (host:port:BootstrapBasicMessaging

   print " "
   print "Creating JMS "+cfType+ " Connection Factory "+cfName+ "..."
   print "busMemberName=" + busMemberName + ";"

   # Check if the connection factory already exists

   if (cfType == ""):
      cfList = AdminTask.listSIBJMSConnectionFactories(scope)
   else:
      cfList = AdminTask.listSIBJMSConnectionFactories(scope, '[ -type '+ cfType + ']')
   print "Factories = " + cfList
   connectionFactory = "DOES_NOT_EXIST"

   if (cfList != ""):
       cfList = cfList.split((java.lang.System.getProperty('line.separator')))
       for cfDest in cfList:
          if (cfDest == cfName):
             connectionFactory = cfDest
             break

   if (connectionFactory == "DOES_NOT_EXIST"):
      print "  Connection Factory Name:  "+cfName
      print "  Connection Factory Type:  "+cfType
      print "  JNDI Name:                "+jndiName

      cfDestOpt = '[ -name ' + cfName + \
              ' -providerEndPoints ' + providerEndPoint + \
              ' -durableSubscriptionHome ' + busMemberName + \
              ' -jndiName ' + jndiName + \
			  ' -busName ' + SIBus + \
              ' -containerAuthAlias ' + authAlias + \
              ' -xaRecoveryAuthAlias ' + authAlias + \
              ' -persistentMapping ' + 'AssuredPersistent' + \
              ' -targetTransportChain ' + 'InboundBasicMessaging' + \
              ' -clientID ' + 'Fiper' + \
              ' ]' 
               # " -type " + cfType +
      try:
         print "about to createSIBJMSConnectionFactory"
         #print "     scope=", scope
         #print "     args=", cfDestOpt
         connectionFactory = AdminTask.createSIBJMSConnectionFactory(scope, cfDestOpt)
         # Update the connection pool values
         cpool = AdminConfig.showAttribute(connectionFactory, 'connectionPool')
         print "Connection pool ID =", cpool
         AdminConfig.modify(cpool, [['maxConnections', '100']])
         AdminConfig.modify(cpool, [['minConnections', '25']])
         AdminConfig.modify(cpool, [['unusedTimeout', '180']])
         
      except:
         print "WSADMIN EXCEPTION: ", sys.exc_type, sys.exc_value
         print "Terminating due to exception!"
      else:
         print cfName+" created successfully!"
   else:
      print cfName +"already exists!"

   return connectionFactory


#-----------------------------------------------------------------
# createJMSQueue - Create a new JMS Queue if one with the same
#            name does not exist at the specified scope. Otherwise,
#            return the existing JMS Queue.
#-----------------------------------------------------------------
def createJMSQueue (busName, qName, jndiName, SIBDest, delMode, scope):
   #    busName  - JMS bus name
   #    qName    - queue name
   #    jndiName - queue jndi name
   #    SIBDest  - SIB destination
   #    delMode  - delivery mode
   #    scope    - scope

   print " "
   print "Creating JMS Queue " + qName +"..."

   # Check if the queue already exists
   qList = AdminTask.listSIBJMSQueues(scope)

   queue = "DOES_NOT_EXIST"

   if (qList != ""):
       qList = qList.split((java.lang.System.getProperty('line.separator')))
       for qDest in qList:
          if (qDest == qName):
             queue = qDest
             break

   if (queue == "DOES_NOT_EXIST"):
      print "  Queue Name:       " + qName
      print "  JNDI Name:        " + jndiName
      print "  SIB Destination:  " + SIBDest
      print "  Delivery Mode:    " + delMode

      qDestOpt = '[-name ' + qName + " -jndiName " + jndiName + " -queueName " + SIBDest + " -deliveryMode " + delMode + " -busName " + busName + ' ]'
      #print qDestOpt
      try:
         queue = AdminTask.createSIBJMSQueue(scope, qDestOpt)
      except:
         print "WSADMIN EXCEPTION: ", sys.exc_type, sys.exc_value
         print "Terminating due to exception!"
      else:
         print qName +" created successfully!"
   else:
      print qName +" already exists!"

   return queue

#-----------------------------------------------------------------
# createJMSTopic - Create a new JMS Topic if one with the same
#            name does not exist at the specified scope. Otherwise,
#            return the existing JMS Topic.
#-----------------------------------------------------------------
def createJMSTopic(name, tName, jndiName, busName, scope, persistent):
   #    name     - name of this entry (differs from topic name by capitalization)
   #    tName    - topic name
   #    jndiName - topic jndi name
   #    busName  - bus name
   #    scope    - scope
   #    persistent - 1 to make bus persistent, 0 to not do so

   print " "
   print "Creating JMS Topic " + name + "..."

   # Check if the topic already exists

   tList = AdminTask.listSIBJMSTopics(scope)

   topic = "DOES_NOT_EXIST"

   if (tList != ""):
       tList = tList.split((java.lang.System.getProperty('line.separator')))
       for tDest in tList:
          if (tDest == tName):
             topic = tDest
             break

   if (topic == "DOES_NOT_EXIST"):
      print "  Name:           " + name
      print "  Topic Name:     " + tName
      print "  JNDI Name:      " + jndiName
      print "  Bus Name:       " + busName

      if persistent:
          tDestOpt = '[-name ' + name + " -jndiName " + jndiName + " -topicName " + tName + " -busName " + busName  + ' -deliveryMode ' + 'Persistent' + ' ]'
      else:
          tDestOpt = '[-name ' + name + " -jndiName " + jndiName + " -topicName " + tName + " -busName " + busName  + ' ]'

      try:
         topic = AdminTask.createSIBJMSTopic(scope, tDestOpt)
      except:
         print "WSADMIN EXCEPTION: ", sys.exc_type, sys.exc_value
         print "Terminating due to exception!"
      else:
         print name +" created successfully!"
   else:
      print name + " already exists!"

   return topic


#-----------------------------------------------------------------
# createMDBActivationSpec - Create a new MDB Activation Spec if one
#            with the same name does not exist at the specified
#            scope. Otherwise, return the existing Activation Spec.
#-----------------------------------------------------------------
def createMDBActivationSpec(mdbName, jndiName, SIBus, JMSDestJndi, destType, maxConcurrent, scope, authalias):
   #    mdbName     - MDB name
   #    jndiName    - activation spec jndi name
   #    SIBus       - SIBus name
   #    JMSDestJndi - JMS destination JNDI name
   #    destType    - destination type
   #    maxConcurrent - Maximum concurrent messages active
   #    scope       - scope
   #    authalias   - authentication alias for security

   print " "
   print "Creating MDB Activation Spec " + mdbName + "..."

   # Check if the activation spec already exists

   asList = AdminTask.listSIBJMSActivationSpecs(scope)

   mdb = "DOES_NOT_EXIST"

   if (asList != ""):
       asList = asList.split((java.lang.System.getProperty('line.separator')))
       for asDest in asList:
          if (asDest == mdbName):
             mdb = asDest
             break

   asDestOpt = '[-name ' + mdbName + \
                   " -jndiName " + jndiName + \
                   " -busName " + SIBus + \
                   " -destinationJndiName " + JMSDestJndi + \
                   " -destinationType " + destType +  \
                   " -maxConcurrency " + str(maxConcurrent) +  \
                   " -maxBatchSize " + "1" + \
                   " -authenticationAlias " + authalias + ' ]'
   if (mdb == "DOES_NOT_EXIST"):
      print "  MDB Activation Spec Name:   " + mdbName
      print "  JNDI Name:                  " + jndiName
      print "  JMS Destination JNDI Name:  " + JMSDestJndi
      print "  Destination Type:           " + destType

      try:
         mdb = AdminTask.createSIBJMSActivationSpec(scope, asDestOpt)
      except:
         print "WSADMIN EXCEPTION:", sys.exc_type, sys.exc_value
         print "Terminating due to exception!"
      else:
         print mdbName+" created successfully!"
   else:
      print mdbName+" already exists!"

   return mdb

#-----------------------------------------------------------------
# createURLResource - Create a new MDB Activation Spec if one
#            with the same name does not exist at the specified
#            scope. Otherwise, return the existing Activation Spec.
#-----------------------------------------------------------------

def createURLResource(urlProvider, urlName, jndiName, url):

    print " "
    print "Creating URL Resource " + urlName + "..."

    nameAttr = ["name", urlName]
    jndiNameAttr = ["jndiName", jndiName]
    specAttr = ["spec", url]
    attrs = []
    attrs.append(nameAttr)
    attrs.append(jndiNameAttr)
    attrs.append(specAttr)

    print " "
    print "ConfigProcs: AdminConfig create URL" , urlProvider , attrs
    print " "

    AdminConfig.create("URL", urlProvider, attrs)

#-----------------------------------------------------------------
# createURLResource - Create a new MDB Activation Spec if one
#            with the same name does not exist at the specified
#            scope. Otherwise, return the existing Activation Spec.
#-----------------------------------------------------------------

def createMailSession(mailProvider, mailName, jndiName, smtpRelay, fromAddress):

    print " "
    print "Creating Mail Session " + mailName + "..."

    nameAttr = ["name", mailName]
    jndiNameAttr = ["jndiName", jndiName]
    mailTransportHost = ['mailTransportHost', smtpRelay]
    mailFrom = ['mailFrom', fromAddress]
    attrs = []
    attrs.append(nameAttr)
    attrs.append(jndiNameAttr)
    attrs.append(mailTransportHost)
    attrs.append(mailFrom)

    print " "
    print "ConfigProcs: AdminConfig create MailSession" , mailProvider , attrs
    print " "

    AdminConfig.create("MailSession", mailProvider, attrs)

#-----------------------------------------------------------------
# removeSIBDestinations - Remove PM specific SIBDestinations
#-----------------------------------------------------------------
def  removeSIBDestinations(node, uploadTopicSpace, internalTopicSpace, uploadSIBDest):
    #Remove SIBDestinations
    objects = (AdminTask.listSIBDestinations('-bus ' + node)).split(java.lang.System.getProperty('line.separator'))
    for object in objects:
        print "SIBDestination = " + object
        objectParm = AdminConfig.show(object, 'identifier')
        parm = objectParm[len('identifier')+2:len(objectParm)-1]
        if parm[0] == "\"" and parm[len(parm)-1] == "\"":
            parm = parm[1:len(parm)-1]
            print "new parm = " + parm
        print "Identifier = " + parm
        if parm == uploadTopicSpace or parm == internalTopicSpace or parm == uploadSIBDest:
            print "Removing SIBDestination = " + parm
            AdminTask.deleteSIBDestination("[-bus " + node + " -name " + parm + "]")
        #endif
    #endfor
#enddef

#-----------------------------------------------------------------
# removeSIBJMSConnectionFactories - Remove PM specific SIBJMSConnectionFactories
#-----------------------------------------------------------------
def  removeSIBJMSConnectionFactories(nodeScope, uploadJMSQCF, streamerJMSTCF, internalJMSTCF):
    #Remove SIBJMSConnectionFactories
    objects = (AdminTask.listSIBJMSConnectionFactories(nodeScope, '[-type all]')).split(java.lang.System.getProperty('line.separator'))
    for object in objects:
        print "SIBJMSConnectionFactory = " + object
        objectParm = AdminConfig.show(object, 'name')
        parm = objectParm[len('name')+2:len(objectParm)-1]
        if parm[0] == "\"" and parm[len(parm)-1] == "\"":
            parm = parm[1:len(parm)-1]
            print "new parm = " + parm
        print "SIBJMSConnectionFactory name = " + parm
        if parm == uploadJMSQCF or parm == streamerJMSTCF or parm == internalJMSTCF:
            print "Removing SIBJMSConnectionFactory = " + parm
            AdminTask.deleteSIBJMSConnectionFactory(object)
        #endif
    #endfor
#enddef

#-----------------------------------------------------------------
# removeSIBJMSQueues - Remove PM specific SIBJMSQueues
#-----------------------------------------------------------------
def removeSIBJMSQueues(nodeScope, uploadQueue):
    #Remove SIBJMSQueues
    objects = (AdminTask.listSIBJMSQueues(nodeScope)).split(java.lang.System.getProperty('line.separator'))
    for object in objects:
        print "SIBJMSQueue = " + object
        objectParm = AdminConfig.show(object, 'name')
        parm = objectParm[len('name')+2:len(objectParm)-1]
        if parm[0] == "\"" and parm[len(parm)-1] == "\"":
            parm = parm[1:len(parm)-1]
            print "new parm = " + parm
        print "SIBJMSQueue name = " + parm
        if parm == uploadQueue:
            print "Removing SIBJMSQueue = " + parm
            AdminTask.deleteSIBJMSQueue(object)
        #endif
    #endfor
#enddef

#-----------------------------------------------------------------
# removeSIBJMSQueues - Remove PM specific SIBJMSQueues
#-----------------------------------------------------------------
def removeSIBJMSTopics(nodeScope, streamerTopic, internalTopic):
    #Remove SIBJMSTopics
    objects = (AdminTask.listSIBJMSTopics(nodeScope)).split(java.lang.System.getProperty('line.separator'))
    for object in objects:
        print "SIBJMSTopics = " + object
        objectParm = AdminConfig.show(object, 'name')
        parm = objectParm[len('name')+2:len(objectParm)-1]
        if parm[0] == "\"" and parm[len(parm)-1] == "\"":
            parm = parm[1:len(parm)-1]
            print "new parm = " + parm
        print "SIBJMSTopics name = " + parm
        if parm == streamerTopic or parm == internalTopic:
            print "Removing SIBJMSTopic = " + parm
            AdminTask.deleteSIBJMSTopic(object)
        #endif
    #endfor
#enddef

#-----------------------------------------------------------------
# removeSIBJMSActivationSpecs - Remove PM specific SIBJMSActivationSpecs
#-----------------------------------------------------------------
def removeSIBJMSActivationSpecs(nodeScope, uploadMDB, configMDB):
    #Remove SIBJMSActivationSpecs
    objects = (AdminTask.listSIBJMSActivationSpecs(nodeScope)).split(java.lang.System.getProperty('line.separator'))
    for object in objects:
        print "SIBJMSActivationSpec = " + object
        objectParm = AdminConfig.show(object, 'name')
        parm = objectParm[len('name')+2:len(objectParm)-1]
        if parm[0] == "\"" and parm[len(parm)-1] == "\"":
            parm = parm[1:len(parm)-1]
            print "new parm = " + parm
        print "SIBJMSActivationSpec name = " + parm
        if parm == uploadMDB or parm == configMDB:
            print "Removing SIBJMSActivationSpec = " + parm
            AdminTask.deleteSIBJMSActivationSpec(object)
        #endif
    #endfor
#enddef

#-----------------------------------------------------------------
# removeSIBBusMembers - Remove PM specific SIBBusMembers
#-----------------------------------------------------------------
def removeSIBBusMembers(node, WASserverName):
    #Remove SIBBusMembers
    objects = (AdminTask.listSIBusMembers('[-bus '+ node +']')).split(java.lang.System.getProperty('line.separator'))
    for object in objects:
        print "SIBusMember = " + object
        print "Removing SIBusMember = " + object
        AdminTask.removeSIBusMember('[-bus ' + node + ' -node ' + node + ' -server ' +WASserverName+']')
    #endfor
#enddef

#-----------------------------------------------------------------
# removeSIBBuses - Remove PM specific SIBBuses
#-----------------------------------------------------------------
def removeSIBBuses(node, WASJMSauthAliasName):
    #Remove SIBBuses
    objects = (AdminTask.listSIBuses()).split(java.lang.System.getProperty('line.separator'))
    for object in objects:
        print "SIBus = " + object
        objectParm = AdminConfig.show(object, 'interEngineAuthAlias')
        parm = objectParm[len('interEngineAuthAlias')+2:len(objectParm)-1]
        if parm[0] == "\"" and parm[len(parm)-1] == "\"":
            parm = parm[1:len(parm)-1]
            print "new parm = " + parm
        print "SIBus interEngineAuthAlias = " + parm
        if parm == WASJMSauthAliasName:
            print "Removing SIBus = " + object
            AdminTask.deleteSIBus('[-bus ' + node + ']')
        #endif
    #endfor
#enddef

#-----------------------------------------------------------------
# removeMailSessions - Remove PM specific removeMailSessions
#-----------------------------------------------------------------
def removeMailSessions(mailName):
    #Remove MailSessions
    objects = (AdminConfig.list('MailSession')).split(java.lang.System.getProperty('line.separator'))
    for object in objects:
        print "MailSession = " + object
        objectParm = AdminConfig.show(object, 'name')
        parm = objectParm[len('name')+2:len(objectParm)-1] 
        if parm[0] == "\"" and parm[len(parm)-1] == "\"":
            parm = parm[1:len(parm)-1]
            print "new parm = " + parm
        print "MailSession name = " + parm
        if parm == mailName:
            print "Removing MailSession = " + object
            AdminConfig.remove(object)
        #endif
    #endfor
#enddef

#-----------------------------------------------------------------
# removeURLResources - Remove PM specific URLResources
#-----------------------------------------------------------------
def removeURLResources(urlPMConfigName, urlPMFileName, urlPMLicName):
    #Remove URLResources
    objects = (AdminConfig.list('URL')).split(java.lang.System.getProperty('line.separator'))
    for object in objects:
        print "URLResource = " + object
        objectParm = AdminConfig.show(object, 'name')
        parm = objectParm[len('name')+2:len(objectParm)-1]
        if parm[0] == "\"" and parm[len(parm)-1] == "\"":
            parm = parm[1:len(parm)-1]
            print "new parm = " + parm
        if parm == urlPMConfigName or parm == urlPMFileName or parm == urlPMLicName:
            print "Removing URLResource = " + object
            AdminConfig.remove(object)
        #endif
    #endfor
#enddef

#-----------------------------------------------------------------
# #removeDataSources - Remove PM specific DataSources
#-----------------------------------------------------------------
def removeDataSources(WASdatasourceName):
    #Remove DataSources
    objects = (AdminConfig.list('DataSource')).split(java.lang.System.getProperty('line.separator'))
    for object in objects:
        print "DataSource = " + object
        objectParm = AdminConfig.show(object, 'name')
        parm = objectParm[len('name')+2:len(objectParm)-1]
        if parm[0] == "\"" and parm[len(parm)-1] == "\"":
            parm = parm[1:len(parm)-1]
            print "new parm = " + parm
        print "DataSource name = " + parm
        if parm == WASdatasourceName:
            print "Removing DataSource = " + object
            AdminConfig.remove(object)
        #endif
    #endfor
#enddef

#-----------------------------------------------------------------
# removeJDBCProviders - Remove PM specific JDBCProviders
#-----------------------------------------------------------------
def removeJDBCProviders(WASJDBCProviderName):
    #Remove JDBCProviders
    objects = (AdminConfig.list('JDBCProvider')).split(java.lang.System.getProperty('line.separator'))
    for object in objects:
        print "JDBCProvider = " + object
        objectParm = AdminConfig.show(object, 'name')
        parm = objectParm[len('name')+2:len(objectParm)-1]
        if parm[0] == "\"" and parm[len(parm)-1] == "\"":
            parm = parm[1:len(parm)-1]
            print "new parm = " + parm
        print "JDBCProvider name = " + parm
        if parm == WASJDBCProviderName:
            print "Removing JDBCProvider = " + object
            AdminConfig.remove(object)
        #endif
    #endfor
#enddef

#-----------------------------------------------------------------
# removeCMPConnectorFactories - Remove PM specific CMPConnectorFactories
#-----------------------------------------------------------------
def removeCMPConnectorFactories(WASdatasourceName):
    #Remove CMPConnectorFactories
    objects = (AdminConfig.list('CMPConnectorFactory')).split(java.lang.System.getProperty('line.separator'))
    for object in objects:
        print "CMPConnectorFactory = " + object
        objectParm = AdminConfig.show(object, 'name')
        parm = objectParm[len('name')+2:len(objectParm)-1]
        if parm[0] == "\"" and parm[len(parm)-1] == "\"":
            parm = parm[1:len(parm)-1]
            print "new parm = " + parm
        print "CMPConnectorFactory name = " + parm
        if parm == WASdatasourceName+"_CF":
            print "Removing CMPConnectorFactory = " + object
            AdminConfig.remove(object)
        #endif
    #endfor
#enddef

#-----------------------------------------------------------------
# modifyVariableMapEntries - Modify PM specific VariableMapEntries
#-----------------------------------------------------------------
def modifyVariableMapEntries(node):
    #Modify VariableMapEntries for DB2UNIVERSAL_JDBC_DRIVER_PATH and UNIVERSAL_JDBC_DRIVER_PATH
    varMap = AdminConfig.getid('/Node:'+node+'/VariableMap:/')
    print "Original VarMap = " + AdminConfig.showall(varMap)
    objects = (AdminConfig.show(varMap,'entries')).split(java.lang.System.getProperty('line.separator'))
    attrs = []
    for object in objects:
        modifiedObject = object[len("[entries \"["):len(object)-len("]\"]")].split(' ')
        for subObject in modifiedObject:
            objectParm = AdminConfig.show(subObject, 'symbolicName')
            parm = objectParm[len('symbolicName')+2:len(objectParm)-1]
            if parm == 'DB2UNIVERSAL_JDBC_DRIVER_PATH' or parm == 'UNIVERSAL_JDBC_DRIVER_PATH':
                print "Removing VariableMap Entry = " + subObject
                AdminConfig.remove(subObject)
                print "create a new variable for " + parm + "in the variable map" 
                nameAttr = ["symbolicName", parm] 
                valAttr = ["value", ''] 
                attrs.append(nameAttr)
                attrs.append(valAttr)
            #endif
        #endFor
        AdminConfig.modify(varMap,[['entries',[attrs]]])
        print "Updated VarMap = " + AdminConfig.showall(varMap)
    #endfor
#enddef

#-----------------------------------------------------------------
# removeJASSDataAuthObjects - Remove PM specific JASSDataAuthObjects
#-----------------------------------------------------------------
def removeJASSDataAuthObjects(WASJMSauthAliasName, WASauthAliasName):
    #Remove JASSDataAuth objects
    objects = (AdminConfig.list('JAASAuthData')).split(java.lang.System.getProperty('line.separator'))
    for object in objects:
        print "JASSDataAuth = " + object
        objectParm = AdminConfig.show(object, 'alias')
        parm = objectParm[len('alias')+2:len(objectParm)-1]
        if parm[0] == "\"" and parm[len(parm)-1] == "\"":
            parm = parm[1:len(parm)-1]
            print "new parm = " + parm
        print "JASSDataAuth alias = " + parm
        if parm == WASJMSauthAliasName or parm == WASauthAliasName:
            print "Removing JASSDataAuth = " + object
            AdminConfig.remove(object)
        #endif
    #endfor
#enddef

#-----------------------------------------------------------------
# removeWebServerESICache - Reset EISCache to default max setting
#-----------------------------------------------------------------
def removeWebServerESICache(webServer):
    print "ConfigProcs: removeWebServerESICache for webserver ", webServer
    servers = AdminConfig.list('Server').split(java.lang.System.getProperty('line.separator'))
    print "Got servers"
    for server in servers:
        print "Server is ", server
        name = AdminConfig.show(server, 'name')
        name = name[len('[name '):len(name)-1]
        print "Server name is ", name
        if (name == webServer):
            print "Found Webserver name is ", name
            component = AdminConfig.show(server, 'components')
            webserver = component[len('[components ['):len(component)-2]
            print "Webserver component is ", webserver
            plugin = AdminConfig.show(webserver, 'pluginProperties')
            plugin = plugin[len('[pluginProperties ['):len(plugin)-2]
            print "Webserver Plugin is ", plugin
            AdminConfig.modify(plugin, [['ESIMaxCacheSize', 1024]])
            print "Webserver ESI Cache Size returned to default max size."
        #endif
#enddef

#-----------------------------------------------------------------
# stopUninstallApps - Stop and remove  PM specific apps
#-----------------------------------------------------------------
def stopUninstallApps(WASclientAppName, WASappName):
    #stop and remove Apps
    apps = (AdminApp.list()).split(java.lang.System.getProperty('line.seperator'))
    for app in apps:
        print "Application = " + app
        if app == WASclientAppName or app == WASappName:
            try:
                print "Stopping app " + app
                appMgr = AdminControl.queryNames('type=ApplicationManager,process='+WASserverName+',*')
                AdminControl.invoke(appMgr,'stopApplication', app)
                print "App Stopped, uninstalling app " + app
                AdminApp.uninstall(app)
                print "App uninstalled"
            except:
                print "Exception Stopping and uninstalling app " + app, sys.exc_type, sys.exc_value

        #endif
    #endfor
#enddef
