Thursday, 26 January 2017

WLST Script to change the BPEL properties , EDN status , Audit level and create partitions..

WLST Script to change the BPEL properties , EDN status , Audit level and create partitions..

Step 1) Create a property file with AdminServer details . Let us say the property filename is : dev.properties.

admin.url=t3://AdminServerName:7001
admin.soaurl=t3://SOAServerName:8001
admin.username=Weblogic
admin.password=Weblogic1

Step 2) Create a WLST script with below entries . let us say , script name is :  fmwBPELMbean.py

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.management.Attribute;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.Query;
import javax.management.QueryExp;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

from java.io import FileInputStream
from java.util import Properties
from org.apache.log4j import *
import javax.management.openmbean.CompositeDataSupport;

if __name__ == '__main__':
    from wlstModule import *



def loginToAdmin(config):
        adminuser = config.get("admin.username")
   
   adminpwd = config.get("admin.password")
        adminurl = config.get("admin.soaurl")
        logger.info('Logging into SOA URL:"+adminurl')
        connect(adminuser,adminpwd,adminurl)

def partitionExists(part):
        foldermbean = sca_getFolderMBean();
        try:
                folders = mbs.getAttribute(foldermbean, "Folders")
                for folder in folders:
                        if folder.getName() == part:
                                return True
                return False
        except Exception, detail:
                print 'Exception:', detail

def createSOAPartition(config):
        loginToSOA(config)
        if not partitionExists('Partition1'):
                sca_createPartition ('Partition1')
        if not partitionExists('Partition2'):
                sca_createPartition ('Partition2')
        if not partitionExists('Partition3'):
                sca_createPartition ('Partition3')
        if not partitionExists('Partition4'):
                sca_createPartition ('Partition4')

        sca_listPartitions()

def changelog(config):
        #requires admin login
        loginToAdmin(config)
        domainRuntime()
        SOAInfraConfigobj = ObjectName('oracle.as.soainfra.config:Location=wls_soa1,name=soa-infra,type=SoaInfraConfig,Application=soa-infra')

        print 'Before: AuditLevel at SOAConfig (Global)~', mbs.getAttribute(SOAInfraConfigobj,'AuditLevel')

        mbs.setAttribute(SOAInfraConfigobj,Attribute("AuditLevel","Off"))
        print 'After : AuditLevel at SOAConfig (Global)~', mbs.getAttribute(SOAInfraConfigobj,'AuditLevel')


def changeEDN(config):
        custom()
        cd('oracle.as.soainfra.config/oracle.as.soainfra.config:name=edn,type=EDNConfig,Application=soa-infra')
        pausedval=get('Paused')
        logger.info('EDN Paused value = ' + str(pausedval))
        sca_disableEventsDelivery()
        logger.info('EDN Paused value = ' + str(pausedval))

def changeBPEL(config):
        logger.info('Processing BPEL')
        BPELConfigobj = ObjectName('oracle.as.soainfra.config:Location=wls_soa1,name=bpel,type=BPELConfig,Application=soa-infra')

        print 'Before: AuditLevel at BPELConfig (Global)~', mbs.getAttribute(BPELConfigobj,'AuditLevel')
        print 'Before: DisableSensors at BPELConfig (Global)~', mbs.getAttribute(BPELConfigobj,'DisableSensors')
        print 'Before: AuditStorePolicy at BPELConfig (Global)~', mbs.getAttribute(BPELConfigobj,'AuditStorePolicy')
        print 'Before: RecurringMaxMessageRaiseSize at BPELConfig (Global)~', mbs.getAttribute(BPELConfigobj,'RecurringMaxMessageRaiseSize')
        print 'Before: StartupMaxMessageRaiseSize at BPELConfig (Global)~', mbs.getAttribute(BPELConfigobj,'StartupMaxMessageRaiseSize')

        # instructions say None.  off appears to be valid, not None
        mbs.setAttribute(BPELConfigobj,Attribute('AuditLevel','off'))

        mbs.setAttribute(BPELConfigobj,Attribute('DisableSensors',1))
        mbs.setAttribute(BPELConfigobj,Attribute('AuditStorePolicy','async'))
        mbs.setAttribute(BPELConfigobj,Attribute('RecurringMaxMessageRaiseSize',0))
        mbs.setAttribute(BPELConfigobj,Attribute('StartupMaxMessageRaiseSize',0))

        print 'After : AuditLevel at BPELConfig (Global)~', mbs.getAttribute(BPELConfigobj,'AuditLevel')
        print 'After : DisableSensors at BPELConfig (Global)~', mbs.getAttribute(BPELConfigobj,'DisableSensors')
        print 'After : AuditStorePolicy at BPELConfig (Global)~', mbs.getAttribute(BPELConfigobj,'AuditStorePolicy')
        print 'After : RecurringMaxMessageRaiseSize at BPELConfig (Global)~', mbs.getAttribute(BPELConfigobj,'RecurringMaxMessageRaiseSize')
        print 'After : StartupmaxMessageRaiseSize at BPELConfig (Global)~', mbs.getAttribute(BPELConfigobj,'RecurringMaxMessageRaiseSize')

def changeBPELRecovery(config):
        logger.info('Processing BPEL')
        BPELConfigobj = ObjectName('oracle.as.soainfra.config:Location=wls_soa1,name=bpel,type=BPELConfig,Application=soa-infra')
        rec_config_obj  = mbs.getAttribute(BPELConfigobj, 'RecoveryConfig')
        rec_recurrr_obj = rec_config_obj.get('RecurringScheduleConfig')
        rec_startup_obj = rec_config_obj.get('StartupScheduleConfig')
        rec_cluster_obj = rec_config_obj.get('ClusterConfig')

        #Update configs
        new_startup_obj = setStartupConfig(rec_startup_obj,BPELConfigobj)
        new_recur_obj = setRecurringConfig(rec_recurrr_obj,BPELConfigobj)
        new_clust_obj = setClusterConfig(rec_cluster_obj,BPELConfigobj)

        #Create HashMap for Assignment
   
   pyMap = { "ClusterConfig":new_clust_obj, "RecurringScheduleConfig":new_recur_obj, "StartupScheduleConfig":new_startup_obj }
        javaMap = java.util.HashMap()
        for k in pyMap.keys():
                javaMap[k] = pyMap[k]

        new_rec_config_obj = CompositeDataSupport(rec_config_obj.getCompositeType(), javaMap)

        #javax.management.Attribute
        SOAattribute = Attribute('RecoveryConfig', new_rec_config_obj)

        mbs.setAttribute(BPELConfigobj, SOAattribute)

def setRecurringConfig(recur_obj,BPELMBeanobj):
        print ' in Recurring Config'
        cnt = 0
        keySet = recur_obj.getCompositeType().keySet()

        keys = keySet.toArray()
        keyitems = [ key for key in keys ]
        values = recur_obj.getAll(keyitems)
        for key in keys:
                print 'Processing key:',key

                if key == 'maxMessageRaiseSize':

                        print 'bpel current RecurringScheduleConfig:maxMessageRaiseSize ' + key + ' to value ' + str(values[cnt])
                        values [cnt] = Integer(0)
                        print 'bpel set RecurringScheduleConfig:maxMessageRaiseSize ' + key + ' to value ' + str(values[cnt])
                if key == 'stopWindowTime':
                        print 'bpel set RecurringScheduleConfig:stopWindowTime ' + key + ' to value ' + str(values[cnt])
                        values [cnt] = '00:00'
                        print 'bpel set RecurringScheduleConfig:stopWindowTime ' + key + ' to value ' + str(values[cnt])
                if key == 'startWindowTime':
                        print 'bpel set RecurringScheduleConfig:startWindowTime ' + key + ' to value ' + str(values[cnt])
                        values [cnt] = '00:00'
                        print 'bpel set RecurringScheduleConfig:startWindowTime ' + key + ' to value ' + str(values[cnt])
                if key == 'subsequentTriggerDelay':
                        print 'bpel set RecurringScheduleConfig:subsequentTriggerDelay ' + key + ' to value ' + str(values[cnt])
                        values [cnt] = Long(0)
                        print 'bpel set RecurringScheduleConfig:subsequentTriggerDelay ' + key + ' to value ' + str(values[cnt])
                if key == 'threshHoldTimeInMinutes':
                        print 'bpel set RecurringScheduleConfig:threshHoldTimeInMinutes ' + key + ' to value ' + str(values[cnt])
                        values [cnt] = Integer(0)
                        print 'bpel set RecurringScheduleConfig:threshHoldTimeInMinutes ' + key + ' to value ' + str(values[cnt])
                cnt = cnt + 1
        new_obj = CompositeDataSupport(recur_obj.getCompositeType(), keyitems, values)
        return new_obj


