Thursday, November 29, 2012

Remote archiving with FTP Adapter (JCA)

The file archiving location can be local or remote. To enable the remote archiving in the FTP adapter add the property  UseRemoteArchive with value as true to the jca file.

Apart from the above change ensure the LogicalArchiveDirectory/PhysicalArchiveDirectory is existing on the FTP server and the folders have write permission enabled



<adapter-config name="ReadOperation" adapter="Ftp Adapter" wsdlLocation="ReadOperation.wsdl" xmlns="http://platform.integration.oracle/blocks/adapter/fw/metadata">
 
  <connection-factory location="eis/ftp/TestFTP" UIincludeWildcard="Process*.txt" adapterRef=""/>
  <endpoint-activation portType="Get_ptt" operation="Get">
    <activation-spec className="oracle.tip.adapter.ftp.inbound.FTPActivationSpec">
      <property name="FileType" value="ascii"/>
      <property name="UseHeaders" value="false"/>
      <property name="AsAttachment" value="true"/>
      <property name="LogicalDirectory" value="inbound"/>
      <property name="UseRemoteArchive" value="true"/>
      <property name="Recursive" value="true"/>
      <property name="LogicalArchiveDirectory" value="archive"/>
      <property name="DeleteFile" value="true"/>
      <property name="IncludeFiles" value="Process.*\.txt"/>
      <property name="PollingFrequency" value="30"/>
      <property name="MinimumAge" value="0"/>
         </activation-spec>
  </endpoint-activation>

</adapter-config>

Cannot call Connection.rollback in distributed transaction. Transaction Manager will commit the resource manager when the distributed transaction is committed

If we take care the configuration details for the data source and connection pool, often transaction roll back exceptions can be avoided

For e.g the below error happened due to the incorrect configuration of d atasource

Internal Exception: java.sql.SQLException: Cannot call Connection.rollback in distributed transaction.  Transaction Manager will commit the resource manager when the distributed transaction is committed

In such situations verify the connection pool and check the type of datasource whether it is XA or non-XA.

If a non-XA data source is used in the connection pool, ensure you unchecked the 'Supports Global Transactions' option in the data source configuration





Wednesday, November 28, 2012

ORA-28001: the password has expired

There is an expiry date for the passwords we set for user account in oracle. Once the password expired the SOA infra will fail to load.

We can check the account status using

select USERNAME,ACCOUNT_STATUS,EXPIRY_DATE from dba_users where USERNAME  like '%DEV%'

If any of the user account_status is expired, using the following query we can see the values for PASSWORD_LIFE_TIME and PASSWORD_GRACE_TIME

SELECT * FROM dba_profiles WHERE profile = 'DEFAULT' AND resource_type = 'PASSWORD'




Set these values to unlimited using the query


ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;

ALTER PROFILE DEFAULT LIMIT PASSWORD_GRACE_TIME  UNLIMITED;



After this for every user name set the new password as follows

 alter user <username> identified by <password>;
 for eg.
 alter user DEV1_ESS identified by manager;

Now execute the query once again to see the account status
select USERNAME,ACCOUNT_STATUS,EXPIRY_DATE from dba_users where USERNAME  like '%DEV%'




Friday, November 16, 2012

Testing a secured proxy service from OSB test console

In the previous blogs I had mentioned how to secure a proxy service using the username token policy. In this article I am going to explain how to test a secured service from the osb test console.

Step1:  In the OSB console using the security configuration create a new user account as follows.
                                                    username - test_user
                                                    password - welcome1


Step2 : Now a key store has to be configured in the em console. Prior to that create a key store (testks.jks) as follows


 Step 3: In the emconsole goto the domain and on the right click menu goto Security->Security Provider Configuration



 
  Step 4: Configure the above created key store as follows

 provide the password as welcome1 for every highlighted item

Save and restart the server. The restart is mandatory to effect the changes done.

Step5 : Create a credential key. In the em console goto the domain->rightclick->Security->Credentials
Step6 : Create a Security Map called oracle.wsm.security , if it not existing

