Friday, 26 January 2018

Trigger SOA workflow from java

In this blog I am going to explain how SOA workflow can be triggered from Java application. SOA workflow contains BPEL process and Human Task. BPEL process initiate the workflow and complete the workflow, where as Human Task represent the action of the workflow like assigning task for approval. From java based application, we can call the BPLE process to initiate the workflow. While calling the BPEL process, we have to provide input as payload. In this example, I am explaining the one way calling of SOA composite, where Java will only call the workflow, but will not expect any return.

Before proceed with the development work, some constraints need to be followed.

1. Usually BPEL process is linked with WebService binding exposed service. If we need to call the composite from java, we need to add Direct Binding service. But we also have to make sure that Direct Binding service is not feeding the payload data to BPEL process. Here is the section we need to add in composite.xml

1. Click on the Exposed Service and click on Insert
2. Select Direct Binding


3. Give a name (e.g. DService1).
4. Select the WSDL same as the web service binding (e.g. ManualAction.wsdl in my example).
5. Choose the port type as the non-callback service (e.g. ManualAction in my example).
6. Choose the Callback Port Type as callback service (e.g. ManualActionCallback.wsdl in my example).
7. Click ok to create the binding.


8. Once the Direct Binding is created, it will look something like below:


9. Now, you have to make the wiring so that Direct binding will point to the Web Service binding. Below xml tag needs to be added in the composite.xml

   <wire>
    <source.uri>DService1</source.uri>
    <target.uri>ManualAction/manualaction_client</target.uri>
  </wire>



   After adding the wire, it should looks like below
 10. Now you can modify the BPEL file according to your business case. Here in this example I have added a Human Task named ManualActionUser.



11. Now the SOA composite is ready. We have to create a java call for this composite.
12. Create a simple java project and below libs to the classpath

Febric-common.jar
Soa-infra-mgmt.jar
Wsclient-extended.jar
Wlfulclient.jar
Common-logging.jar


13. Use the below code to a new class file.

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.naming.Context;
import oracle.soa.api.JNDIDirectConnectionFactory;
import oracle.soa.api.PayloadFactory;
import oracle.soa.api.XMLMessageFactory;
import oracle.soa.api.invocation.DirectConnection;
import oracle.soa.api.invocation.DirectConnectionFactory;
import oracle.soa.api.message.Message;
import oracle.soa.api.message.Payload;
import oracle.xml.parser.v2.XMLPrintDriver;
import org.xml.sax.InputSource;

public class TestWF1 {
    public TestWF1() {
        super();
    }
    
    public static void main(String[] args) throws Exception {
        String operation = "process";

        // This is the request message XML
        String ns = "http://xmlns.oracle.com/TestWLWS/ManualAction/ManualAction";
        String payloadXML = "<process anualaction="" estwlws="" http:="" xmlns.oracle.com="" xmlns="\">" +
                            "<oldvalue>1</oldvalue>" +
                            "<newvalue>Testing</newvalue>" +
                            "<approverusername>REQUAP9</approverusername>" +
                            "<approverrolename>2</approverrolename>" +
                            "<workflowrequired>3</workflowrequired>" +
                            "<processinstancekey>4</processinstancekey>" +
                            "<targetprocesstaskname>5</targetprocesstaskname>" +
                            "<currentprocesstaskinstancekey>6</currentprocesstaskinstancekey>" +
                            "<applicationname>7</applicationname>" +
                            "<beneficiaryuserlogin>8</beneficiaryuserlogin>" +
                            "<beneficiaryuserkey>123654789</beneficiaryuserkey>" +
                            "<processformfieldname>10</processformfieldname>" +
                            "</process>"; 

        String serviceAddress = "soadirect:/default/ManualAction!1.0/DService1";

        // Specify the direct binding connection properties
        Map<string object=""> props = new HashMap<string object="">();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
        props.put(Context.PROVIDER_URL, "t3://" + "localhost" + ':' + "8001");
        props.put(Context.SECURITY_PRINCIPAL,"weblogic");
        props.put(Context.SECURITY_CREDENTIALS, "Welcome1");

        // Create the direct binding connection, using those context properties
        DirectConnectionFactory factory = JNDIDirectConnectionFactory.newInstance();
        DirectConnection dc = null;
        try {
           dc = factory.createConnection(serviceAddress, props);
            
            oracle.xml.parser.v2.DOMParser op = new oracle.xml.parser.v2.DOMParser();
            op.parse(new InputSource(new StringReader(payloadXML)));
            XMLPrintDriver pd = new XMLPrintDriver(System.out);
            pd.setFormatPrettyPrint(true);
            pd.printDocument(op.getDocument());
            
            Map partData = new HashMap();
            partData.put("payload", op.getDocument().getDocumentElement());
            Payload payload = PayloadFactory.createXMLPayload(partData); 
            
            Message request = XMLMessageFactory.getInstance().createMessage();
            request.setPayload(payload); 
            
            String uuid = "uuid:" + UUID.randomUUID(); 
            System.out.println("uuid = "+ uuid); 
            request.setProperty(request.CONVERSATION_ID, uuid); 
            dc.post("process", request); 

        } catch(Exception e){
            e.printStackTrace();
        }finally {
            dc.close();
        }
    }

}