def setClusterConfig(cluster_obj,BPELMBeanobj):
        print ' in ClusterConfig '
        cnt = 0
        keySet = cluster_obj.getCompositeType().keySet()
        keys = keySet.toArray()
        keyitems = [ key for key in keys ]
        values = cluster_obj.getAll(keyitems)
        for key in keys:
                print 'Processing key:',key
                cnt = cnt + 1
        new_obj = CompositeDataSupport(cluster_obj.getCompositeType(), keyitems, values)

      return new_obj


def setStartupConfig(startup_obj,BPELMBeanobj):
        print ' in Startup Config'
        cnt = 0
        keySet = startup_obj.getCompositeType().keySet()

        print 'keySet:',keySet
        keys = keySet.toArray()
        print 'keys:',keys
        keyitems = [ key for key in keys ]
        print 'keyitems:',keyitems
        values = startup_obj.getAll(keyitems)
        print 'keySet',keySet
        for key in keys:
                print key
                if key == 'maxMessageRaiseSize':
                        print 'bpel current StartupScheduleConfig:maxMessageRaiseSize ' + key + ' to value ' + str(values[cnt])
                        values [cnt] = Integer(0)
                        print 'bpel set StartupScheduleConfig:maxMessageRaiseSize ' + key + ' to value ' + str(values[cnt])
                if key == 'startupRecoveryDuration':
                        print 'bpel set StartupScheduleConfig:startupRecoveryDuration ' + key + ' to value ' + str(values[cnt])
                        values [cnt] = Long(0)
                        print 'bpel set StartupScheduleConfig:startupRecoveryDuration ' + key + ' to value ' + str(values[cnt])
                if key == 'subsequentTriggerDelay':
                        print 'bpel set StartupScheduleConfig:subsequentTriggerDelay ' + key + ' to value ' + str(values[cnt])
                        values [cnt] = Long(0)
                        print 'bpel set StartupScheduleConfig:subsequentTriggerDelay ' + key + ' to value ' + str(values[cnt])
                cnt = cnt + 1
        new_obj = CompositeDataSupport(startup_obj.getCompositeType(), keyitems, values)
        return new_obj





##################### Main line ##########################

env=sys.argv[1]
print "Config file:" + env
configfile = FileInputStream(env)

print "Loaded file : " + env
configProps = Properties()
configProps.load(configfile)

PropertyConfigurator.configure("log4j.properties")
logger = Logger.getLogger("SOASetup")


logger.info('Starting')
try:
        createconn(end,configProps)
        changelog(configProps)
        changeBPEL(configProps)
        changeBPELRecovery(configProps)
        changeEDN(configProps)
        createSOAPartition(configProps)

except Exception, e:
        print 'Exception---------------------------'
        print e
        cancelEdit('y')

logger.info('Ending')

3) Invoke WLST to change BEPL configurations : wlst.sh fmwBPELMbean.py  dev.properties
WLST script to create JMS Objects  ( JMS servers , Modules , FileStore ,Queue , Topic , Connection factories and so on )

1) Step : Create property file with list of JMS Servers , JMS Module,FileStore ,Queue , Topic , Connection factories needs to configure.  Let us say property file name : jmsObjects.properties.

#  JMS Objects - Properties
#
#
#############################################################
domain.name=soa_domain

wlst.log=soa_domain_jms.log
admin.url=t3://AdminServerURL:7001
admin.username=Weblogic
admin.password=Weblogic1

####################################################################
# PERSISTENT STORES PROPERTIES
####################################################################
persistentstores.list=JMSFileStorePOSIA_auto_1,JMSFileStorePOSIA_auto_2

JMSFileStorePOSIA_auto_1.directory=/u01/admin/soa_domain/soa_cluster/JMSFileStorePOSIA_auto_1
JMSFileStorePOSIA_auto_1.target=wls_soa1
JMSFileStorePOSIA_auto_1.targetType=Server

JMSFileStorePOSIA_auto_2.directory=/u01/admin/soa_domain/soa_cluster/JMSFileStorePOSIA_auto_2
JMSFileStorePOSIA_auto_2.target=wls_soa3
JMSFileStorePOSIA_auto_2.targetType=Server



###################################################################
#
#        JMS SERVERS PROPERTIES
##################################################################
jmsservers.list=JMSServer_auto_1,JMSServer_auto_2

JMSServer_auto_1.filestore=JMSFileStorePOSIA_auto_1
JMSServer_auto_1.target=wls_soa1
JMSServer_auto_1.targetType=Server

JMSServer_auto_2.filestore=JMSFileStorePOSIA_auto_2
JMSServer_auto_2.target=wls_soa3
JMSServer_auto_2.targetType=Server



##################################################################
##
##################################################################
##
##         JMS MODULES
##
#################################################################
jmsmodules.list=JMSModule

JMSModule.targets=soa_cluster:Cluster


JMSModule.subdeployments.list=SUB
JMSModule.SUB.target=JMSServer_auto_1,JMSServer_auto_2
JMSModule.SUB.targetType=JMSServer



JMSModule.connectionFactories.list=QueueConnectionFactory,ErrorConnectionFactory

JMSModule.QueueConnectionFactory.jndiName=jms/jms/QueueConnectionFactory
JMSModule.QueueConnectionFactory.clientID=
JMSModule.QueueConnectionFactory.clientIDPolicy=
JMSModule.QueueConnectionFactory.subscriptionSharingPolicy=
JMSModule.QueueConnectionFactory.messagesMaximun=
JMSModule.QueueConnectionFactory.xaEnabled=true
JMSModule.QueueConnectionFactory.transactionTimeout=
JMSModule.QueueConnectionFactory.serverAffinity=false


JMSModule.uniformDistributedQueues.list=IN_QUEUE_DLQ


Step 2) : create below .py script . let us say file name : JMSObjectsCreation.py

"""
This script starts an edit session, creates two different JMS Servers,
targets the jms servers to the server WLST is connected to and creates
jms topics, jms queues and jms templates in a JMS System module. The
jms queues and topics are targeted using sub-deployments.
"""

def startTransaction():
    edit()
    startEdit()

def endTransaction():
    save()
    activate(block="true")


############################################################################
#  Connect to the domain Administration Server
############################################################################
def connectToAdminServer(conUsername, conPassword, conURL):
    try:
        print 'Connecting to the Admin Server : %s with the user: %s' %(conURL, conUsername)
        connect(conUsername, conPassword, conURL)
        print 'Connected...'
    except:
        print 'Cannot connect to the administration server'
        exit()

def createFilePersistentStore(psname, psDirectoryValue, psTargetValue, psTargetType):
    try:
        print 'Creating Physical Directories on the shared'
        fileStoreDir = File(psDirectoryValue)
        bCreate = fileStoreDir.mkdirs()
        if bCreate == 0:
            if fileStoreDir.delete() == 1:
                bCreate = fileStoreDir.mkdirs()
            else:
                stopExecution("Cannot create a physical directory")
                exit()
        print 'Creating File Persistent Store'
        cmo = cd('/')
        print psname
        cmo.createFileStore(psname)
        psPath = '/FileStores/' + psname
        cmo = cd(psPath)
        cmo.setDirectory(psDirectoryValue)
        targets = createTargetsObj(psTargetValue, psTargetType)
        print targets

        set('Targets',jarray.array(targets, ObjectName))

        save()
        print ' Successful Create File Persistent Store %s' %(psname)

    except Exception, e:
        print 'Cannot Create the File Persistent Store %s' %(psname)
        print e
        cancelEdit('y')
        stopExecution('Cannot Create the File Persistent Store')
        exit()

def createJMSServer(jmsServerName, jmsFileStoreValue, jmsTargetValue,jmsTargetTypePropertyValue):
    try:
        print 'Creating JMS Server'
        cmo = cd('/')
        cmo.createJMSServer(jmsServerName)
        jmsPath = '/Deployments/' + jmsServerName
        cmo = cd(jmsPath)
        fsPath = '/FileStores/' + jmsFileStoreValue
        cmo.setPersistentStore(getMBean(fsPath))

        targets = createTargetsObj(jmsTargetValue, jmsTargetTypePropertyValue)

        set('Targets',jarray.array(targets, ObjectName))

        save()
        print ' Successful Create JMS Server %s' %(jmsServerName)

    except Exception, e:
        print 'Cannot Create the JMS Server %s' %(jmsServerName)
        print e
        cancelEdit('y')
        stopExecution('Cannot Create the JMS Server')
        exit()

def createJMSModule(jmsModuleName,jmsModuleTargets):
    try:
        print 'Creating JMS Module'
        cmo = cd('/')
        cmo.createJMSSystemResource(jmsModuleName)
        modulePath = '/SystemResources/' + jmsModuleName
        cmo = cd(modulePath)
        print "jmsModuleTargets =  "+jmsModuleTargets
        targets = createTargetsObjList(jmsModuleTargets)
        set('Targets',jarray.array(targets, ObjectName))

        save()
        print ' Successful Create JMS Module %s' %(jmsModuleName)

    except Exception, e:
        print 'Cannot Create the JMS Module %s' %(jmsModuleName)
        print e
        cancelEdit('y')
        stopExecution('Cannot Create the JMS Server')
        exit()