Under this map create a new security key as follows


Now we are ready to test the OSB service from the test console. Open the test console
In the override attribute section provide the security key as test_user and then click the execute button.

Now we can see a SOAP Header is attached to the request and the service executed successfully.




Monday, November 12, 2012

List all the deployed composites

It will be handy if we have a script to list all the deployed composites belong to a partition. Here is a sample

Step1:

Create a property file as follows

=============Env.properties====================


url=t3://localhost:7001
server=localhost
port=8001
username=weblogic
password=weblogic1
PARTITIONS=default,masterdata,marketing


============end of Env.properties==================

Step 2 :

Create the following python script

=================ListDeployedComposites.py=========

from java.io import FileInputStream

try:
propInputStream = FileInputStream("D:\\tech\\wlst\\Env.properties")
configProps = Properties()
configProps.load(propInputStream)
except NameError, e:
print 'EXCEPTION OCCURED'
print 'Please check there is: ', sys.exc_info()[0], sys.exc_info()[1]
else:
print 'properties loaded properly'
print 'configProps',configProps
url = configProps.get("url")
print 'url=', url
server = configProps.get("server")
print 'server=', server
port = configProps.get("port")
print 'port=', port
username = configProps.get("username")
print 'username=', username
password = configProps.get("password")
print 'password = ', password

partitions = configProps.get("PARTITIONS")
print 'partitions = ', partitions


print '========================'
partitionList = partitions.split(",")
count = 0
for i in partitionList:
try:
sca_listCompositesInPartition(server,port,username,password,partitionList[count])
except NameError, e:
print 'EXCEPTION OCCURED'
print "Please check there is: ", sys.exc_info()[0], sys.exc_info()[1]
count = count+1

============= end of ListDeployedComposites.py==========

Step 3:
Start the wlst command as follows
D:\Oracle\Middleware\Oracle_SOA1\common\bin>wlst.cmd
Run the script from wlst prompt as follows
wls:/offline> execfile('D:\\tech\wlst\\ListDeployedComposites.py')

Result:

Following 21 composites are currently deployed to the platform, in partition: default.

1. AIAB2BInterface[1.0], partition=default, mode=active, state=on, isDefault=true, deployedTime=2012-06-08T09:03:08.211Z
2. ProductionRecipeResponseEBS[1.0], partition=default, mode=active, state=on, isDefault=true, deployedTime=2012-10-10T09:59:04.233Z
3. SyncProductionRecipeListEbizProvABCSImpl[1.0], partition=default, mode=active, state=on, isDefault=true, deployedTime=2012-10-10T
4. SyncSpecPLM4PAdapter[1.0], partition=default, mode=active, state=on, isDefault=true, deployedTime=2012-10-10T09:54:10.927Z
5. SyncRecipeListEbizAdapter[1.0], partition=default, mode=active, state=on, isDefault=true, deployedTime=2012-10-10T09:59:49.244Z
6. SyncItemListEbizProvABCSImpl[1.0], partition=default, mode=active, state=on, isDefault=true, deployedTime=2012-10-10T10:03:57.380
7. ItemResponseEBSV2[1.0], partition=default, mode=active, state=on, isDefault=true, deployedTime=2012-10-10T09:57:59.963Z
8. TransformAppContextEbizService[1.0], partition=default, mode=active, state=on, isDefault=true, deployedTime=2012-10-10T10:00:21.9
9. SyncItemListEbizAdapter[1.0], partition=default, mode=active, state=on, isDefault=true, deployedTime=2012-10-10T09:59:28.608Z
10. ProductionRecipeEBS[1.0], partition=default, mode=active, state=on, isDefault=true, deployedTime=2012-10-10T09:58:45.184Z
11. AgToAGPollingTest[1.0], partition=default, mode=active, state=off, isDefault=true, deployedTime=2012-08-09T11:48:04.849Z
12. SimpleApproval[1.0], partition=default, mode=active, state=on, isDefault=true, deployedTime=2012-05-21T15:51:27.432+05:30
13. AIAErrorTaskAdministrationProcess[1.0], partition=default, mode=active, state=on, isDefault=true, deployedTime=2012-06-08T08:53:
14. AIAB2BErrorHandlerInterface[1.0], partition=default, mode=active, state=on, isDefault=true, deployedTime=2012-06-08T09:04:31.440
15. SampleCursorRef[1.0], partition=default, mode=retired, state=on, isDefault=true, deployedTime=2012-11-02T16:00:17.268+05:30
16. AIAReadJMSNotificationProcess[1.0], partition=default, mode=active, state=on, isDefault=true, deployedTime=2012-06-08T09:00:29.4
17. FirstBPEL[1.0], partition=default, mode=active, state=on, isDefault=true, deployedTime=2012-11-09T21:26:47.672+05:30
18. ReloadProcess[1.0], partition=default, mode=retired, state=on, isDefault=true, deployedTime=2012-06-08T09:02:14.366Z
19. AIAAsyncErrorHandlingBPELProcess[1.0], partition=default, mode=active, state=on, isDefault=true, deployedTime=2012-06-08T09:01:2
20. QueryResponsibilityEbizAdapter[1.0], partition=default, mode=active, state=on, isDefault=true, deployedTime=2012-10-10T09:52:36.
21. SyncSpecPLM4PReqABCSImpl[1.0], partition=default, mode=active, state=on, isDefault=true, deployedTime=2012-10-10T10:02:53.116Z





