Tuesday, 10 December 2013

Using DecisionTables in BussinessRules --SOA 11g



Hi Guys

The Decision Table is a smart, compact way of clustering many IF/THEN rules together, as will be demonstrated in this article. As we dealt with simple IF/THEN,Functions in previous posts.


Demo
This article demonstrates how the decision table can be put to good use to implement the business logic behind the classical game of Dice

Rules for Dice game as defined below :

IF Player 1 ="three" Player 2="three"  Player 2 wins
IF Player 1 ="three" Player 2="one,two,four,five,six"  Player 1 wins
IF Player 1 ="one" Player 2="one"  Player 2 wins
IF Player 1 ="one" Player 2="three,two,four,five,six"  Player 1 wins
IF Player 1 ="five" Player 2="five"  Player 2 wins
IF Player 1 ="five" Player 2="three,two,four,six,one"  Player 1 wins
IF Player 1 ="six" Player 2="six"  Player 1,2  are in tie wins
IF Player 1 ="six" Player 2="three,two,four,five,six"  Player 1 wins
IF Player 1 ="two,four" Player 2="two,four" response="tryAgain"



Designing SOA Application :


Create a new XSD document, called Diceplayergame.xsd. It should be composed as follows:





 The RequestType describes the input that the Business Rule will deal with. It consists of two entries, here labeled with throwOne and throwTwo. Both contain exactly one value from the enumerated list of values Stype1. The Response type contains a single element outcomeof Stype2 that has one of three values: One_Wins | Two_Wins | tie.



Create and configure the Business Rule 

 Create new Business Rule component


 

Set the input and output for the rule based on the Request and Response type defined in the XSD document.
Double click the Business Rule component to edit the rule definition.
o Create XML Facts – go to the Facts tab, click on the green plus icon, select the complex and simple types from the XSD document to have XML Facts created from them


  Verify/Create Bucketsets as illustrated below




Configure the Decision Function




Edit default rule set; create a Decision Table

Create an action: Assert New InputGamedetailsresponse. The outcomeresponse property is parametrized (always to be determined for the rule), make sure the checkbox Always Selected is checked (to make sure this action is executed for every rule that is triggered) and press the ok button




Add conditions for InputGamedetails.throwone and InputGamedetails .throwtwo. Both conditions are associated with bucketset Roll_Dice.




Below illustrated Design of decision-table







TestCases :














HappyLearning

                                                                                                                By DeepthiReddy

Sunday, 8 December 2013

BussinessRulesEngine Using Functions --Soa 11g

Hi Guys

In this Post we will discuss in depth of BussinessRuleEngine.(Continution to  BussinessRule Part 1)

Our current rule developed in BussinessRule Part 1 approves vacations of one day in duration, requiring all other leave requests to be manually approved. Ideally, we would like to approve holidays of varying duration as long as sufficient notice has been given, for example:
  • Approve vacations of one day in duration with a start date that's two weeks or more in the future
  • Approve if for 2-3 days and more than 30 days in the future
  • Approve if 5 days or less and more than 60 days in the future

  • So we will need to write our own logic to calculate these values. Rather than embedding this logic directly in each rule, best practice dictates that we place this logic into a separate function. This not only ensures that we have a single version of the logic to implement but minimizes the size of our rules, thus making them simpler and easier to maintain. For our purposes, we will create the following functions:
  • startsIn: Which returns the number of days before the specified start date
  • leaveDuration: Which returns the number of days from the start date to the end date
To create our first function, within the rule editor, click on the Functions tab. This will list all the functions currently defined to our ruleset. To create a new function, click on the green plus icon, as shown in the following screenshot:
This will add a new function with a default name (for example, Function_1) to our list. Click on the function name to select it and update it to startIn. From the drop-down list, select the Return Type of the function, which is int in our case.

Next, we need to specify the arguments we wish to pass to our function. Click on the green plus sign, as shown in the following screenshot, and this will add an argument to our list. Here we can specify the argument name (for example, startDate), and from the drop-down list, the argument Type, which should be XMLGregorianCalendar (when creating XML facts, the JAXB processor maps the type xsd:date to javax.xml.datatype.XMLGregorianCalendar).
The list of valid types is made up of the basic types (for example, int, double, char, and so on), plus the XML facts (excluding object factories) and the Java Facts (excluding the Rules Extension Method) defined in our rules dictionary.
The final step is to implement the business logic of our function, which consists of one or more actions. We enter these actions in the Body section of the function. The first action we need to create is one that creates a local variable of type calendar, which holds the current date.
To do this, click on <insert action> within the Body section of our function. The rule editor will display a drop-down list that lists all the available actions.