14. After running the code check from the Weblogic EM console, by checking in instance of the composite


Friday, 1 December 2017

Change SOA Human Task email header

I am writing this blog to show how Email subject header can be change for a SOA human task. I believe you have observed, that when human task is assigned to any approve, email message header contains "Action Required". If you need to change this to any other value, you cannot do it from composite level. By default all this header values are coming from bpm-services.jar file, which can be find from [SOA_HOME]/soa/modules/oracle.soa.workflow_11.1.1

If you want to change this default header value with some other, you have to make a custom bundle. Follow the below steps to create a custom bundle for email header modification:

1. Copy the bpm-services.jar from [SOA_HOME]/soa/modules/oracle.soa.workflow_11.1.1 to /tmp location
2. Unjar the contents and copy the "oracle\bpel\services\workflow\resource" directory to a seperate location.
3. Make sure that you are maintaining the same directory structure as mentioned above.
4. Under the "oracle\bpel\services\workflow\resource" directory, delete i18NUtil.class file.
5. Change the appropriate properties file according to your need and language supports.
6. For example I need to change the email subject header "Action Required" with "Need your Attention", so I will change the value of TASK_VIEW_CONTEXT_ASSIGNEE_ASSIGNED attribute in WorkflowLabels.properties and WorkflowLabels_en.properties.
7. Once you are done with your changes, make a jar file of "oracle\bpel\services\workflow\resource" directory. in my case it is custombundle.jar
8. Copy the jar to any shared location.
9. Now you have to change the SOA MBean properties "WorkflowCustomClasspathURL" with the path of the bundle jar.
10. You cane do the change using two methods a) Using EM console UI, b) Using WLST command

Changing "WorkflowCustomClasspathURL" using EM console UI
1. Open EM console.
2. Expand SOA, and right click on soa-infra and select Administration->System MBean Browser.
3. Navigate to oracle.as.soainfra.config->Server:[SERVER_NAME]->WorkflowConfig->human-workflow.
4. Click on the human-workflow and change the value of WorkflowCustomClasspathURL with bundle jar filepath.
5. Once done click on Apply.
6. No restart required.



Changing "WorkflowCustomClasspathURL" using WLST command
1. Run [OIM_HOME]/common/bin/wlst.sh
2. Enter the WLST command as bellow:

 wls:/offline> connect('$WL_USER', '$WL_PASSWORD', '$SOA1_URL[t3://localhost:8001]')
 wls:/iam/serverConfig> custom()
 wls:/iam/custom> cd ('oracle.as.soainfra.config:name=human-workflow,type=WorkflowConfig,Application=soa-infra')
 wls:/iam/custom/oracle.as.soainfra.config/oracle.as.soainfra.config:name=human-workflow,type=WorkflowConfig,Application=soa-infra> set('WorkflowCustomClasspathURL','file://FILE_PATH//')
 wls:/iam/custom/oracle.as.soainfra.config/oracle.as.soainfra.config:name=human-workflow,type=WorkflowConfig,Application=soa-infra> disconnect()
 wls:/offline> exit()