def createTargetsObj(targets, targetType):
    listOfTargets = []
    targetList = targets.split(',')
    for target in targetList:
        targetObj = 'com.bea:Name='+ target + ',Type=' + targetType
        print targetObj
        listOfTargets.append(ObjectName(str(targetObj)))

    return listOfTargets

def createTargetsObjList(listOfTargetsStr):
    listOfTargets = []
    targetList = listOfTargetsStr.split(',')
    for targetStr in targetList:
        target = targetStr.split(":")
        targetObj = 'com.bea:Name='+ target[0] + ',Type=' + target[1]
        print targetObj
        listOfTargets.append(ObjectName(str(targetObj)))

    return listOfTargets

def getJMSModulePath(jmsModuleName):
        jmsModulePath = "/JMSSystemResources/"+jmsModuleName+"/JMSResource/"+jmsModuleName
        return jmsModulePath

def createSubDeployment(jmsModuleName, jmsSubDeployName, jmsTargetVal, jmsTargetTypeVal):
    try:
        print 'Creating SubDeployment...' + jmsSubDeployName + ' for Module ...' + jmsModuleName
        cmo = cd('/')
        cmo = cd('/SystemResources/'+jmsModuleName)
        cmo.createSubDeployment(jmsSubDeployName)
        cmo = cd('/SystemResources/'+jmsModuleName+'/SubDeployments/'+subDeployName)
        targets = createTargetsObj(jmsTargetVal, jmsTargetTypeVal)
        set('Targets',jarray.array(targets, ObjectName))

        save()
        print ' Successful Create SubDeployment %s' %(jmsSubDeployName)

    except Exception, e:
        print 'Cannot Create the SubDeployment name %s' %(jmsSubDeployName)
        print e
        cancelEdit('y')
        stopExecution('Cannot Create the JMS Module')
        exit()

def createJMSConnectionFactory(jmsModuleName, cfName, configProps):
    try:
        jmsModulePath = getJMSModulePath(jmsModuleName)
        cmo = cd(jmsModulePath)
        cf = create(cfName,'ConnectionFactory')
        cfPath =jmsModulePath + '/ConnectionFactories/' + cfName
        cmo = cd(cfPath)
        value = configProps.get(jmsModuleName + '.' + cfName + '.jndiName')
        if (value != None and value != ''):
            value = String(value).trim()
            cmo.setJNDIName(value)

        value = configProps.get(jmsModuleName + '.' + cfName + '.subdeploymentName')
        if (value != None and value != ''):
            value = String(value).trim()
            cmo.setSubDeploymentName(value)
            cmo.setDefaultTargetingEnabled(false)
        else:
            cmo.setDefaultTargetingEnabled(true)

        cmo = cd(cfPath + '/ClientParams/' + cfName)

        value = configProps.get(jmsModuleName + '.' + cfName + '.clientID')
        if (value != None and value != ''):
            value = String(value).trim()
            cmo.setClientId(value)

        value = configProps.get(jmsModuleName + '.' + cfName + '.clientIDPolicy')
        if (value != None and value != ''):
            if (value == 'Restricted' or value == 'Unrestricted'):
                cmo.setClientIdPolicy(value)

        value = configProps.get(jmsModuleName + '.' + cfName + '.subscriptionSharingPolicy')
        if (value != None and value != ''):
            if (value == 'Exclusive' or value == 'Sharable'):
                cmo.setSubscriptionSharingPolicy(value)

        value = configProps.get(jmsModuleName + '.' + cfName + '.messagesMaximun')
        if (value != None and value != ''):
            cmo.setMessagesMaximum(value)

        cmo = cd(cfPath+'/TransactionParams/'+ cfName)

        value = configProps.get(jmsModuleName + '.' + cfName + '.xaEnabled')
        if (value == 'true'):
            cmo.setXAConnectionFactoryEnabled(true)
        if (value == 'false'):
            cmo.setXAConnectionFactoryEnabled(false)

        value = configProps.get(jmsModuleName + '.' + cfName + '.transactionTimeout')
        if (value != None and value != ''):
            cmo.setTransactionTimeout(Long(value))

        cmo = cd(cfPath+'/LoadBalancingParams/'+ cfName)

        value = configProps.get(jmsModuleName + '.' + cfName + '.serverAffinity')
        if (value != None and value != ''):
            if (value == 'true'):
                cmo.setServerAffinityEnabled(true)
            if (value == 'false'):
                cmo.setServerAffinityEnabled(false)

        save()
        print ' Successful Create Connection Factory %s' %(cfName)

    except Exception, e:
        print 'Cannot Create the Connection Factory name %s' %(cfName)
        print e
        cancelEdit('y')
        stopExecution('Cannot Create the Connection Factory')
        exit()


def createJMSDistributedQueueUDD(jmsModuleName, distrQName, configProps):
    try:
        jmsModulePath = getJMSModulePath(jmsModuleName)
        cmo = cd(jmsModulePath)
        cmo.createUniformDistributedQueue(distrQName)
        distrQPath = jmsModulePath + '/UniformDistributedQueues/' + distrQName
        cmo = cd(distrQPath)
        value = configProps.get(jmsModuleName + '.' + distrQName + '.jndiName')
        if (value != None and value != ''):
            value = String(value).trim()
            cmo.setJNDIName(value)

        value = configProps.get(jmsModuleName + '.' + distrQName + '.subdeploymentName')
        if (value != None and value != ''):
            value = String(value).trim()
            cmo.setSubDeploymentName(value)

        cmo = cd(distrQPath + '/DeliveryFailureParams/' + distrQName)

        value = configProps.get(jmsModuleName + '.' + distrQName + '.errorDestination')
        if (value != None and value != ''):
            value = String(value).trim()
            errorQPath = '/JMSSystemResources/' + jmsModuleName + '/JMSResource/' + jmsModuleName + '/UniformDistributedQueues/' + value
            cmo.setErrorDestination(getMBean(errorQPath))

        value = configProps.get(jmsModuleName + '.' + distrQName + '.expirationLoggingPolicy')
        if (value != None and value != ''):
            value = String(value).trim()
            cmo.setExpirationLoggingPolicy(value)

        value = configProps.get(jmsModuleName + '.' + distrQName + '.expirationPolicy')
        if (value != None and value != ''):
            value = String(value).trim()
            cmo.setExpirationPolicy(value)

        value = configProps.get(jmsModuleName + '.' + distrQName + '.redeliveryLimit')
        if (value != None and value != ''):
            cmo.setRedeliveryLimit(Integer(value))

        cmo = cd(distrQPath + '/DeliveryParamsOverrides/' + distrQName)

        value = configProps.get(jmsModuleName + '.' + distrQName + '.deliveryMode')
        if (value != None and value != ''):
            value = String(value).trim()
            cmo.setDeliveryMode(value)

        value = configProps.get(jmsModuleName + '.' + distrQName + '.redeliveryDelay')
        if (value != None and value != ''):
            cmo.setRedeliveryDelay(Long(value))

        value = configProps.get(jmsModuleName + '.' + distrQName + '.timeToDeliver')
        if (value != None and value != ''):
            cmo.setTimeToDeliver(value)

        value = configProps.get(jmsModuleName + '.' + distrQName + '.timeToLive')
        if (value != None and value != ''):
            cmo.setTimeToLive(Long(value))

        cd(distrQPath + '/MessageLoggingParams/' + distrQName)

        value = configProps.get(jmsModuleName + '.' + distrQName + '.messageLoggingEnabled')
        if (value == 'true'):
            cmo.setMessageLoggingEnabled(true)
        if (value == 'false'):
            cmo.setMessageLoggingEnabled(false)

        value = configProps.get(jmsModuleName + '.' + distrQName + '.messageLoggingFormat')
        if (value != None and value != ''):
            value = String(value).trim()
            cmo.setMessageLoggingFormat(value)

        save()

    except Exception, e:
        print 'Cannot Create the UUD Queue name %s' %(distrQName)
        print e