Same as above create another Function,Argument for leaveduration as showm below




Now modify the Ruleset  to below





Now we are ready to test Function logic for BussinessruleEngine


HappyLearning


                                                                                                             By DeepthiReddy

Working with Bussiness Rule Engine --Soa 11g


Hi Guys

The Oracle Business Rules engine that comes as part of the SOA Suite provides a declarative mechanism for defining business rules externally to our application. This not only ensures that each rule is used in a consistent fashion, but in addition, it makes it simpler and quicker to modify. We only have to modify a rule once and can do this with almost immediate effect, thus increasing the agility of our solution.

In this article, we will introduce the new rules editor and look at how we can use it to define a decisions service to automate the approval of leave requests. Then, once we've done this, we'll see how to invoke the rule from the leave approval BPEL process.
 

Business rule concepts

Before we implement our first rule, let's briefly introduce the key components which make up a business rule. These are:
  • Facts: Represent the data or business objects that rules are applied to.
  • Rules: A rule consists of two parts, namely, an IF part that consists of one or more tests to be applied to a fact(s), and a THEN part that lists the actions to be carried out, should the test evaluate to true.
  • Rule Set: As the name implies, it is just a set of one or more related rules that are designed to work together.
  • Dictionary: A dictionary is the container of all components that make up a business rule. It holds all the Facts, Rule Sets, and Rules for a business rule.

Leave approval business rule

 To begin with, we will write a simple rule to automatically approve a leave request that is of the type Vacation and only for one day's duration. This is a pretty trivial example, but once we've done this, we will look at how to extend this rule to handle more complex examples.

Creating Soa Composite
Within JDeveloper, open up your LeaveApproval application . Open up the composite.xml file for the application and then from the Component Palette, drag-and-drop a Business Rule onto the composite.This will launch the Create Business Rules dialog, as shown in the following screenshot:



The first step is to give our dictionary a name, such as  LeaverequestRules, and a corresponding
In addition, we need to specify the Input and Output facts that we will pass to our decision service. For our purpose, we will pass in a single leave request. The rule engine will then apply the rules that we define and update the status of the leave request to either Approved or Manual

Next, click the Advanced tab. Here we can see that JDeveloper has given the default name LeaveApprovalRules_DecisionService_1 to our decision service. Give it a more meaningful name such as LeaveApprovalDecisonService.




Implementing our business rules

The rules editor allows you to view/edit the various components which make up your business rules. To select a particular component, such as Facts, Functions, Globals, and so on, just click on the corresponding tab down the left-hand side.

To add a rule, click the green plus symbol on the top-right-hand corner, and select Create Rule, as shown in the following screenshot (alternatively click on the Create Rule button, circled in the following screenshot).





For our leave approval rule, we need to define two tests, one to check that the request is only for a day in duration, which we can do by checking that the start date equals the end date, and the second to check that the request is of type Vacation.
To define the first test, click on &ltinsert test&gt. This will add the line <operand> = = <operand> under the IF statement where we can define the test condition.






The rule editor allows us to choose from the following action types:
  • assert new: We use this to create and assert a new fact, for example, a new LeaveRequest. Once asserted, the new fact will be evaluated by the rules engine against the ruleset.
  • modify: We can use this to either assign a value to a variable or a fact attribute; in our case we want to assign a status of Approved to the requestStatus property.
  • retract: This enables you to retract any of the facts matched in the pattern (for example, TLeaveRequest) so that it will no longer be evaluated as part of the ruleset.
  • call: This allows you to call a function to perform one or more actions.

The actions assert new and retract are important when we are dealing with rulesets that deal with multiple interdependent facts, as this allows us to control which facts are being evaluated by the rule engine at any particular time.
For our purposes, we want to update the status of our leave, so select modify




Calling a business rule from BPEL

Save the rule, and then switch back to our composite and double-click the LeaveRequest BPEL process to edit it. Drag a Business Rule from the BPEL Activities and Components palette into your BPEL process



Once we've specified the service, we need to specify how we want to invoke the decision service. We specify this through the Operation attribute. Here we have two options:
  • Execute function and reset the session
  • Execute function
If we choose the option Execute function and thus don't reset the session, if we were then to call the decision service several times within the same instance of our BPEL process, each new invocation would reuse the same session and would also evaluate facts asserted in any previous invocation. For our purposes, we just need to assert a single fact and run the ruleset, so accept the default value of Execute function and reset the session.



 We are ready to go with testing