Now you can see the email header has been changed with your defined value.

Friday, 17 November 2017

Using weblogic data source from deployed applications

In this blog I am going to show how weblogic datasource can be use to call execute SQL.
To use the weblogic internal datasource, the best option is to use it inside the deployed application.
Here in this example I have created an Web Service application which is deployed in weblogic admin server
and I used the datasource of OIM application which is implemented under oim server (port is 8005).


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Hashtable;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.naming.Context;


@WebService
public class WeblogicDS {
    public String userkey = "";

    public WeblogicDS() {
        super();
    }
    @WebMethod
    public String connectDS(String applicationPort) {

        Hashtable props = new Hashtable();
        props.put(Context.INITIAL_CONTEXT_FACTORY,
                  "weblogic.jndi.WLInitialContextFactory");
        props.put(Context.PROVIDER_URL, "t3://localhost:" + applicationPort);
        System.out.println("1");
        Connection connection = null;
        javax.naming.Context ctx = null;
        javax.sql.DataSource dataSource = null;

        try {

            ctx = new javax.naming.InitialContext(props);
            System.out.println("2");
            dataSource = (javax.sql.DataSource)ctx.lookup("jdbc/ApplicationDBDS"); //JNDI name of the datasource
            System.out.println(dataSource);
            connection = dataSource.getConnection();
            System.out.println("connected");

            PreparedStatement pstmt = null;
            ResultSet appInstRS = null;

            String query = "select * from usr where usr_login='XELSYSADM'";
            pstmt = connection.prepareStatement(query);
            System.out.println("Status:" + pstmt.execute());
            pstmt.getResultSet().next();
            userkey = pstmt.getResultSet().getString("USR_KEY");

        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return userkey;

    }
}

Here the webmethod connectDS is taking 1 input which is the application port is 8005.



Thursday, 16 November 2017

Adding worklist URI of an Human Task Pragmatically using BPEL APIs

In this blog I am going to show how worklist URI can be set for an human task programitically using BPEL APIs. This code snipet can be used to automate the URI adding process after deploying the SOA composite.

Add the below jar files in your project classpath [WLHOME]/server/lib/weblogic.jar [SOAHOME]/soa/modules/oracle.soa.fabric11.1.1/bpm-infra.jar [SOAHOME]/soa/modules/oracle.soa.fabric11.1.1/fabric-runtime.jar [SOAHOME]/soa/modules/oracle.soa.workflow11.1.1/bpm-services.jar [WLHOME]/server/lib/wlfullclient.jar [OIMHOME]/server/ext/spml/wsclientextended.jar

here is the code snipet for adding worklist URI

import java.util.List;
import java.util.logging.Logger;
import oracle.bpel.services.workflow.client.IWorkflowServiceClient;
import oracle.bpel.services.workflow.client.WorkflowServiceClientFactory;
import oracle.bpel.services.workflow.client.config.RemoteClientType;
import oracle.bpel.services.workflow.client.config.ServerType;
import oracle.bpel.services.workflow.client.config.WorkflowServicesClientConfigurationType;
import oracle.bpel.services.workflow.client.config.RemoteClientType.Password;
import oracle.bpel.services.workflow.query.ITaskQueryService;
import oracle.bpel.services.workflow.runtimeconfig.model.TaskDisplayInfo;
import oracle.bpel.services.workflow.runtimeconfig.model.TaskDisplayInfoType;
import oracle.bpel.services.workflow.verification.IWorkflowContext;
import oracle.bpel.services.workflow.WorkflowException;
import org.identityconnectors.common.security.GuardedString;
import org.identityconnectors.common.security.GuardedString.Accessor;


public class TestSOA {
    