def createJMSDistributedTopicUDD(jmsModuleName, distrTopicName, configProps):
    try:
        jmsModulePath = getJMSModulePath(jmsModuleName)
        cmo = cd(jmsModulePath)
        cmo.createUniformDistributedTopic(distrTopicName)
        distrTPath = jmsModulePath + '/UniformDistributedTopics/' + distrTopicName
        cmo = cd(distrTPath)

        value = configProps.get(jmsModuleName + '.' + distrTopicName + '.jndiName')
        cmo.setJNDIName(value)

        value = configProps.get(jmsModuleName + '.' + distrTopicName + '.forwardingPolicy')
        if (value == 'Replicated' or value == 'Partitioned'):
            cmo.setForwardingPolicy(value)

        value = configProps.get(jmsModuleName + '.' + distrTopicName + '.subdeploymentName')
        if (value != None and value != ''):
            value = String(value).trim()
            cmo.setSubDeploymentName(value)

        value = configProps.get(jmsModuleName + '.' + distrTopicName + '.jmscreatedestinationidentifier')
        if (value != None and value != ''):
            value = String(value).trim()
            cmo.setJMSCreateDestinationIdentifier(value)

        cmo = cd(distrTPath + '/DeliveryFailureParams/' + distrTopicName)

        value = configProps.get(jmsModuleName + '.' + distrTopicName + '.errorDestination')
        if (value != None and value != ''):
            value = String(value).trim()
            errorTPath = '/JMSSystemResources/' + jmsModuleName + '/JMSResource/' + jmsModuleName + '/UniformDistributedTopics/' + value
            cmo.setErrorDestination(getMBean(errorTPath))

        value = configProps.get(jmsModuleName + '.' + distrTopicName + '.expirationPolicy')
        if (value == 'None' or value == 'Log' or value == 'Redirect' or value == 'Discard'):
            cmo.setExpirationPolicy(value)

        value = configProps.get(jmsModuleName + '.' + distrTopicName + '.redeliveryLimit')
        if (value != None and value != ''):
            value = String(value).trim()
            cmo.setRedeliveryLimit(Integer(value))

        cmo = cd(distrTPath + '/DeliveryParamsOverrides/' + distrTopicName)

        value = configProps.get(jmsModuleName + '.' + distrTopicName + '.deliveryMode')
        if (value == 'Persistent' or value == 'Non-Persistent' or value == 'No-Delivery'):
            cmo.setDeliveryMode(value)

        value = configProps.get(jmsModuleName + '.' + distrTopicName + '.redeliveryDelay')
        if (value != None and value != ''):
            value = String(value).trim()
            cmo.setRedeliveryDelay(Long(value))

        value = configProps.get(jmsModuleName + '.' + distrTopicName + '.timeToDeliver')
        if (value != None and value != ''):
            value = String(value).trim()
            cmo.setTimeToDeliver(value)

        value = configProps.get(jmsModuleName + '.' + distrTopicName + '.timeToLive')
        if (value != None and value != ''):
            value = String(value).trim()
            cmo.setTimeToLive(Long(value))


        cmo = cd(distrTPath + '/MessageLoggingParams/' + distrTopicName)
        value = configProps.get(jmsModuleName + '.' + distrTopicName + '.messageLoggingEnabled')
        if (value == 'false'):
            cmo.setMessageLoggingEnabled(false)

        if (value == 'true'):
            cmo.setMessageLoggingEnabled(true)
            format = configProps.get(jmsModuleName + '.' + distrTopicName + '.messageLoggingFormat')
            if (format != None and format != ''):
                format = String(format).trim()
                cmo.setMessageLoggingFormat(format)

        save()

    except Exception, e:
        print 'Cannot Create the Distributed Topic Name %s' %(distrTopicName)
        print e


def createJMSTemplates(jmsModuleName, template, configProps):
    try:
        jmsModulePath = getJMSModulePath(jmsModuleName)
        cmo = cd(jmsModulePath)
        cmo.createTemplate(template)
        templatePath = jmsModulePath + '/Templates/' + template
        cmo = cd(templatePath)

        cmo = cd(templatePath + '/DeliveryFailureParams/' + template)

        value = configProps.get(jmsModuleName + '.' + template + '.expirationPolicy')
        if (value == 'None' or value == 'Log' or value == 'Redirect' or value == 'Discard'):
            cmo.setExpirationPolicy(value)

        value = configProps.get(jmsModuleName + '.' + template + '.redeliveryLimit')
        if (value != None and value != ''):
            value = String(value).trim()
            cmo.setRedeliveryLimit(Integer(value))

        cmo = cd(templatePath + '/DeliveryParamsOverrides/' + template)

        value = configProps.get(jmsModuleName + '.' + template + '.deliveryMode')
        if (value == 'Persistent' or value == 'Non-Persistent' or value == 'No-Delivery'):
            cmo.setDeliveryMode(value)

        value = configProps.get(jmsModuleName + '.' + template + '.redeliveryDelay')
        if (value != None and value != ''):
            value = String(value).trim()
            cmo.setRedeliveryDelay(Long(value))

        value = configProps.get(jmsModuleName + '.' + template + '.timeToDeliver')
        if (value != None and value != ''):
            value = String(value).trim()
            cmo.setTimeToDeliver(value)

        value = configProps.get(jmsModuleName + '.' + template + '.timeToLive')
        if (value != None and value != ''):
            value = String(value).trim()
            cmo.setTimeToLive(value)


        cmo = cd(templatePath + '/MessageLoggingParams/' + template)
        value = configProps.get(jmsModuleName + '.' + template + '.messageLoggingEnabled')
        if (value == 'false'):
            cmo.setMessageLoggingEnabled(false)

        if (value == 'true'):
            cmo.setMessageLoggingEnabled(true)
            format = configProps.get(jmsModuleName + '.' + template + '.messageLoggingFormat')
            if (format != None and format != ''):
                format = String(format).trim()
                cmo.setMessageLoggingFormat(format)

        save()

    except Exception, e:
        print 'Cannot Create the template Name %s' %(template)
        print e



def createJMSQuotas(jmsModuleName, quota, configProps):
    try:
        jmsModulePath = getJMSModulePath(jmsModuleName)
        cmo = cd(jmsModulePath)
        cmo.createQuota(quota)
        quotaPath = jmsModulePath + '/Quotas/' + quota
        cmo = cd(quotaPath)

        value = configProps.get(jmsModuleName + '.' + quota + '.bytesMaximum')
        if (value != None and value != ''):
            value = String(value).trim()
            cmo.setBytesMaximum(Long(value))

        value = configProps.get(jmsModuleName + '.' + quota + '.messagesMaximum')
        if (value != None and value != ''):
            value = String(value).trim()
            cmo.setMessagesMaximum(Long(value))

        value = configProps.get(jmsModuleName + '.' + quota + '.policy')
        if (value != None and value != ''):
            value = String(value).trim()
            cmo.setPolicy(value)

        value = configProps.get(jmsModuleName + '.' + quota + '.shared')
        if (value == 'false'):
            cmo.setShared(false)
        if (value == 'true'):
            cmo.setShared(true)

        save()

    except Exception, e:
        print 'Cannot Create the Quota Name %s' %(quota)
        print e



def UpdateJMSServer(jmsServerName, configProps):
    try:
        print 'Updating JMS Server %s' %(jmsServerName)
        jmsPath = '/Deployments/' + jmsServerName
        cmo = cd(jmsPath)

        value = configProps.get(jmsServerName + '.hostingTemporaryDestinations')
        if (value != None and value != ''):
            value = String(value).trim()
            if (value == 'true'):
                cmo.setHostingTemporaryDestinations(true)
                value1 = configProps.get(jmsServerName + '.temporaryTemplateResource')
                if (value1 != None and value1 != ''):
                    value1 = String(value1).trim()
                    cmo.setTemporaryTemplateResource(value1)

                value1 = configProps.get(jmsServerName + '.temporaryTemplateName')
                if (value1 != None and value1 != ''):
                    value1 = String(value1).trim()
                    cmo.setTemporaryTemplateName(value1)
                #end if
            #end if
        #end if

        save()
        print ' Successful Update JMS Server %s' %(jmsServerName)

    except Exception, e:
        print 'Cannot Update the JMS Server %s' %(jmsServerName)
        print e
        cancelEdit('y')
        stopExecution('Cannot Update the JMS Server')
        exit()

def createForeignJNDIProvider(foreignJNDIProviderName,listOfTargetsStr,initialContextFactory,providerURL,user,password):
    try:
        print 'Creating ForeignJNDIProvider'
        cmo = cd('/')
        foreignJNDIInstance=create(foreignJNDIProviderName,"ForeignJNDIProvider")
        foreignJNDIInstance.setInitialContextFactory(initialContextFactory)
        foreignJNDIInstance.setProviderURL(providerURL)
        foreignJNDIInstance.setUser(user)
        foreignJNDIInstance.setPassword(password)

        targetList = listOfTargetsStr.split(',')
        for targetStr in targetList:
                target = targetStr.split(":")
                targetObj = 'com.bea:Name='+ target[0] + ',Type=' + target[1]
                if (target[1]=="Server"):
                        targetMB=getMBean("/Servers/"+target[0])
                if (target[1]=="Cluster"):
                        targetMB=getMBean("/Clusters/"+target[0])
                if targetMB is None:
                        print "@@@ Invalid Foreign JNDI Provider Target '"+target[0]+"'"
                        exit()
                foreignJNDIInstance.addTarget(targetMB)

        save()

    except Exception, e:
        print 'Cannot Create the Foreign JNDI Provider name %s' %(foreignJNDIProviderName)
        print e
        cancelEdit('y')
        stopExecution('Cannot Create the Foreign JNDI Provider')
        exit()

