Showing posts with label customization. Show all posts
Showing posts with label customization. Show all posts

Friday, November 4, 2011

OSB, customizing the customization file ALSBCustomizationFile.xml

I hate having to modify the ALSBCustomizationFile.xml with tokens to be replaced or, even worse, maintain a separate ALSBCustomizationFile.xml per environment.

And I believe the "find and replace" strategy is weak and error-prone.

Better define in a separate file what you want to customize and its new value. One file per environment. Sweet and simple.

At last I can put all pieces together:


Your "mycustomizations.properties" file should be like this:

#ownerType.ownerPath.envValueType=newvalue
ProxyService:OSBProject1/ProxyService1:Service URI=/OSBProject1/ProxyServicePluto

and this is the Groovy code:


import groovy.xml.XmlUtil

/*
 * Lookup customization file
 * Search //cus:envValueAssignments[(cus:envValueAssignments/xt:owner/xt:type/text() == $1 
 *          AND //cus:envValueAssignments/xt:owner/xt:path/text() = $2)][xt:envValueType == $3]
 * and replace their xt:value with $4
 *  
 */

def customizations = new XmlSlurper().parse("ALSBCustomizationFile.xml").declareNamespace(xt: 'http://www.bea.com/wli/config/xmltypes',xsi: 'http://www.w3.org/2001/XMLSchema-instance', cus : 'http://www.bea.com/wli/config/customizations')

//println XmlUtil.serialize( customizations )

File theInfoFile = new File("mycustomizations.properties")

theInfoFile.eachLine { line ->
  if ( (line.trim().size() == 0) || (line.trim().startsWith("#")) ) {
   // ignore
  } else {
    words = line.split("=")
    keys = words[0].split(":")
    value = words[1]

  ownerType = keys[0]
  ownerPath = keys[1]
  envValueType = keys[2]
  
  customizations.'cus:customization'.each {

   if (it.'@xsi:type' == "cus:EnvValueCustomizationType") {
    println "FOUND"
    for (item in it.'cus:envValueAssignments') {
     if ( (item.'xt:envValueType' == envValueType) &&  (item.'xt:owner'.'xt:type' = ownerType) &&  (item.'xt:owner'.'xt:path' = ownerPath) ) {
      println "ITEM " + envValueType + " " + ownerType + " " + ownerPath + ", before is " + item.'xt:value'
      item.'xt:value'.replaceBody(value)
      println "ITEM " + envValueType + " " + ownerType + " " + ownerPath + ",  after is " + item.'xt:value'
     }
    }
   } // if
  } // each
   } // if else
}
 

println XmlUtil.serialize( customizations )



Groovy is great but not intuitive and self-explanatory to use.... Groovy plugin for Eclipse does code completion but can't introspect the runtime type of a variable, of course...

Friday, August 12, 2011

OSB customization from a environment dependent property file with WLST

I proceed as follows:

- create customization file from OSB console
- replace all environment dependent values (mostly URIs) with tokens:

{$REPLACE_PROPERTY_MQ_QUEUE}

- create a import.properties."env" file ("env" depends on the environment you are targetting)

in this property file you have:

adminUrl=t3://localhost:7009
importUser=pierluigi
importPassword=welcome1

customizationFile=ALSBCustomizationFile.xml

REPLACE_PROPERTY_MQ_QUEUE=VALUE_TO_BE_USED_IN_THIS_ENV
#here all other properties, they must start with REPLACE_PROPERTY_
REPLACE_PROPERTY_HOST=acme.com


run the customize.py script :

cd $DOMAIN_HOME/wlstscripts

. $DOMAIN_HOME/bin/setDomainEnv.sh

java weblogic.WLST customize.py dev


for tst, the file will be import.properties.tst and you call

java weblogic.WLST customize.py tst

customize.py (largely copied from import.py provided by Oracle):

from java.util import HashMap
from java.util import HashSet
from java.util import ArrayList
from java.io import FileInputStream

from com.bea.wli.sb.util import Refs
from com.bea.wli.config.customization import Customization
from com.bea.wli.sb.management.importexport import ALSBImportOperation

import fileinput


import sys

#=======================================================================================
# Entry function to customize a ALSB domain
#=======================================================================================

def customizeDomain(envname):
    try:
        SessionMBean = None
        importConfigFile = 'import.properties.' + envname
        print 'Loading Deployment config from :', importConfigFile
        exportConfigProp = loadProps(importConfigFile)
        adminUrl = exportConfigProp.get("adminUrl")
        importUser = exportConfigProp.get("importUser")
        importPassword = exportConfigProp.get("importPassword")

        customFile = exportConfigProp.get("customizationFile")

        connectToServer(importUser, importPassword, adminUrl)

        print 'Attempting to customize ALSB Admin Server listening on :', adminUrl


        configProperties = loadProps('import.properties.' + envname)

        #select only properties starting with REPLACE_
        mylist = Properties()
        for property in configProperties:
            if property.startswith('REPLACE_'):
                mylist.put(property, configProperties.get(property))



        targetCustomizationFile = customFile + envname + '.xml'	 

        output=open(targetCustomizationFile, 'w')

        #read all lines and replace all tokens
        for line in fileinput.input([customFile]):
           for property in mylist:
               line = line.replace('{$' + property + '}', mylist.get(property))
           output.write(line)

        output.close()

		
		
        sessionName = createSessionName()
        print 'Created session', sessionName
        SessionMBean = getSessionManagementMBean(sessionName)
        print 'SessionMBean started session'
        ALSBConfigurationMBean = findService(String("ALSBConfiguration.").concat(sessionName), "com.bea.wli.sb.management.configuration.ALSBConfigurationMBean")
        print "ALSBConfiguration MBean found", ALSBConfigurationMBean
       

        #customize if a customization file is specified
        #affects only the created resources
        if customFile != None :
            print 'Loading customization File', targetCustomizationFile
            iStream = FileInputStream(targetCustomizationFile)
            customizationList = Customization.fromXML(iStream)
            ALSBConfigurationMBean.customize(customizationList)

        SessionMBean.activateSession(sessionName, "Complete customization using wlst")

    except:
        print "Unexpected error:", sys.exc_info()[0]
        if SessionMBean != None:
            SessionMBean.discardSession(sessionName)
        raise

#=======================================================================================
# Utility function to load properties from a config file
#=======================================================================================

def loadProps(configPropFile):
    propInputStream = FileInputStream(configPropFile)
    configProps = Properties()
    configProps.load(propInputStream)
    return configProps

#=======================================================================================
# Connect to the Admin Server
#=======================================================================================

def connectToServer(username, password, url):
    connect(username, password, url)
    domainRuntime()


#=======================================================================================
# Utility function to create an arbitrary session name
#=======================================================================================
def createSessionName():
    sessionName = String("SessionScript"+Long(System.currentTimeMillis()).toString())
    return sessionName

#=======================================================================================
# Utility function to load a session MBeans
#=======================================================================================
def getSessionManagementMBean(sessionName):
    SessionMBean = findService("SessionManagement", "com.bea.wli.sb.management.configuration.SessionManagementMBean")
    SessionMBean.createSession(sessionName)
    return SessionMBean



# IMPORT script init
try:
    # import the service bus configuration
    # argv[1] is the environment you are customizing
    customizeDomain(sys.argv[1])

except:
    print "Unexpected error: ", sys.exc_info()[0]
    dumpStack()
    raise





The WLST task can be run from Ant of course...