start/stop/activate/retire composites using wlst

Here is a script for doing the state change for a deployed composite. This is a generic python script which will cater the requirement for start/stop/retire/activate any number of composites at a time

Step1 :
Create a property file, specify the server connection details, the list of composites and the action required on them

========= composite.properties ==================

url=t3://localhost:7001
host=localhost
port=8001
username=weblogic
password=weblogic1

COMPOSITES=default/SampleCursorRef/1.0,default/ReloadProcess/1.0
operation=retire

========== end of composite.properties =============

Step 2 :
Create the following python script

=================StateChange.py===============
from java.io import FileInputStream
propInputStream = FileInputStream("D:\\tech\\wlst\\composite.properties")
configProps = Properties()
configProps.load(propInputStream)
url = configProps.get("url")
print 'url=', url
host = configProps.get("host")
print 'host=', host
port = configProps.get("port")
print 'port=', port
username = configProps.get("username")
print 'username=', username
password = configProps.get("password")
print 'password = ', password
operation = configProps.get("operation")
print 'operation = ', operation

print '========================'
print 'host=', host
COMPOSITES = configProps.get("COMPOSITES")
print 'COMPOSITES = ', COMPOSITES
print 'host=', host
compositeList=COMPOSITES.split(',')
print compositeList[1]
count = 0
for i in compositeList:
   compositeProps = compositeList[count].split("/")
   partition = compositeProps[0]
   compoisteName = compositeProps[1]
   version = compositeProps[2]
   print 'partition ..',partition
   print 'newPartition..',newPartition
   print 'compoisteName ..',compoisteName
   print 'version ..',version
   print '========================'
   
   print 'trying to  ',operation ,'the', compoisteName
   try:
if operation=='start':
sca_startComposite(host, port, username, password, compoisteName, version)
elif operation=='stop':
sca_stopComposite(host, port, username, password, compoisteName, version)
elif operation=='activate':
sca_activateComposite(host, port, username, password, compoisteName, version)
elif operation=='retire':
sca_retireComposite(host, port, username, password, compoisteName, version)
else:
   print '=======DO NOTHING ========='
   except NameError, e:
print 'EXCEPTION OCCURED'
print "Please check there is: ", sys.exc_info()[0], sys.exc_info()[1]
   else:
print 'Completed the action on ',compoisteName
   count = count+1
=================end of StateChange.py============