def createForeignJNDIProviderLink(foreignJNDIProviderName,linkName,localJNDI,remoteJNDI):
    try:
        print 'Creating ForeignJNDIProvider link'
        foreignJNDIInstance = getMBean("/ForeignJNDIProviders/"+foreignJNDIProviderName)
        foreignLinkInstance=foreignJNDIInstance.createForeignJNDILink(linkName)
        foreignLinkInstance.setLocalJNDIName(localJNDI)
        foreignLinkInstance.setRemoteJNDIName(remoteJNDI)
        save()

    except Exception, e:
        print 'Cannot Create the Foreign JNDI Provider name %s' %(foreignJNDIProviderName)
        print e
        cancelEdit('y')
        stopExecution('Cannot Create the Foreign JNDI Provider')
        exit()

####################################################################################################
#
#     Main Module
#
####################################################################################################

from java.io import FileInputStream
from wlstModule import *

print 'Starting...'

propertiesFile = sys.argv[1]
if (propertiesFile == None or len(propertiesFile) == 0):
    print 'Usage wlst.sh configureJMSObjects.py JMSPLIS.properties'
    exit()

try:
    propInputStream = FileInputStream(propertiesFile)
    configProps = Properties()
    configProps.load(propInputStream)
    wlstLogFile = configProps.get("wlst.log")
    redirect(wlstLogFile)

    domainName=configProps.get("domain.name")
    adminURL=configProps.get("admin.url")
    adminUserName=configProps.get("admin.username")
    adminPassword=configProps.get("admin.password")
except Exception, e:
    print 'Missing properties in properties file or cannot read properties file'
    print e
    exit()

#    Connect to the Administration Server

print 'Connecting to the Administration server ...'
connectToAdminServer(adminUserName, adminPassword, adminURL)

print 'Starting Edit the domain ' + domainName

#### Starting an edit session

startTransaction()

### Creating file stores
filestores=configProps.get("persistentstores.list")
if (filestores != None and (len(String(filestores).trim()) > 0)):

    print 'Creating Persistent Stores:  %s' %(filestores)

    listofPS = filestores.split(',')
    for psname in listofPS:
        print psname
        psDirectoryProperty = psname + '.directory'
        psDirectoryValue = configProps.get(psDirectoryProperty)
        print psDirectoryValue
        psTargetProperty = psname + '.target'
        psTargetValue = configProps.get(psTargetProperty)
        print psTargetValue
        psTargetTypeProperty = psname + '.targetType'
        psTargetTypeValue = configProps.get(psTargetTypeProperty)
        print psTargetTypeValue

        createFilePersistentStore(psname, psDirectoryValue, psTargetValue, psTargetTypeValue)

# Create JMS Servers
jmsservers=configProps.get("jmsservers.list")
if (jmsservers != None and (len(String(jmsservers).trim()) > 0)):
    print 'Creating JMS Servers:  %s' %(jmsservers)

    listofJMSServers = jmsservers.split(',')
    for jmsServerName in listofJMSServers:
        print jmsServerName
        jmsFileStoreProperty = jmsServerName + '.filestore'
        jmsFileStoreValue = configProps.get(jmsFileStoreProperty)
        print jmsFileStoreValue
        jmsTargetProperty = jmsServerName + '.target'
        jmsTargetValue = configProps.get(jmsTargetProperty)
        print jmsTargetValue
        jmsTargetTypeProperty = jmsServerName + '.targetType'
        jmsTargetTypeValue = configProps.get(jmsTargetTypeProperty)
        print jmsTargetTypeValue

        createJMSServer(jmsServerName, jmsFileStoreValue, jmsTargetValue, jmsTargetTypeValue)

#### Activating the creation of JMS Servers before creating the modules
endTransaction()

startTransaction()

#Create JMS Modules
jmsmodules = configProps.get("jmsmodules.list")
if (jmsmodules != None and (len(String(jmsmodules).trim()) > 0)):
    print 'Creating JMS Modules: %s' %(jmsmodules)
    listofJMSModules = jmsmodules.split(',')
    for jmsModuleName in listofJMSModules:
        print jmsModuleName
        jmsTargetsProp = jmsModuleName + '.targets'
        jmsTargetsPropValue = configProps.get(jmsTargetsProp)
        print jmsTargetsPropValue

        createJMSModule(jmsModuleName,jmsTargetsPropValue)

        ####Create Sub deployment

        subDeploys = configProps.get(jmsModuleName + '.subdeployments.list')
        if (subDeploys != None and (len(String(subDeploys).trim()) > 0)):
            print 'Creating Sub Deployments: %s' %(subDeploys)

          listOfSubDeploys = subDeploys.split(',')
            for subDeployName in listOfSubDeploys:
                print subDeployName
                jmsTargetProperty = jmsModuleName + '.' + subDeployName + '.target'
                jmsTargetTypeProperty = jmsModuleName + '.' + subDeployName + '.targetType'
                jmsTargetVal = configProps.get(jmsTargetProperty)
                jmsTargetTypeVal = configProps.get(jmsTargetTypeProperty)
                createSubDeployment(jmsModuleName, subDeployName, jmsTargetVal, jmsTargetTypeVal)
            #end for
        #end if
        #Create JMS Module Objects - ConnectionFactories
        connFactories = configProps.get(jmsModuleName + '.connectionFactories.list')
        if (connFactories != None and (len(String(connFactories).trim()) > 0)):
            print 'Creating Connection Factories %s for Module: %s' %(connFactories, jmsModuleName)
            listofCfName = connFactories.split(',')
            for cfName in listofCfName:
                print cfName
                createJMSConnectionFactory(jmsModuleName, cfName, configProps)
            # end for connectionFactories
        #end if

        ## Create JMS Templates
        templates = configProps.get(jmsModuleName + '.templates.list')
        if (templates != None and (len(String(templates).trim()) > 0)):
            print 'Creating Templates %s for Module: %s' %(templates, jmsModuleName)
            listofTemplates = templates.split(',')
            for template in listofTemplates:
                print template
                createJMSTemplates(jmsModuleName, template, configProps)
            #end for
        #end if

        ## Create JMS Quotqs
        quotas= configProps.get(jmsModuleName + '.quotas.list')
        if (quotas != None and (len(String(quotas).trim()) > 0)):
            print 'Creating Quotas %s for Module: %s' %(quotas, jmsModuleName)
            listofQuotas = quotas.split(',')
            for quota in listofQuotas:
                print quota
                createJMSQuotas(jmsModuleName, quota, configProps)
            #end for
        #end if

        ## Create JMS Module Objects - Distributed Queue
        distrQueues = configProps.get(jmsModuleName + '.uniformDistributedQueues.list')
        if (distrQueues != None and (len(String(distrQueues).trim()) > 0)):
            print 'Creating Distributed Queues UDD %s for Module: %s' %(distrQueues, jmsModuleName)
            listofDistrQName = distrQueues.split(',')
            for distrQName in listofDistrQName:
                print distrQName
                createJMSDistributedQueueUDD(jmsModuleName, distrQName, configProps)
            #end for
        #end if

        ## Create JMS Module Objects - Distributed Topics
        distrTopics = configProps.get(jmsModuleName + '.uniformDistributedTopics.list')
        if (distrTopics != None and (len(String(distrTopics).trim()) > 0)):
            print 'Creating Distributed Topics UDD %s for Module: %s' %(distrTopics, jmsModuleName)
            listofDistrTName = distrTopics.split(',')
            for distrTName in listofDistrTName:
                print distrTName
                createJMSDistributedTopicUDD(jmsModuleName, distrTName, configProps)
            #end for
        #end if

    #end for
#end if
endTransaction()

startTransaction()
###### Update JMS Servers
jmsservers=configProps.get("update.jmsservers.list")
if (jmsservers != None and (len(String(jmsservers).trim()) > 0)):
    print 'Updating JMS Servers:  %s' %(jmsservers)

    listofJMSServers = jmsservers.split(',')
    for jmsServerName in listofJMSServers:

 print jmsServerName
        UpdateJMSServer(jmsServerName, configProps)


endTransaction()

startTransaction()