In my next post we will discuss about Using Functions in BussinessRules


Happy Learning

                                                                                                                   By DeepthiReddy

Saturday, 7 December 2013

Signalling In BPEL--Master & Detail Process

HI Guys

A BPEL process can communicate with another BPEL process just like it can communicatie with any Web Service – as BPEL processes expose WebService interfaces to the world – or at least to their fellow components in the same Composite Application. When one process – the master in tis discussion – calls another one – it can have several types of interaction and dependency on that other process – we will call it the detail process for the purpose of this article:
  • it is not interested at all in the detail process – its call was a one-way fire and forget
  • it is interested in the response and it will wait for the response before it can continue processing (synchronous calls will always do this, asynchronous calls could have some activity going on while the detail process is churning away)
  • it is interested in the fact that the detail process has reached a certain stage – but it does not actually need a response (it wants a signal but no data)
The Signal and ReceiveSignal activities are Oracle extensions to BPEL – that only work on the Oracle BPEL engine – that help us to implement the third scenario.
As part of the Invoke activity from a BPEL process to another process, we can specify that the called process should be considered a Detail process (and therefore the calling process as the Master process). When we have established this Master-Detail relationship, we can next create a Signal-ReceiveSignal connection between the two. These connections can be created in both directions: the Master sends a signal to the Detail (and the Detail waits to receive the signal) and vice versa the Detail process sends a signal that the Master is waiting for. Unfortunately, as we will see in this article, we cannot have multiple such interactions between a Master-and-Detail pair.
Typical use cases for the signal pattern are situations where a master process can only proceed when detail processes have completed or at least reached a certain state (the master process should only send the email to the customer when the detail process has handed the order to the shipping department) or when a master process calls a detail process to start processing and then needs to do some additional work before the detail process(es) can continue to their next step (master process asks detail to start gathering quotes from car rental companies, than continues to establish the credit-worthiness of the customer and when that has been taken care of indicates to the detail process that it may continue processing).
Note: there is nothing signal .and receiveSignal can do that we cannot also achieve using asynchronous, correlation driven calls. However, when we can achieve our goals using signaling, it is usually much easier to implement and lighter-weight to execute than the full blown correlation based solution.

Master and Detail Process Coordination Responsibilities
If A... Contains A... Then...
Master process Signal activity The master process signals all of its associated detail processes at runtime.
Detail process Receive signal activity The detail process waits until it receives the signal executed by its master process.
Detail process Signal activity The detail process signals its associated master process at runtime that processing is complete.
Master process Receive signal activity The master process waits until it receives the signal executed by all of its detail processes.



To create a master process:

In the SOA Composite Editor, create a BPEL process service component. For this example, the process is named MasterProcess.
Double-click the MasterProcess BPEL process.
In the Component Palette, expand BPEL Activities.
Drag a Signal activity into the designer
Double-click the Signal activity.
This activity signals the detail process to perform processing at runtime.



 Click OK.
Drag a Receive Signal activity into the designer.
Double-click the Receive Signal activity.
This activity enables the master process to wait until it receives the signal executed by all of its detail processes.
  
The master process has now been designed to:
  • Signal the detail process to perform processing at runtime.
  • Wait until it receives the signal executed by the detail process.

    How to Create a Detail Process

    To create a detail process:
    In the SOA Composite Editor, create a second BPEL process service component. For this example, the process is named DetailProcess
    Double-click the DetailProcess BPEL process
    Drag a Receive Signal activity into your BPEL process service component
    Double-click the Receive Signal activity.
    This activity enables the detail process to wait until it receives the signal executed by its master process.





    Click OK
    Drag a Signal activity into the designer
    Double-click the Signal activity.
    This activity enables the detail process to signal its associated master process at runtime that processing is complete








    Click OK.
    The detail process has now been designed to:
    • Wait until it receives the signal executed by its master process.
    • Signal the master process at runtime that processing is complete.

     

    To create an invoke activity:

  • Return to the MasterProcess master process.
  • Drag an Invoke activity into your BPEL process service component.
  • Double-click the Invoke activity.
  • Select the DetailProcess BPEL process you created in first Step as the partner link.
  • Complete all remaining fields in the Invoke dialog, and click OK.
  • In the designer, click Source.