Step3: Open a command promt and start the wslt command from D:\Oracle\Middleware\Oracle_SOA1\common\bin as follows  

D:\Oracle\Middleware\Oracle_SOA1\common\bin>wlst.cmd

This will start the wslt engine . Now execute the python script from the wlst prompt as follows
wls:/offline> execfile('D:\\tech\wlst\\StateChange.py')

To do start/stop/activate change the value for operation in the composite.properties file

Sample result
===================== 
trying to   retire the ReloadProcess
host = localhost
port = 8001
user = weblogic
partition = default
compositeName = ReloadProcess
revision = 1.0
label =  None
compositeDN =default/ReloadProcess!1.0
Connecting to: service:jmx:t3://localhost:8001/jndi/weblo
Composite (default/ReloadProcess!1.0) is successfully ret
Completed the action on  ReloadProcess
=======================================


Friday, November 9, 2012

Securing OSB proxy service

Security is an important aspect in the webservice domain. Let us see how to secure an OSB proxy service using OWSM

Create a OWSM enabled osb domain


Create a proxy service. Add the security policy as shown below

Enable the Header Processing as below

Save and Activate the changes in the osb console.

Now test the service from Test Console without passing the SOAP Header

It will throw an error as shown below

The service cannot be invoked without passing user credentials as part of SOAP Header.


Now lets see how to invoke this secured service from BPEL 

Create a partner link for the above OSB service in the BPEL.

In the composite.xml design view select the partnerlink

Right click on the partner link and select the Configure WS Policies option

Choose the wss_username_token_client_policy for the Security field

In the property inspector window, go to binding property section and click on the add button.


Add two new properties for username and password with appropriate values for the properties

Now the composite.xml will appear like as shown below. 



Deploy and test the BPEL. Now this BPEL will successfully invoke the secured OSB proxy service


Thursday, November 8, 2012

OSB Remote Archive with FTP protocol

Sometimes while using FTP protocol in OSB we want to place the archive the files to the remote directory in the FTP server. In such situations enable the remote streaming option in the FTP Transport Configuration. Give a valid directory name(which exists in the FTP server) for the Archive Directory field


Wednesday, November 7, 2012

Read file content. Write content to file

Simple utility methods for reading from and writing to a file