#Create Foreign JNDI Providers
foreignJNDIProviders = configProps.get("foreignJNDIProviders.list")
if (foreignJNDIProviders != None and (len(String(foreignJNDIProviders).trim()) > 0)):
    print 'Creating Foreign JNDI Providers: %s' %(foreignJNDIProviders)
    listofForeignJNDIProviders = foreignJNDIProviders.split(',')
    for foreignJNDIProviderName in listofForeignJNDIProviders:
        print foreignJNDIProviderName
        providerTargetsProp = foreignJNDIProviderName + '.targets'
        listOfTargetsStr = configProps.get(providerTargetsProp)
        print listOfTargetsStr
        providerInitialContextFactoryProp = foreignJNDIProviderName + '.initialContextFactory'
        providerInitialContextFactoryPropValue = configProps.get(providerInitialContextFactoryProp)
        print providerInitialContextFactoryPropValue
        providerURLProp = foreignJNDIProviderName + '.providerURL'
        providerURLPropValue = configProps.get(providerURLProp)
        print providerURLPropValue
        providerUserProp = foreignJNDIProviderName + '.user'
        providerUserPropValue = configProps.get(providerUserProp)
        print providerUserPropValue
        providerPasswordProp = foreignJNDIProviderName + '.password'
        providerPasswordPropValue = configProps.get(providerPasswordProp)
        print providerPasswordPropValue

        createForeignJNDIProvider(foreignJNDIProviderName,listOfTargetsStr,providerInitialContextFactoryPropValue,providerURLPropValue,providerUserPropValue,providerPas
swordPropValue)

        ####Create Foreign JNDI Provider Links
        jndiLinks = configProps.get(foreignJNDIProviderName + '.jndi.list')
        if (jndiLinks != None and (len(String(jndiLinks).trim()) > 0)):
            print 'Creating Foreign JNDI Provider Links: %s' %(jndiLinks)
            listOfLinks = jndiLinks.split(',')
            for jndiLinkName in listOfLinks:
                print jndiLinkName
                localJNDIProp = foreignJNDIProviderName + '.jndi.' + jndiLinkName + '.localJNDI'
                localJNDIValue = configProps.get(localJNDIProp)
                remoteJNDIProp = foreignJNDIProviderName + '.jndi.' + jndiLinkName + '.remoteJNDI'
                remoteJNDIValue = configProps.get(remoteJNDIProp)
                createForeignJNDIProviderLink(foreignJNDIProviderName,jndiLinkName,localJNDIValue,remoteJNDIValue)
            #end for
        #end if
    #end for
#end if
endTransaction()

exit()

Step 3) Invoke WLST and run .py script : wlst.sh JMSObjectsCreation.py    jmsObjects.properties

WLST script for Database adaptor configurations

Step 1) create a property file with Admin Server details , and Number of connections to configure in database adaptor and those configuration details. in this example , i am taking only one DB adaptor configuration. let us say our property file name : dev.properties

domain.name=soa_domain
domain.adminHost=AdminServerHostname
domain.adminPort=7001
domain.adminUserName=Weblogic
domain.soahome=/u01/fmw/product/111/soa_111


###########################DB Configuration#########################################
########## make 'xa' value true if data source is XA################################

deploymentPlan.db.location=/u01/shared/posia/soa/connectors/DBAdapterPlan.xml
totalDbToConfigure=1
############################DB CCBSOA Config properties#################################
db.resource.dbJNDIName1=eis/DB/SOA_INFRA
db.resource.dataSourceName1=jdbc/SOA/SOA_INFRA
db.resource.platformClassName1=
db.resource.xa1=true
db.resource.sequencePreallocationSize1=1
############################################################################################

Step 2 ) Script for DB Adaptor configurations. Let us say file name is : DBAdaptorConfig.py

from java.io import FileInputStream
env=sys.argv[1]

propInputStream = FileInputStream( env+".properties")

configProps = Properties()
configProps.load(propInputStream)
totdbToConfigure=configProps.get('totalDbToConfigure')
domainName=configProps.get("domain.name")
hostName=configProps.get("domain.adminHost")
portNo=configProps.get("domain.adminPort")
adminUserName=configProps.get("domain.adminUserName")
planPathDB=configProps.get("deploymentPlan.db.location")
adminURL="t3://" + hostName + ":" + portNo
soahome=configProps.get('domain.soahome')
appPathDB=soahome+'/soa/connectors/DbAdapter.rar'
appNameDB='DbAdapter'
moduleOverrideNamedb=appNameDB+'.rar'
moduleDescriptorName='META-INF/weblogic-ra.xml'

def delDeploymentPlanVariable(wlstPlan, name, value, xpath,overrideName, origin='planbased'):
    print 'inside delDeploymentPlanVariable'
    wlstPlan.destroyVariable(name)
    wlstPlan.destroyVariableAssignment(name, overrideName, moduleDescriptorName)


def makeDeploymentPlanVariable(wlstPlan, name, value, xpath,overrideName, origin='planbased'):
    print 'inside makeDeploymentPlanVariable'
    wlstPlan.destroyVariable(name)

    wlstPlan.destroyVariableAssignment(name, overrideName, moduleDescriptorName)

    variableAssignment = wlstPlan.createVariableAssignment(name, overrideName, moduleDescriptorName)

    variableAssignment.setXpath(xpath)
    variableAssignment.setOrigin(origin)

    wlstPlan.createVariable(name, value)

    print 'moduleDescriptorName=',moduleDescriptorName

i = 1
print 'no of adapter to configure...' +totdbToConfigure
print 'connecting to weblogic domain...' + domainName
print 'configuring adapter ....' + appPathDB


