Thursday, 22 March 2018

OIM Plugins auto registration

In OIM, we register plugins for event handler, request data validator etc. We generally copy the plugin zip file contains the jar and plugin.xml, and then we register it manually.

OIM also provided a feature to register the plugin automatically after copying the OIM_HOME/server/plugin folder.

Here are the details of auto-registration process of plugin.


Export the oim-config.xml file.

1. login to weblogic EM console
2. Go to Identity and Access -> OIM -> oim(11.1.2.0.0)
3. Right click on it and click System MBean Browser.
4. Now go the below location





5. Click on the MDSAppRuntime.
6. provide toLocation as /tmp
7. provide docs as /db/oim-config.xml


8. once done click on Invoke
9. check on the /tmp location of the respective server (if select oim server1 then check on the oim1 unix server).

10. a directory named db created, under which you will find oim-config.xml


Modify the oim-config.xml

1. open the oim-config.xml in edit mode.
2. Search for the tag pluginConfig



3. Modify the the value of reloadEnabled and relodaInterval accordingly.
                    reloadEnabled=true means auto registration allowed.
                    reloadInterval=20 means auto registration will occured every 20 sec.

4. After changing the value save the change and close the editor.


Import the modified oim-config.xml

1. 1. login to weblogic EM console
2. Go to Identity and Access -> OIM -> oim(11.1.2.0.0)
3. Right click on it and click System MBean Browser.
4. Now go the same location as export.
5. Select importMetadata, and provide fromLocation and docs as below (same as export).


6. Once done click on Invoke.
7. Restart the oim managed servers.

Wednesday, 21 February 2018

Using GuardedString in OIM custom code.

It was observed in several cases, where we write custom java code for OIM (adapter, event handler, UI code , scheduler etc) with password as string value. If we store the password as java.lang.String, it is kept in memory as a clear text password and stays in memory at least until it is garbage collected. Code reviewer will always reject such code, if they find any password as java.lang.String.

GuardedString class can eliminate this problem by storing the password as characters in memory in an encrypted form. The encryption key will be a randomly-generated key. In their serialized form, Guarded String will be encrypted using a known default key. This is to provide a minimum level of protection regardless of the transport. For communications with the Remote Connector Framework it is recommended that deployments enable SSL for true encryption.

In this example I will explained how you can use Guarded String in OIM custom code.

GuardedString class is the member of  org.identityconnectors.common.security package and can be found in framework-1.3.2.jar. That means in your java project you have to import framework-1.3.2.jar as a library.


Below code sample describe how to store string password in GuardedString.

import org.identityconnectors.common.security.GuardedString;

String password = "abcd1234";
char[] passwordToChar = password.toCharArray();
GuardedString guardedPassword = new GuardedString(passwordToChar);


Below code sample describe how to get the password from GuardedString

          guardedPassword.access(new GuardedString.Accessor() {
                        @Override
                        public void access(char[] clearChars) {
                            System.out.println( "String password::::::::::::::::::::::::"+new String(clearChars)); //print the password.
                            
                        }
                    });
            retrivePassword.dispose(); // dispose the GuardedString after use.


it is always better to dispose the GuardedString after authentication operation is done using dispose() method.



Friday, 9 February 2018

Read OIM ITResource parameter using API

In this blog I am going to explain how to read the OIM IT Resource parameter using API. Here is the code sample you can use to fetch any available IT resource parameter in your java code.


public void getITResourceParameter(String ITResourceName) throws NumberFormatException, tcAPIException, Exception {

final String methodName = "::getITResourceParameter::";
System.out.println("start execution of CallStoredProcedureForDBAT::"+methodName);

Map phAttributeList = new HashMap();
phAttributeList.put("IT Resources.Name", ITResourceName);

HashMap paramMap = new HashMap();

tcITResourceInstanceOperationsIntf ITResourceAPI = (tcITResourceInstanceOperationsIntf)oimClientObj.getService(tcITResourceInstanceOperationsIntf.class);
tcResultSet itresSet = ITResourceAPI.findITResourceInstances(phAttributeList);
itresSet.goToRow(0);
String ITResourceKey = itresSet.getStringValue("IT Resources.Key");
System.out.println("ITResourceKey::"+ITResourceKey);
tcResultSet paramValuesRS = ITResourceAPI.getITResourceInstanceParameters(Long.parseLong(ITResourceKey));

for(int j=0;j<paramValuesRS.getTotalRowCount();j++){

paramValuesRS.goToRow(j);

paramMap.put(paramValuesRS.getStringValue("IT Resources Type Parameter.Name"), paramValuesRS.getStringValue("IT Resources Type Parameter Value.Value"));

}

adminName = (String) paramMap.get("principal"); // "principal" is the IT Resource attribute name
adminPassword = (String) paramMap.get("credentials"); // "credentials" is the IT Resource attribute name
ldapPort = (String) paramMap.get("port"); //"port" is the IT Resource attribute name
HostName = (String) paramMap.get("host"); //"host" is the IT Resource attribute name
searchBase = (String) paramMap.get("baseContexts"); //"baseContexts" is the IT Resource attribute name

System.out.println("adminName ::"+adminName);
System.out.println("adminPassword ::"+adminPassword);
System.out.println("HostName ::"+HostName);
System.out.println("ldapPort ::"+ldapPort);
System.out.println("searchBase ::"+searchBase);

}

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.

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: /************...