    private String soaAdminUserName = "weblogic";
    private GuardedString soaAdminPassword = null;
    private String adminPassword = "Weblogic Password"; // put your weblogic password
    private String soaServerName = "SOA Server name"; //put your SOA server name e.g. soa_server1
    private String soaServerURL = "t3://SOA_HOST:8001"; //replace the value of SOA_HOST.
    Password weblogicPWD = null;
    IWorkflowContext wctx = null;
    ITaskQueryService qService = null;

    /**
     * This method will check the input request id has been approved by a human
     * @param reqId : OIM request id
     * @return : true/false
     * @throws Exception
     */
    public void addWorkilistURI() throws Exception{
        
        boolean flag = false;
                Logger logger = Logger.getLogger(TestSOA.class.getName());
                /**
                 * Adding SOA server and its properties into the WorkflowServicesClientConfigurationType
                 */
                WorkflowServicesClientConfigurationType wssst = new WorkflowServicesClientConfigurationType();
                List servers = wssst.getServer();
                ServerType server = new ServerType();
                server.setDefault(true);
                server.setName(soaServerName);
                servers.add(server);

                RemoteClientType rct = new RemoteClientType();
                rct.setServerURL(soaServerURL);
                rct.setUserName(soaAdminUserName);
                soaAdminPassword = new GuardedString (adminPassword.toCharArray());
                soaAdminPassword.access(new Accessor() {
                    @Override
                    public void access(char[] clearChars) {
                        System.out.println( new String(clearChars));
                        weblogicPWD = new Password();
                        weblogicPWD.setValue(new String(clearChars));
                    }
                });

                rct.setPassword(weblogicPWD);
                rct.setInitialContextFactory("weblogic.jndi.WLInitialContextFactory");
                rct.setParticipateInClientTransaction(false);
                server.setRemoteClient(rct);
                
                /**
                 * Creating remote enterprise java bean interface to invoke workflow 
                 * service located remotely from the client.
                 * 
                 * After creating IWorkflowServiceClient object, get the Query Service.
                 */
                IWorkflowServiceClient wfsc = WorkflowServiceClientFactory.getWorkflowServiceClient(WorkflowServiceClientFactory.REMOTE_CLIENT,wssst,logger);
                qService = wfsc.getTaskQueryService();
                  
                 soaAdminPassword.access(new Accessor() {
                     public void access(char[] clearChars) {
                        System.out.println( new String(clearChars));
                        try {
                            wctx = qService.authenticate(soaAdminUserName, clearChars, null);
                    } catch (WorkflowException we) {
                        we.printStackTrace();
                    }
                     }
                });
                    
                soaAdminPassword.dispose();
                List taskDisplayInfoTypeList = wfsc.getRuntimeConfigService().getTaskDisplayInfoByTaskDefinitionId(wctx, TASK_ID, APPLICATION_NAME, FORM_NAME);

                if (taskDisplayInfoTypeList.size()==0){
                 
                 oracle.bpel.services.workflow.runtimeconfig.model.ObjectFactory of = new oracle.bpel.services.workflow.runtimeconfig.model.ObjectFactory();
                    TaskDisplayInfo taskInfoType = of.createTaskDisplayInfo();
                    taskInfoType.setHostname("HOSTNAME"); //enter your URI hostname
                    taskInfoType.setHttpPort("HTTP PORT"); //enter URI HHTP port
                    taskInfoType.setHttpsPort("HTTPS PORT");//enter URI HTTPS port
                    taskInfoType.setApplicationName("worklist");
                    taskInfoType.setFormName("default");
                    taskInfoType.setUri("URI VALUE"); //enter the URI value
                    
                    taskDisplayInfoTypeList.add(taskInfoType);
                    
                    wfsc.getRuntimeConfigService().setTaskDisplayInfo(wctx, HUMANTASK_NAME_SPACE, COMPOSITE_VERSION, PARTITION_NAME, taskDisplayInfoTypeList);
                    System.out.println("done");
                }else{
                 System.out.println("URI already added");
                }
                
               return flag;
    }