connect()
edit()
startEdit()
try:


        myPlandb=loadApplication(appPathDB, planPathDB)
        while (i <= int(totdbToConfigure)):
            print 'inside while'
            try:
                    dbJndi =  configProps.get("db.resource.dbJNDIName"+str(i))
                    dbDS=configProps.get('db.resource.dataSourceName'+str(i))
                    dbPlatform=configProps.get('db.resource.platformClassName'+str(i))
                    xaDS= configProps.get('db.resource.xa'+str(i))
                    sequencePreallocationSize=configProps.get('db.resource.sequencePreallocationSize'+str(i))
                    print 'dbjndi............', dbJndi

                    makeDeploymentPlanVariable(myPlandb, "ConnectionInstance_"+dbJndi, dbJndi, '/weblogic-connector/outbound-resource-adapter/connection-definition-grou
p/[connection-factory-interface="javax.resource.cci.ConnectionFactory"]/connection-instance/[jndi-name="'+dbJndi+'"]/jndi-name',moduleOverrideNamedb)

                    if String(xaDS).indexOf('false') == -1:
                        delDeploymentPlanVariable(myPlandb, "ConfigProperty_dataSourceName_Value_"+dbJndi, dbDS, '/weblogic-connector/outbound-resource-adapter/connecti
on-definition-group/[connection-factory-interface="javax.resource.cci.ConnectionFactory"]/connection-instance/[jndi-name="'+dbJndi+'"]/connection-properties/properties/
property/[name="dataSourceName"]/value',moduleOverrideNamedb)
                        makeDeploymentPlanVariable(myPlandb, "ConfigProperty_dataSourceName_Value_"+dbJndi, dbDS, '/weblogic-connector/outbound-resource-adapter/connect
ion-definition-group/[connection-factory-interface="javax.resource.cci.ConnectionFactory"]/connection-instance/[jndi-name="'+dbJndi+'"]/connection-properties/properties
/property/[name="xaDataSourceName"]/value',moduleOverrideNamedb)
                    else:
                        print 'Not a XA'
                        delDeploymentPlanVariable(myPlandb, "ConfigProperty_dataSourceName_Value_"+dbJndi, dbDS, '/weblogic-connector/outbound-resource-adapter/connecti
on-definition-group/[connection-factory-interface="javax.resource.cci.ConnectionFactory"]/connection-instance/[jndi-name="'+dbJndi+'"]/connection-properties/properties/
property/[name="xaDataSourceName"]/value',moduleOverrideNamedb)
                        makeDeploymentPlanVariable(myPlandb, "ConfigProperty_dataSourceName_Value_"+dbJndi, dbDS, '/weblogic-connector/outbound-resource-adapter/connect
ion-definition-group/[connection-factory-interface="javax.resource.cci.ConnectionFactory"]/connection-instance/[jndi-name="'+dbJndi+'"]/connection-properties/properties
/property/[name="dataSourceName"]/value',moduleOverrideNamedb)
                    if len(dbPlatform)!=0:
                        makeDeploymentPlanVariable(myPlandb, "ConfigProperty_platformClassName_Value_"+dbJndi, dbPlatform, '/weblogic-connector/outbound-resource-adapte
r/connection-definition-group/[connection-factory-interface="javax.resource.cci.ConnectionFactory"]/connection-instance/[jndi-name="'+dbJndi+'"]/connection-properties/p
roperties/property/[name="platformClassName"]/value',moduleOverrideNamedb)
                    if len(sequencePreallocationSize)!=0:
                        makeDeploymentPlanVariable(myPlandb, "ConfigProperty_platformClassName_Value_"+dbJndi, sequencePreallocationSize, '/weblogic-connector/outbound-
resource-adapter/connection-definition-group/[connection-factory-interface="javax.resource.cci.ConnectionFactory"]/connection-instance/[jndi-name="'+dbJndi+'"]/connecti
on-properties/properties/property/[name="sequencePreallocationSize"]/value',moduleOverrideNamedb)
                    myPlandb.save();
                    save();

            except:
                    print 'Exception occured while creating datasource'
                    print 'error infor....', sys.exc_info()[0]
                    raise
            i = i+1
        cd('/AppDeployments/DbAdapter/Targets');
        print 'updating configuration............. for ', appNameDB
        print 'updating configuration............. for ', planPathDB
        updateApplication(appNameDB, planPathDB);
        startApplication(appNameDB)
        activate(block='true');
except:
     print '********************************************'
     print 'Exception occured while configuring db jndi'
     print 'error infor....', sys.exc_info()[0]
     undo('false','y')
     exit('y',1001)
     print '********************************************'

Step 3) Invoke WLST and run the script : wlst.sh DBAdaptorConfig.py dev


WLST script for Weblogic Datasource create , update and delete

1) create a property file with the details of datasources for create , update and delete. Let us property file name : dataSourceCreate_update_delete.properties

admin.url=t3://AdminServerHostName:7001
admin.username=Weblogic
admin.password=Weblogic1

# this value allows main controller to loop over projects to
resources.loop=1,2,3,4

#########################################
# DB Connectionparams for XrsConnectionPool
#########################################
# create,delete,noaction
db.action_1=create
# the format is target1:type1,target2:type2
# the target is cluster name or server nams
# type is either 'Cluster' or 'Server'
db.targets_1=soa_cluster:Cluster
# flag for either 'xa' or 'nonxa'
db.type_1=xa
db.jndiname_1=jdbc/SOA/DEV_SOAINFRA
db.name_1=DEVSOA_INFRA
db.url_1=jdbc:oracle:thin:@DatabaseServerName:dbPort:Schema
db.username_1=DEV_SOAINFRA
db.password_1=XXXXXX
db.transaction_1=
db.test.query_1=SQL SELECT * FROM DUAL
db.maxCapacity_1=32


#########################################
# DB Connectionparams for SOADataSource
#########################################
# create,delete,noaction,update
db.action_2=update
db.name_2=SOADataSource
db.initCapacity_2=10
db.minCapacity_2=10
db.maxCapacity_2=100
db.connectTimeout_2=10000
db.readTimeout_2=30000

#########################################
# DB Connectionparams for SOALocalTxDataSource
#########################################
# create,delete,noaction,update
db.action_3=update
db.name_3=SOALocalTxDataSource
db.initCapacity_3=10
db.minCapacity_3=10
db.maxCapacity_3=100
db.connectTimeout_3=10000
db.readTimeout_3=30000

#########################################
# DB Connectionparams for mds-soa
#########################################
# create,delete,noaction,update
db.action_4=update
db.name_4=mds-soa
db.initCapacity_4=10
db.minCapacity_4=10
db.maxCapacity_4=70
db.connectTimeout_4=10000
db.readTimeout_4=30000

2)  WLST script for datasource creation , update and delete. Let us script name : dataSourceCreate_update_delete.py

from java.io import FileInputStream
from java.util import Properties
from org.apache.log4j import *

PropertyConfigurator.configure("log4j.properties")
logger = Logger.getLogger("JDBCSetup")

# Load the properties file.
def loadProperties(fileName):
        logger.info ("Processing: " + fileName)
        properties = Properties()
        input = FileInputStream(fileName)
        properties.load(input)
        input.close()

        result= {}
        for entry in properties.entrySet(): result[entry.key] = entry.value

        return result

configfile=sys.argv[1]

properties = loadProperties(configfile)
username = properties['admin.username']
password = properties['admin.password']
url = properties['admin.url']
resources_loop = properties['resources.loop']

# Connect to Admin Server
connect(username, password, url)
adminServerName = cmo.adminServerName
logger.info( "Connected to = " + url )
logger.info( "adminServerName = " + adminServerName )

try:
        logger.info ("Give a try ...")
        domainName = cmo.name
        cd("Servers/%s" % adminServerName)
        adminServer = cmo

        def updatedbsource(dsName,dsInitCapacity,dsMinCapacity,dsMaxCapacity,dsReadTimeout,dsConnectTimeout):
          logger.info( 'Begining updatedbsource for ' + dsName )
          startTransaction()
          try:
            startTransaction()
            cd('/JDBCSystemResources/' + dsName + '/JDBCResource/' + dsName + '/JDBCConnectionPoolParams/' + dsName )
            if dsInitCapacity is not None:
              cmo.setInitialCapacity(dsInitCapacity)
            if dsMinCapacity is not None:
              cmo.setMinCapacity(dsMinCapacity)
            if dsMaxCapacity is not None:
              cmo.setMaxCapacity(dsMaxCapacity)

            if dsConnectTimeout is not None:
              cd('/JDBCSystemResources/'+dsName+'/JDBCResource/'+dsName+'/JDBCDriverParams/'+dsName+'/Properties/'+dsName)
              try:
                logger.info ( 'after destroying property oracle.net.CONNECT_TIMEOUT')
                cmo.destroyProperty(getMBean('/JDBCSystemResources/'+dsName+'/JDBCResource/'+dsName+'/JDBCDriverParams/SOADataSource/Properties/'+dsName+'/Properties/or
acle.net.CONNECT_TIMEOUT'))
                logger.info ( 'before destroying property oracle.net.CONNECT_TIMEOUT')
              except:
                pass

              try:
                cmo.createProperty('oracle.net.CONNECT_TIMEOUT')
              except:
                pass

              cd('/JDBCSystemResources/'+dsName+'/JDBCResource/'+dsName+'/JDBCDriverParams/'+dsName+'/Properties/'+dsName+'/Properties/oracle.net.CONNECT_TIMEOUT')
              logger.info ( 'Setting value for oracle.net.CONNECT_TIMEOUT:' + dsConnectTimeout)
              cmo.setValue(dsConnectTimeout)



            if dsReadTimeout is not None:
              cd('/JDBCSystemResources/'+dsName+'/JDBCResource/'+dsName+'/JDBCDriverParams/'+dsName+'/Properties/'+dsName)
              try:
                logger.info ( 'after destroying property oracle.jdbc.ReadTimeout')
                cmo.destroyProperty(getMBean('/JDBCSystemResources/'+dsName+'/JDBCResource/'+dsName+'/JDBCDriverParams/SOADataSource/Properties/'+dsName+'/Properties/or
acle.jdbc.ReadTimeout'))
                logger.info ( 'after destroying property oracle.jdbc.ReadTimeout')
              except:
                pass

              try:
                cmo.createProperty('oracle.jdbc.ReadTimeout')
              except:
                pass

              cd('/JDBCSystemResources/'+dsName+'/JDBCResource/'+dsName+'/JDBCDriverParams/'+dsName+'/Properties/'+dsName+'/Properties/oracle.jdbc.ReadTimeout')
              logger.info ( 'Setting value for oracle.jdbc.ReadTimeout:' +dsReadTimeout)
              cmo.setValue(dsReadTimeout)

            endTransaction()
          except Exception,e:
            logger.info( 'error in updatedbsource for ' + dsName + '\n' + str(e))
            pass
          logger.info( 'Ending updatedbsource for ' + dsName )


        #####################################################################
        #
        #   CsrConnectionPool : jdbc/CsrDataSource : xa
        #   Datasource classname: oracle.jdbc.xa.client.OracleXADataSource
        #   Resource Type: javax.sql.XADataSource
        #   JDBC URL: jdbc:oracle:thin:@ldohsbcmh005.oracleoutsourcing.com:10710:DBCM2O
        #   user: XRS_APP
        #   password: XRS_aPp_HLbrt01
        #
        ####################################################################
        def createdbsource(dsName,dsJNDIName,dsURL,dsPassword,dsUserName,dsTestQuery,xaType,dsTargets,nonxaTransaction,dsMaxCapacity=None,dsInitCapacity=None,dsMinCapac
ity=None,XaSetTransactionTimeout=None):
          try:
            startTransaction()
            cd('/')
            cmo.createJDBCSystemResource(dsName)
            cd('/JDBCSystemResources/' + dsName + '/JDBCResource/' + dsName)
            cmo.setName(dsName)

            cd('/JDBCSystemResources/' + dsName + '/JDBCResource/' + dsName + '/JDBCDataSourceParams/' + dsName )
            set('JNDINames',jarray.array([String('jdbc/' + dsJNDIName )], String))

            cd('/JDBCSystemResources/' + dsName + '/JDBCResource/' + dsName + '/JDBCDriverParams/' + dsName )

            cmo.setUrl(dsURL)

            if  xaType == 'xa':
              cmo.setDriverName("oracle.jdbc.xa.client.OracleXADataSource")

            if  xaType == 'nonxa':
              cmo.setDriverName("oracle.jdbc.OracleDriver")

            cmo.setPassword( dsPassword)

            cd('/JDBCSystemResources/' + dsName + '/JDBCResource/' + dsName + '/JDBCConnectionPoolParams/' + dsName )
            cmo.setTestTableName(dsTestQuery)

            if dsMaxCapacity is not None:
              logger.info ( 'setting cmo.setMaxCapacity: ' + str(dsMaxCapacity) )
              cmo.setMaxCapacity(dsMaxCapacity)
              logger.info( 'retrieved Max ' + str(cmo.getMaxCapacity()) )

            if dsMinCapacity is not None:
              logger.info ( 'setting cmo.setMinCapacity: ' + str(dsMinCapacity) )
              cmo.setMinCapacity(dsMinCapacity)
              logger.info( 'retrieved Min ' + str(cmo.getMinCapacity()) )

            if dsInitCapacity is not None:
              logger.info ( 'setting cmo.setInitialCapacity: ' + str(dsInitCapacity) )
              cmo.setInitialCapacity(dsInitCapacity)
              logger.info( 'retrieved Initial ' + str(cmo.getInitialCapacity()) )

            cd('/JDBCSystemResources/' + dsName + '/JDBCResource/' + dsName + '/JDBCDriverParams/' + dsName + '/Properties/' + dsName )
            cmo.createProperty('user')

            cd('/JDBCSystemResources/' + dsName + '/JDBCResource/' + dsName + '/JDBCDriverParams/' + dsName + '/Properties/' + dsName + '/Properties/user')
            cmo.setValue(dsUserName)

            if  xaType == 'nonxa':
              logger.info( "nonxaTransaction =  "+nonxaTransaction )
              cd('/JDBCSystemResources/' + dsName + '/JDBCResource/' + dsName + '/JDBCDataSourceParams/' + dsName )
              cmo.setGlobalTransactionsProtocol(nonxaTransaction)

            if  xaType == 'xa':
              cd('/JDBCSystemResources/' + dsName + '/JDBCResource/' + dsName + '/JDBCXAParams/' + dsName )
              logger.info( ' In XaSetTransactionTimeout processing: ' + str(XaSetTransactionTimeout) )
              if XaSetTransactionTimeout is not None:
                cmo.setXaSetTransactionTimeout(XaSetTransactionTimeout)
                logger.info( 'setting XaSetTransactionTimeout to: ' + str(XaSetTransactionTimeout) )

            logger.info ( "dsTargets =  "+dsTargets )
            targetListObj = []
            targetListStr = dsTargets.split(',')
            for targetStr in targetListStr:
              targetObj = targetStr.split(":")
              logger.info ( "targetStr="+targetStr )
              targetListObj.append(ObjectName('com.bea:Name=' + targetObj[0] + ',Type=' + targetObj[1]))
              logger.info( "targetName-targetType="+targetObj[0]+"-"+targetObj[1] )

            cd('/SystemResources/' + dsName )
            set('Targets',jarray.array(targetListObj, ObjectName))
            endTransaction()
          except:
            logger.info('Skipping create and rolling backedit')
            cancelEdit(defaultAnswer="true")
            pass

        def startTransaction():
          edit()
          startEdit()

        def endTransaction():
          save()
          activate(block="false")

        def deleteIgnoringExceptions(mbean):
          try: delete(mbean)
          except: pass

        def loopit():
          logger.info ( "loopit called unit test" )

        ########################################################################
        #         Main Controller
        ########################################################################
        #print 'Task = '+resources_loop
        logger.info ('Task = '+resources_loop )

        mylist = resources_loop.split(",")

        num = 0
        while num < len(mylist):
          num = num + 1
          action = properties['db.action'+'_'+str(num)]
          #print "Action to Perform "+action
          logger.info( "Action to Perform "+action )

          if action == 'delete':
            dbName = properties['db.name'+'_'+str(num)]
            #print "Deleting "+dbName
            logger.info( "Deleting "+dbName )
            startTransaction()
            cd("/JDBCSystemResources")
            deleteIgnoringExceptions(dbName)
            endTransaction()
            logger.info ( "Done Deleting "+dbName )
          elif action == 'update':
            dbName = properties['db.name'+'_'+str(num)]
            logger.info ("START Updating "+dbName)
            try:
                logger.info( 'processing db.initCapacity_'+str(num) )
                dbInitCapacity = int(properties['db.initCapacity'+'_'+str(num)])
                logger.info( dbInitCapacity )
            except KeyError:
                dbInitCapacity = None
                logger.info( 'no Key db.InitCapacity'+'_'+str(num) )

            try:
                logger.info( 'processing db.maxCapacity_'+str(num) )
                dbMaxCapacity = int(properties['db.maxCapacity'+'_'+str(num)])
                logger.info( dbMaxCapacity )
            except KeyError:
                dbMaxCapacity = None
                logger.info( 'no Key db.maxCapacity'+'_'+str(num) )

            try:
                logger.info( 'processing db.minCapacity_'+str(num) )
                dbMinCapacity = int(properties['db.minCapacity'+'_'+str(num)])
                logger.info( dbMinCapacity )
            except KeyError:
                dbMinCapacity = None
                logger.info( 'no Key db.minCapacity'+'_'+str(num) )

            try:
                logger.info( 'processing db.connectTimeout_'+str(num) )
                dbconnectTimeout = properties['db.connectTimeout'+'_'+str(num)]
                logger.info( dbconnectTimeout )
            except KeyError:
                dbconnectTimeout = None
                logger.info( 'no Key db.connectTimeout'+'_'+str(num) )

            try:
                logger.info( 'processing db.readTimeout_'+str(num) )
                dbreadTimeout = properties['db.readTimeout'+'_'+str(num)]
                logger.info( dbreadTimeout )
            except KeyError:
                dbreadTimeout = None
                logger.info( 'no Key db.readTimeout'+'_'+str(num))

            updatedbsource(dsName=dbName,
              dsInitCapacity=dbInitCapacity,
              dsMinCapacity=dbMinCapacity,
              dsMaxCapacity=dbMaxCapacity,
              dsReadTimeout=dbreadTimeout,
              dsConnectTimeout=dbconnectTimeout);
            exit()
            logger.info ( "END   Updating "+dbName)
          elif action == 'create':
            dbTargets = properties['db.targets'+'_'+str(num)]
            dbType = properties['db.type'+'_'+str(num)]
            jndiName = properties['db.jndiname'+'_'+str(num)]
            dbName = properties['db.name'+'_'+str(num)]
            dbURL = properties['db.url'+'_'+str(num)]
            dbUserName = properties['db.username'+'_'+str(num)]
            dbPassWord = properties['db.password'+'_'+str(num)]
            dbTransaction = properties['db.transaction'+'_'+str(num)]
            dbTest = properties['db.test.query'+'_'+str(num)]
            logger.info( "Creating "+dbName )
            try:
                logger.info ('processing db.maxCapacity_'+str(num) )
                dbMaxCapacity = int(properties['db.maxCapacity'+'_'+str(num)])
                logger.info ( dbMaxCapacity )
            except KeyError:
                dbMaxCapacity = None
                logger.info ( 'no Key db.maxCapacity'+'_'+str(num) )

            try:
                logger.info( 'processing db.initCapacity_'+str(num) )
                dbInitCapacity = int(properties['db.initCapacity'+'_'+str(num)])
                logger.info( dbInitCapacity )
            except KeyError:
                dbInitCapacity = None
                logger.info( 'no Key db.InitCapacity'+'_'+str(num) )

            try:
                logger.info( 'processing db.minCapacity_'+str(num) )
                dbMinCapacity = int(properties['db.minCapacity'+'_'+str(num)])
                logger.info( dbMinCapacity )
            except KeyError:
                dbMinCapacity = None
                logger.info( 'no Key db.minCapacity'+'_'+str(num) )


          try:
                logger.info ( 'processing db.transactionTimeout_'+str(num) )
                dbXaSetTransactionTimeout = (properties['db.xatransactionTimeout'+'_'+str(num)].lower() == "true")
                logger.info ( dbXaSetTransactionTimeout )
            except KeyError:
                dbXaSetTransactionTimeout = None
                logger.info ( 'no Key db.transactionTimeout'+'_'+str(num) )

            createdbsource(dsName=dbName,
              dsJNDIName=jndiName,
              dsURL=dbURL,
              dsPassword=dbPassWord,
              dsUserName=dbUserName,
              dsTestQuery=dbTest,
              xaType=dbType,
              dsTargets=dbTargets,
              nonxaTransaction=dbTransaction,
              dsMaxCapacity=dbMaxCapacity,
              dsInitCapacity=dbInitCapacity,
              dsMinCapacity=dbMinCapacity,
              XaSetTransactionTimeout=dbXaSetTransactionTimeout);
            logger.info( "Done Creating DataSource "+dbName )

          else:
            logger.info ( "Not Deleting or Create iteration="+str(num)+" action="+action )

except NameError, e:
        logger.info ( "Please check there is: ", sys.exc_info()[0], sys.exc_info()[1] )
        cancelEdit("n")
        raise

except:
        dumpStack()
        cancelEdit("n")
        raise
logger.info ("Disconnecting")
disconnect(force="True")

print "exit"
exit()

3) Run WLST script by invoking wlst.sh  :  wlst.sh   dataSourceCreate_update_delete.py
dataSourceCreate_update_delete.properties