Select the Invoke As Detail checkbox in the invoke activity.
 Specify the bpelx:detailLabel attribute for correlating with the receive signal activity
  1. <invoke name="MyInvoke" partnerLink="DetailProcess"
       portType="dp:DetailProcess" 
       operation="initiate"
       inputVariable="detail_input"/>
       bpelx:detailLabel="detailProcessComplete0"
       <bpelx:invokeAsdetail name="true"/>
    

HappyLearning

                         
                                                                                                                By DeepthiReddy

Invoke Soa Composite from JAVA----ADV Bpel Concept

There are different approaches to invoke the SOA Composites through java like DirectConnection, ADFBinding etc. But in both the approaches we have to add the additional configurations in the Composite.xml file.
Instead of using this approach, we can use the Apache Axis framework to invoke all the composites as a webservice.
We have implemented a Service Invocation Framework to invoke the composites through JAVA.
We have to set the endpoint and the operation name correspondingly to invoke the service

We can call SOA composite from java in simple two steps. First write java code to call composite and second change binding in Composite.xml to adf binding.

First step is to write java code that will invoke SOA composite. To make java code work you need to import some packages. Basically you need to add three below mentioned jar files in your project.

following are the Jars to import in to your java project:







next step is changing the composite.xml to add binding.adf like below(bold) :

  <service name="JavaBinding" ui:wsdlLocation="HelloBPELProcess.wsdl">
    <interface.wsdl interface="http://xmlns.oracle.com/SOATECHBLOG/Hello_project/HelloBPELProcess#wsdl.interface(HelloBPELProcess)"/>
    <binding.direct/>
  </service>



and actual java code :


Locator locator = null;
try {
DirectConnectionFactory factory = JNDIDirectConnectionFactory.newInstance();
String serviceAddress = "soadirect:/default/Hello_project!1.0/JavaBinding";
            DirectConnection dc;
            dc = factory.createConnection(serviceAddress,jndiProps);

            // Sample payload from em is as follows -

String inputPayload =
    "<Order xmlns=\"http://www.example.org\">"+
    "<customerId>38271</customerId>"+
    "<customerName>deepthireddy</customerName>"+
    "<customerdetails>CDH account</customerdetails>"+
    "<CardType>ACH</CardType>"+
    "<Product>iphone5</Product>"+
    "<Quantity>4</Quantity>"+
    "<TotalPrice>45,000</TotalPrice>"+
    "</Order>"  
    ;
    System.out.println(inputPayload);
  
   /*       xmlns=\"http://www.example.org\\">
      <customerId></customerId>
      <customerName></customerName>
      <customerdetails></customerdetails>
      <CardType></CardType>
      <Product></Product>
      <Quantity></Quantity>
      <TotalPrice></TotalPrice>
    </Order>";*/
  
  
System.out.println("Input = " +"\n" + inputPayload);
//
// parse using the Oracle XML parser.
// Thanks Silviu!
oracle.xml.parser.v2.DOMParser op = new DOMParser();
op.parse(new InputSource(new StringReader(inputPayload)));

// just a print to check it
XMLPrintDriver pd = new XMLPrintDriver(System.out);
pd.setFormatPrettyPrint(true);
pd.printDocument(op.getDocument());

Map partData = new HashMap();
partData.put("payload", op.getDocument().getDocumentElement());

// Create the Message and pass in the payload
Payload payload = PayloadFactory.createXMLPayload(partData);

Message request = XMLMessageFactory.getInstance().createMessage();
request.setPayload(payload);

// Define conversation ID
String uuid = "uuid:" + UUID.randomUUID();
System.out.println("uuid = "+ uuid);
request.setProperty(request.CONVERSATION_ID, uuid);

// Invoke...
dc.post("process",request);

} catch (Exception e) {
e.printStackTrace();
}

}

}


Now you are ready to invoke SOA Composite by using this Java API.

Happy Learning

                                                                                                                         By DeepthiReddy

CompensateHandler_Soa11g


Hi Guys

Today I want to discuss about Compensate Handlers

Concept

Process and service activities can be divided into unit-of-works, called transactions that are either executed (i.e. committed) as a whole or undone as a whole (i.e. rollbacked) due to some error or an explicit rollback command. When the activities within the same unit-of-work span multiple resources (databases, Java components, JMS topics, and so on) these resources all need to support global (XA) transactions and need to enlist in the global transaction, to support commits and rollbacks on the transaction as a whole.