public static String readFile(File file) throws Exception
{
 BufferedReader br = null;
 java.io.FileReader fr = null;
 try {
 fr = new java.io.FileReader(file);
 br = new BufferedReader(fr);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
throw new FileNotFoundException(e.getMessage());
}
StringBuffer sb = new StringBuffer();
String str= null;
try
{
while((str=br.readLine()) != null)
{
 sb.append(str);
 sb.append("\n");
}

}
    catch(Exception e)
{
e.printStackTrace();
throw new Exception(e.getMessage());
}
    finally
    {
    try {
    fr.close();
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    }
    return sb.toString();
  }
public static void writeFile(File file,String content) throws Exception
{
BufferedWriter out=null;
     try{
       // Create file
       FileWriter fstream = new FileWriter(file);
           out = new BufferedWriter(fstream);
       out.write(content);
       //Close the output stream
       out.close();
       }catch (Exception e){//Catch exception if any
         System.err.println("Error: " + e.getMessage());
         throw new Exception(e.getMessage());
       }
       finally
       {
        if(out != null)
        {
        try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
        }
       }
}

Remove namespace from xml

Sometime we might need to remove all the namespaces from an xml document.

Here is piece of java code which does that job !!


public static String removeNamespaces(String s)
 {
     Transformer transformer = null;
     try
     {
         transformer = templates.newTransformer();
     }
     catch(TransformerConfigurationException transformerconfigurationexception)
     {
         System.err.println("Error transforming XML");
         transformerconfigurationexception.printStackTrace();
         return null;
     }
     StringReader stringreader = new StringReader(s);
     StringWriter stringwriter = new StringWriter();
     try
     {
         transformer.transform(new StreamSource(stringreader), new StreamResult(stringwriter));
         return stringwriter.toString();
     }
     catch(TransformerException transformerexception)
     {
         System.err.println("Error transforming XML");
         transformerexception.printStackTrace();
         return null;
     }
 }

wlst script for stopping the composites

Often it will be handy if we have a wlst script to stop and start the deployed composites. This will be useful if we have many composites to be switched off and on frequently

Keep the server details and the list of composites to be stopped in a properties file in a local directory - deploydirectory

CompositeList.properties
==================================



url=t3://localhost:7001
host=localhost
port=8001
username=weblogic
password=weblogic1


COMPOSITES=default/SampleCursorRef/1.0,default/AgToAGPollingTest/1.0,default/ReloadProcess/1.0


=================== end of compositeList.properties==============

Create a wlst script as follows

ShutdownComposite.py
====================

from java.io import FileInputStream

propInputStream = FileInputStream("D:\\tech\\wlst\\compositeList.properties")
configProps = Properties()
configProps.load(propInputStream)

url = configProps.get("url")
print 'url=', url
host = configProps.get("host")
print 'host=', host
port = configProps.get("port")
print 'port=', port
username = configProps.get("username")
print 'username=', username
password = configProps.get("password")
print 'password = ', password


print '========================'

COMPOSITES = configProps.get("COMPOSITES")
print 'COMPOSITES = ', COMPOSITES

compositeList=COMPOSITES.split(',')
print compositeList[1]
count = 0
for i in compositeList:
   compositeProps = compositeList[count].split("/")
   partition = compositeProps[0]
   compoisteName = compositeProps[1]
   version = compositeProps[2]
   print 'partition ..',partition
   print 'compoisteName ..',compoisteName
   print 'version ..',version
   print '========================'

   print 'trying to stop ',compoisteName
   try:
sca_stopComposite(host, port, username, password, compoisteName, version)
   except NameError, e:
print 'EXCEPTION OCCURED'
print "Please check there is: ", sys.exc_info()[0], sys.exc_info()[1]
   else:
print 'Stopped ',compoisteName
   count = count+1



============== end of StopComposites.py===============

open command prompt and start the wlst as follows


D:\Oracle\Middleware\Oracle_SOA1\common\bin>wlst.cmd

Run the script from wlst prompt as follows
execfile('D:\\tech\wlst\\ShutdownComposite.py')


Result
==============

========================
trying to stop  ReloadProcess
host = localhost
port = 8001
user = weblogic
partition = default
compositeName = ReloadProcess
revision = 1.0
label =  None
compositeDN =default/ReloadProcess!1.0
Connecting to: service:jmx:t3://localhost:8001/jndi/weblogic.management.mbeanservers.runtime
Composite (default/ReloadProcess!1.0) is successfully stopped.
Stopped  ReloadProcess





OSB deployment using scripts

We can deploy(import) osb project to sbconsole using the wlst script. Exporting of the project from sbconsole and from eclipse workspace also can be done using scripts. Here are the steps

Download import.py and export.py to a local directory(deploy directory)

Create a build properties file in the deploy directory as below.

build.properties
=============

fmw.home=D:/Oracle/Middleware

wls.username      = weblogic
wls.password      = weblogic1
wls.server        = t3://localhost:7001

# properties for workspace export
#config.project="OSB Configuration"
#config.jar=D:/temp/sbconfig.jar
#config.subprojects="ASynchronous"
#config.includeDependencies=true
#workspace.dir=C:/eclipse/user/workspace

# export properties

# specify a project or use None
#export.project    = EJB
export.project    = None
export.jar        = D:/temp/sbconfig.jar
#export.customFile = c:/temp/cust.xml
export.customFile = None

# import properties

# specify a project or use None
import.project    = None
#import.project    = EJB
import.jar        = D:/temp/sbconfig.jar
import.customFile = None
import.customFile = D:/temp/ALSBCustomizationFile.xml

==================end of build.properties==============
Create a build.xml file as below in the deploy.directory

build.xml
===============

<?xml version="1.0" encoding="windows-1252" ?>
<project name="ConfigExport">

<property file="./build.properties"/>
<property name="bea.home"               value="${fmw.home}"/>
<property name="build"                  value="build"/>
<property name="dist"                   value="dist"/>
<property name="domain.export.script"   value="export.py"/>
<property name="domain.import.script"   value="import.py"/>
<property name="eclipse.home" value="${fmw.home}/oepe_11gR1PS4"/>
<property name="export.config.file"     value="export.properties"/>
<property name="import.config.file"     value="import.properties"/>
<property name="metadata.dir" value="${workspace.dir}/.metadata"/>
<property name="osb.home" value="${fmw.home}/Oracle_OSB1"/>
<property name="weblogic.home" value="${fmw.home}/wlserver_10.3"/>

  <path id="class.path">
  <pathelement path="${bea.home}/wlserver_10.3/server/lib/weblogic.jar"/>
  <pathelement path="${bea.home}/Oracle_OSB1/lib/sb-kernel-api.jar"/>
  <pathelement path="${bea.home}/Oracle_OSB1/lib/sb-kernel-impl.jar"/>
        <pathelement path="${bea.home}/Oracle_OSB1/modules/com.bea.common.configfwk_1.6.0.0.jar"/>
  </path>


  <taskdef classpath="${bea.home}/wlserver_10.3/server/lib/weblogic.jar" name="wlst" classname="weblogic.ant.taskdefs.management.WLSTTask"/>


   <target name="exportFromWorkspace">
      <!--delete failonerror="false" includeemptydirs="true"
              dir="${metadata.dir}"/-->
      <java dir="${eclipse.home}"
            jar="${eclipse.home}/plugins/org.eclipse.equinox.launcher_1.1.1.R36x_v20101122_1400.jar"
            fork="true" failonerror="true" maxmemory="768m">
         <jvmarg line="-XX:MaxPermSize=256m"/>
         <arg line="-data ${workspace.dir}"/>
         <arg line="-application com.bea.alsb.core.ConfigExport"/>
         <arg line="-configProject ${config.project}"/>
         <arg line="-configJar ${config.jar}"/>
         <arg line="-configSubProjects ${config.subprojects}"/>
         <arg line="-includeDependencies ${config.includeDependencies}"/>
         <sysproperty key="weblogic.home" value="${weblogic.home}"/>
         <sysproperty key="osb.home" value="${osb.home}"/>
         <sysproperty key="osgi.bundlefile.limit" value="500"/>
         <sysproperty key="harvester.home" value="${osb.home}/harvester"/>
         <sysproperty key="osgi.nl" value="en_US"/>
         <sysproperty key="sun.lang.ClassLoader.allowArraySyntax" value="true"/>
      </java>
   </target>

  <target name="export">
    <echo message="exportscript: ${domain.export.script}"/>
    <java classname="weblogic.WLST" fork="true">
        <arg line="${domain.export.script} ${export.config.file}"/>
        <classpath refid="class.path"/>
    </java>
  </target>

  <target name="import">
    <echo message="importscript: ${domain.import.script}"/>
    <java classname="weblogic.WLST" fork="true">
        <arg line="${domain.import.script} ${import.config.file}"/>
        <classpath refid="class.path"/>
    </java>
  </target>

  <target name="clean">
    <delete dir="${dist}"/>
    <delete dir="${build}"/>
    <mkdir dir="${dist}"/>
    <mkdir dir="${build}"/>
  </target>

 
</project>

=========================== end of build.xml==============

Create an import.properties as below in the deploy directory

import.porperties
==============================

##################################################################
# OSB Admin Security Configuration                              #
##################################################################
adminUrl=t3://localhost:7001
importUser=weblogic
importPassword=weblogic1

##################################################################
# OSB Jar to be exported, optional customization file           #
##################################################################
importJar=D:/temp/sbconfig.jar
customizationFile=D:/temp/ALSBCustomizationFile.xml

##################################################################
# Optional passphrase and project name                           #
##################################################################
#passphrase=osb
#project=default
==================end of import.properties==============

Create a batch file to set the class path

deploy.bat
=============

set FMW_HOME=D:\Oracle\Middleware
set ANT_HOME=%FMW_HOME%\modules\org.apache.ant_1.7.1
set PATH=%ANT_HOME%\bin;%PATH%
set JAVA_HOME=C:\jdk1.7.0
set CLASSPATH=%FMW_HOME%/wlserver_10.3/server/lib/weblogic.jar;%FMW_HOME%/Oracle_OSB1/lib/alsb.jar;%FMW_HOME%/Oracle_OSB1/modules/com.bea.common.configfwk_1.6.0.0.jar

============== end of deploy.bat====================



Open command prompt and navigate to the deploy directory
Run the deploy.bat
To deploy/import run the command :  ant -verbose import
To export from workspace run the command :  ant -verbose exportFromWorkspace


export.py
============
from java.io import FileInputStream
from java.io import FileOutputStream
from java.util import ArrayList
from java.util import Collections
from com.bea.wli.sb.util import EnvValueTypes
from com.bea.wli.config.env import EnvValueQuery;
from com.bea.wli.config import Ref
from com.bea.wli.config.customization import Customization
from com.bea.wli.config.customization import FindAndReplaceCustomization
import sys
#====================================================================
# Utility function to load properties from a config file
#=========================================================================
def exportAll(exportConfigFile):
try:
print "Loading export config from :", exportConfigFile
exportConfigProp = loadProps(exportConfigFile)
adminUrl = exportConfigProp.get("adminUrl")
exportUser = exportConfigProp.get("exportUser")
exportPasswd = exportConfigProp.get("exportPassword")
exportJar = exportConfigProp.get("exportJar")
customFile = exportConfigProp.get("customizationFile")
passphrase = exportConfigProp.get("passphrase")
project = exportConfigProp.get("project")
connectToServer(exportUser, exportPasswd, adminUrl)
ALSBConfigurationMBean = findService("ALSBConfiguration", "com.bea.wli.sb.management.configuration.ALSBConfigurationMBean")
print "ALSBConfiguration MBean found"
print project
if project == None :
ref = Ref.DOMAIN
collection = Collections.singleton(ref)
if passphrase == None :
print "Export the config"
theBytes = ALSBConfigurationMBean.export(collection, true, None)
else:
print "Export and encrypt the config"
theBytes = ALSBConfigurationMBean.export(collection, true,passphrase)
else:
ref = Ref.makeProjectRef(project);
print "Export the project", project
collection = Collections.singleton(ref)
theBytes = ALSBConfigurationMBean.exportProjects(collection,passphrase)
aFile = File(exportJar)
out = FileOutputStream(aFile)
out.write(theBytes)
out.close()
print "ALSB Configuration file: "+ exportJar + " has been exported"
if customFile != None:
print collection
query = EnvValueQuery(None,
Collections.singleton(EnvValueTypes.WORK_MANAGER), collection, false, None, false)
customEnv = FindAndReplaceCustomization('Set the right Work Manager', query, 'Production System Work Manager')
print 'EnvValueCustomization created'
customList = ArrayList()
customList.add(customEnv)
print customList
aFile = File(customFile)
out = FileOutputStream(aFile)
Customization.toXML(customList, out)
out.close()
print "ALSB Dummy Customization file: "+ customFile + " has been created"
except:
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()
# EXPORT script init
try:
exportAll(sys.argv[1])
except:
print "Unexpected error: ", sys.exc_info()[0]
dumpStack()
raise

import.py
==================
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 sys

#=======================================================================================
# Entry function to deploy project configuration and resources
#        into a ALSB domain
#=======================================================================================

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

        importJar = exportConfigProp.get("importJar")
        customFile = exportConfigProp.get("customizationFile")

        passphrase = exportConfigProp.get("passphrase")
        project = exportConfigProp.get("project")

        connectToServer(importUser, importPassword, adminUrl)

        print 'Attempting to import :', importJar, "on ALSB Admin Server listening on :", adminUrl

        theBytes = readBinaryFile(importJar)
        print 'Read file', importJar
        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
        ALSBConfigurationMBean.uploadJarFile(theBytes)
        print 'Jar Uploaded'

        if project == None:
            print 'No project specified, additive deployment performed'
            alsbJarInfo = ALSBConfigurationMBean.getImportJarInfo()
            alsbImportPlan = alsbJarInfo.getDefaultImportPlan()
            alsbImportPlan.setPassphrase(passphrase)
            alsbImportPlan.setPreserveExistingEnvValues(true)
            importResult = ALSBConfigurationMBean.importUploaded(alsbImportPlan)
            SessionMBean.activateSession(sessionName, "Complete test import with customization using wlst")
        else:
            print 'ALSB project', project, 'will get overlaid'
            alsbJarInfo = ALSBConfigurationMBean.getImportJarInfo()
            alsbImportPlan = alsbJarInfo.getDefaultImportPlan()
            alsbImportPlan.setPassphrase(passphrase)
            operationMap=HashMap()
            operationMap = alsbImportPlan.getOperations()
            print
            print 'Default importPlan'
            printOpMap(operationMap)
            set = operationMap.entrySet()

            alsbImportPlan.setPreserveExistingEnvValues(true)

            #boolean
            abort = false
            #list of created ref
            createdRef = ArrayList()

            for entry in set:
                ref = entry.getKey()
                op = entry.getValue()
                #set different logic based on the resource type
                type = ref.getTypeId
                if type == Refs.SERVICE_ACCOUNT_TYPE or type == Refs.SERVICE_PROVIDER_TYPE:
                    if op.getOperation() == ALSBImportOperation.Operation.Create:
                        print 'Unable to import a service account or a service provider on a target system', ref
                        abort = true
                elif op.getOperation() == ALSBImportOperation.Operation.Create:
                    #keep the list of created resources
                    createdRef.add(ref)

            if abort == true :
                print 'This jar must be imported manually to resolve the service account and service provider dependencies'
                SessionMBean.discardSession(sessionName)
                raise

            print
            print 'Modified importPlan'
            printOpMap(operationMap)
            importResult = ALSBConfigurationMBean.importUploaded(alsbImportPlan)

            printDiagMap(importResult.getImportDiagnostics())

            if importResult.getFailed().isEmpty() == false:
                print 'One or more resources could not be imported properly'
                raise

            #customize if a customization file is specified
            #affects only the created resources
            if customFile != None :
                print 'Loading customization File', customFile
                print 'Customization applied to the created resources only', createdRef
                iStream = FileInputStream(customFile)
                customizationList = Customization.fromXML(iStream)
                filteredCustomizationList = ArrayList()
                setRef = HashSet(createdRef)

                # apply a filter to all the customizations to narrow the target to the created resources
                for customization in customizationList:
                    print customization
                    newcustomization = customization.clone(setRef)
                    filteredCustomizationList.add(newcustomization)

                ALSBConfigurationMBean.customize(filteredCustomizationList)

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

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

#=======================================================================================
# Utility function to print the list of operations
#=======================================================================================
def printOpMap(map):
    set = map.entrySet()
    for entry in set:
        op = entry.getValue()
        print op.getOperation(),
        ref = entry.getKey()
        print ref
    print

#=======================================================================================
# Utility function to print the diagnostics
#=======================================================================================
def printDiagMap(map):
    set = map.entrySet()
    for entry in set:
        diag = entry.getValue().toString()
        print diag
    print

#=======================================================================================
# 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 read a binary file
#=======================================================================================
def readBinaryFile(fileName):
    file = open(fileName, 'rb')
    bytes = file.read()
    return bytes

#=======================================================================================
# 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 export config properties file

    importToALSBDomain(sys.argv[1])

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