 public static void main(String[] args) {
       TestSOA a = new TestSOA();
       try {
            a.addWorkilistURI();
       } catch (Exception e) {
            e.printStackTrace();
       }
   }
}

Replace the below variable as per your requirement

TASK_ID: Human Task id, e.g. "default/DisconnectedProvisioning!1.0/ManualProvisioningTask"
APPLICATION_NAME: name of the application. Default is "worklist"
FORM_NAME: Default value is "default"
HUMANTASK_NAME_SPACE: Namespace of the human task, e.g. "http://xmlns.oracle.com/DefaultProvisioningComposite/DisconnectedProvisioning/ManualProvisioningTask"
COMPOSITE_VERSION: version of the composite, e.g. "1.0"
PARTITION_NAME: name of the partition where the composite is deployed, e.g. "default"

Note: Kindly ignore the line 122 in the code"".. some how it is appearing in the code block.

Sunday, 1 October 2017

OIM 12c Installation (With Quick Start)

OIM 12c introduces quick installer package, where you don't need to install all the components (like Weblogic, SOA and OIM suite) separately. The package comes with everything including inbuilt RCU. Here are the steps for installing OIM 12c with quick start version:

Pre-Requisites


1. Database must be installed (in my case I have installed Oracle DB 12.2.1.3)
2. All the below required parameters of database are set.

          open_cursors with value 800 and more
          processes with 800 and more
          XA transaction recovery views/synonyms are installed

3. All the required OS and Kernel parameters are set (for Linux)
visit below URLs for more details..

http://www.oracle.com/technetwork/middleware/ias/downloads/fusion-certification-100350.html

http://docs.oracle.com/middleware/12213/idmsuite/INOAM/GUID-16F78BFD-4095-45EE-9C3B-DB49AD5CBAAD.htm#INOAM-GUID-BEC7EF99-83DC-4511-9F40-57FD5DA602B2

Installation steps


1. Installing Binaries

a. Install JDK (version jdk-8u144-linux-x64)
b. Set the JAVA_HOME and PATH with jdk directory.
c. Download and unzip the fmw_12.2.1.3.0_idmqs_Disk1_1of2.zip and fmw_12.2.1.3.0_idmqs_Disk1_2of2.zip. This will unzip 2 jar files.

d. run the first jar file as below
     [JAVA_HOME]/bin/java -jar fmw_12.2.1.3.0_idmquickstart.jar


e. A Graphical interface will open.


f. Click on Next
g. Skip the software update and click Next

h. Provide the Oracle Home directory location and click Next. Next page will check for the pre-requisite settings. If all pre-requisites are cleared, then click on Next. Otherwise cancel the installation and perform the failed pre-requisite configuration. For development setup you can skip the pre-requite step.


i. Click on Install.
j. Installation will take few minutes. Once the installation is done, click on Next
k. Installation completion page will appear. Click finish to close the wizard.
l. Purpose of this installation is to create the oracle home directory with necessary components for OIM. Now if you go the provided oracle home directory, you can find all the required components are created as below



2. Creating database Schema using RCU

OIM 12c does not have a separate RCU. RCU packages are included in the quickstart binaries. Follow the below procedure to run RCU.

a. Go to [ORACLE_HOME]/oracle_common/bin and run the ./rcu


b. RCU Welcome wizard will be opened.


c. Click on Next


d. If you have DBA privilege, then select the "System load and Product load". If you do not have the DBA access then select the "Prepare Script for System load". This option will generate a script at end of the RCU execution that you can provide to DBA team. Once DBA team perform the script execution, you have to run the RCU again and choose the "Perform Product Load" and continue.

** In this scenario I am running with the "System Load and Product Load".


e. Provide the necessary details of you database and click Next.


f. This will check the parameters of the database. once the checking is done click on OK.


g. In this section Create a new prefix name (like DEV) and select the only the "Oracle Identity Manager". Other dependent components will be automatically selected. Once done click on Next.


h. Now ECU will check all the pre-requisite for selected schemas. Once the checking is done click on OK.


I. Now provide the schema password. This will the password for all the newly created schemas. Either you can choose one single password for all the schemas or you can choose different password for each schema. Here I choose single password. After entering password click Next.


j. Here in this page you can select the size of the SOA schema (small, medium, large) and SOA health care integration option (yes, no). This is a new feature of 12c. Once the selection is done click on Next


k. Check all the new table-space and TEMP table-space name that will be created in the next step. Once done click on Next to create table spaces.


l. Table Spaces are now created. Once done click on OK.


m. Now click on Create to create schemas.


n. Once all the schemas creation are done, it will show the completion message with individual schema creation log files. Click Close to close the wizard.

o. Verify all the schema by connecting them from sql-developer.


3. IAM domain creation

a. Go to [ORACLE_HOME]/oracle_common/common/bin and run ./config.sh. This will open the domain configuration wizard.


b. Select "Create a new domain" and click on Next.


c. Select only "Oracle Identity Manager 12.2.1.3.0 [idm]". All other supporting components will be selected automatically. Once done click on Next.