It is not always possible to use transactions as a means to commit, or rollback related activities as a whole. For example when the invoked services do not support global transactions. Next to this, long running processes execute several (implicit) commits since transactions shouldn't be kept open too long: this degrades performance and causes completed activities to remain invisible to others. Once a commit has been executed, the committed activities cannot be rollbacked. Consider an Order-to-Process in which we book the customer's credit card in advance and deliver the ordered goods a few days later. The process will dehydrate at some point causing a commit on the active transaction. If delivery of the ordered goods fails we cannot rollback the credit card booking.

Compensation provides a mechanism to undo already committed activities by means of invoking opposite activities (i.e. compensation) in reverse order. For example booking the opposite amount of money to the credit card that was initially charged. SOA Suite provides the following activities to support compensation:
  • Compensation handler. Compensation handlers contain the activities that need to be executed as part of the compensation flow. These handlers are defined per scope, similar to catch blocks. Per scope you need decide if you need a compensation handler. 
  • Compensate activity. The activity that triggers compensation for a SOA Composite. Executing this activity will cause the invocation of compensation handlers for all successfully completed scopes that have defined a handler, and are not yet compensated. Only compensation handlers of scopes that are directly enclosed by the scope that contains the compensate activity will be executed. The handlers are executed in reverse order, so the handler of the last completed scope is executed first. 
Before we jump to the demo some considerations when using compensation:
  • Compensate activities can only be executed from catch blocks and compensation handlers.
  • Compensation activities either trigger compensation for all enclosed and completed scopes using the compensate activity (supported in BPEL 1.1 and 2.0), or can trigger compensation for one specific scope using the compensateScope activity (only BPEL 2.0).
  • Compensation handlers can only be defined on scope level, not on sequence level.
Demo


Here i am working on Simple example of mathematicalOperations.The composite contains a single, asynchronous BPEL component called CompensateDemo. After receiving the input message the process executes the following scopes and sequences:

first scope defines a normal add logic and compensatehadlers triggers when compensate activity has to be executed.



for divide logic , I designed the flow as below



Let me get in to the code in detail:

If the result of Divide='Infinity'  throws an error 'ThrowErr_DivByZero'  which is catched by catch activity
and reset the value  and throw the exception which is handled by Catchall Block




Compensate All activity cares for  Scopes to excecute their compensate Handlers









Happy Learning


                                                                                                                     By DeepthiReddy

Thursday, 5 December 2013

Base64 Binary Encoding and Decoding - BPEL 11G


Hi Guys,

Sometimes there are requirements where we receives request from consumer in opaque/binary format or we may have to interact with applications using binary format.To facilitate this requirement Java embedding activity is used in BPEL.I will be demonstrating how to convert string to binary format and vice verse.

For this use case I have already created a BPEL process that will receive string in string format.In the BPEL code I have added 2 java embedding activities one for encoding and one for decoding the data.
 


Firstly, I will encode the payload received in binary format using below code:

addAuditTrailEntry("Encoding started");       
try {       
oracle.xml.parser.v2.XMLElement input = (oracle.xml.parser.v2.XMLElement) getVariableData("inputVariable","payload","/ns1:encode/ns1:PIN-NUMBER");       
java.lang.String input_str = input.getTextContent();       
addAuditTrailEntry("Input String = "+input_str);       
oracle.soa.common.util.Base64Encoder encoder = new oracle.soa.common.util.Base64Encoder();           
java.lang.String encoded = null;          
encoded = encoder.encode(input_str);       
addAuditTrailEntry("encoded string = "+encoded);       
setVariableData("EncodeVar",encoded);       
} catch (Exception e) {       
  addAuditTrailEntry("Exception: "+e.getMessage());       
}       
addAuditTrailEntry("Encoded ended");


Pass the input variable name in the input string and create one more variable of 64binary format that will store the encoded string.


Now, we will decode the string that we encoded in previous step using below code:

addAuditTrailEntry("decoding started");
String encodedString = (String)getVariableData("EncodeVar");
Base64Decoder Decoder = new Base64Decoder();
addAuditTrailEntry("encoded String = "+encodedString);
try
{
String decoded = Base64Decoder.decode(encodedString);
addAuditTrailEntry("decoded string = "+decoded);  
setVariableData("Decodedvar",decoded);
}
catch(Exception e)
{
  addAuditTrailEntry("Exception: "+e.getMessage());
}




Create one more variable of string type that will contain the decoded string.In this case we will pass the variable we created in previous step as input.Decoded string will be stored in variable we created for storing decoded string.


Now, we will test our composite to verify the changes we have made.String passed is encoded using 1st java embedding activity and decoded using second java embedding java activity.





Happy Learning



                                                                                                                By Deepthi Reddy