 d. If you need to store JTA transaction logs and JMS persistence data into database then select JDBC for both the JTA and JMS. here I choose the file system instead of database. Once done click on Next.


e. Select the domain application directory and click Next.


f. Provide weblogic password and click Next.


g. Select the domain mode (Development, Production) and JDK. By default installer will take the JAVA_HOME value but you still can change it to different one. Once done click on Next.


h. In this window, you do not need to put any value. Just click on the "Get RCU Configuration", and installer will automatically take the RCU created schemas and their configurations. Once you click on that button, you will see something like below:


I. Verify all and click on Next.


J. In this window system will check all the schemas by connecting them one by one. Once the testing is done click on Next.



k. In OIM 12c, all the OIM configuration will be done in this step, so you have to provide OIM details as well.

      For the keystore provide username "keystore" and a new password.
      For OIMSchemaPassword put username as OIM schema name and enter its password.
      For sysadmin provide "xelsysadm" as username and give a new password.
      For WeblogicAdminKey provide "weblogic" as username and enter its password.

Once done click on Next.


l. In this window you can add your own certificates. If you want configure it later then simply click on Next.


m. Here you can click on each item and configure as per your requirement. Or if you want go with all  default settings then simple click on Next.


n. Now click on Create. This will create your domain.


o. Once the domain creation is done, click on Next.


p. At the end of configuration window, you will get the url of the weblogic console. Click one finish to close the wizard.

q. After creation of domain, you can find the domain directory has been created.


4. Performing Post-Configuration Tasks

a. Set the DOMAIN_HOME and JAVA_HOME variable.
b. go to [ORACLE_HOME]/idm/server/bin
c. Give execute permission to offlineConfigManager.sh file (chmod 755 offlineConfigmanager.sh).
d. Run the file.


e. Once the execution is done, you will get some success message like below:



5. Starting Server

 Now start all the servers as per below sequence:

      1. Nodemanager
      2. WebLogic Server
      3. SOA Server (Run after WebLogic is RUNNING)
      4. OIM Server (run after SOA is RUNNING)


6. Integrating OIG with SOA suite

a. Open EM console (http://hostname:7001/em)
b. Login using weblogic credential.


c. Click on WebLogic Domain and select System MBean Browser.


d. Now in the find properties, enter "OIMSOAIntegrationMBean" and search


e. Once found, select the same and then select "integrateWithSOAServer".


f. Enter all the required details and click on Invoke.


g. Once the invoke is successful, it will show you the below message.



h. This change does not require any server restart.

************** OIM Installation is now done***********************************

Now open identity console http://hostname:14000/identity and check the release version



Followers

OIM API for adding process task and retry failed task

 In this blog you can find how to add new process task and retry any failed/rejected tasks using API. Adding new process task: /************...