Friday, May 13, 2016

Invoke a BPEL workflow from WSO2 ESB proxy service


In this blog post I will illustrate how to invoke a BPEL workflow from a proxy service using WSO2 ESB.

1. Deploy a BPEL process on WSO2 BPS Server. (Login to the BPS Management Console and go to Processes -> Add then select the BPEL Archive(zip) file and upload it. If your BPEL process has external web service invocations, you can be hosted those web services WSO2 App Server or axis2Server)

2. Start WSO2 ESB Server and create a custom proxy as below. (Change the port offset to avoid conflicts with the WSO2 BPS Server).

<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
       name="bpel_factory"
       transports="https,http"
       statistics="disable"
       trace="disable"
       startOnLoad="true">
   <target>
      <inSequence>
         <payloadFactory media-type="xml">
            <format>
               <p:MultiOperatorServiceRequest xmlns:p="http://wso2.org/bps/operator"><!--Exactly 1 occurrence--><x xmlns="http://wso2.org/bps/operator">$1</x>
                  <!--Exactly 1 occurrence--><y xmlns="http://wso2.org/bps/operator">$2</y>
               </p:MultiOperatorServiceRequest>
            </format>
            <args>
               <arg xmlns:m="http://wso2.org/bps/operator"
                    evaluator="xml"
                    expression="//m:MultiOperatorServiceRequest/x"/>
               <arg xmlns:m="http://wso2.org/bps/operator"
                    evaluator="xml"
                    expression="//m:MultiOperatorServiceRequest/y"/>
            </args>
         </payloadFactory>
         <send>
            <endpoint>
               <address uri="http://10.100.7.75:9763/services/MultiOperatorService.MultiOperatorServicehttpMultiOperatorServiceBindingEndpoint/"/>
            </endpoint>
         </send>
      </inSequence>
      <outSequence>
         <log level="full"/>
         <respond/>
      </outSequence>
   </target>
   <description/>
</proxy>
                     
Here you can find out the address URL in SOAP-UI after clicking on the TryIt wizard in WSO2 BPS Server.  Payload factory mediator is used to transform the payload in incoming request to the appropriate format that allow by the request for the BPEL process invocation.

you can copy and paste the request body in the SOAP-UI to the format element in payload factory mediator and replace ? with the arguments defined in the message context.  

3. Next you can send a POST request with the payload to the proxy service and see the response as following figure.


In this example I used a BPEL process to solve [(x * y) - (x + y)]^2  formula.
eg: x=5, y=3 =>[(5 * 3) - (5 + 3)]^2 => 49.0


Wednesday, May 11, 2016

Send SMS through WSO2 Twilio Connector

Introduction


The WSO2 Twilio connector allows us to connect to Twilio, an online service that lets us embed phones, VoIP, and messaging in web, desktop, and mobile software. The connector uses the Twilio REST API to connect to Twilio and work with accounts, applications, calls, messages, and more. The underlying Java classes in the connector use the Twilio Java Helper Library to make the HTTP requests to the Twilio API.

How to enable Twilio Connector ?


1. Download the Connector from here.
2. Upload the connector to the ESB instance as below.


3. Once the connector is successfully uploaded, it's required to “enable” the connector in order to activate. For that click on List under Connectors in Main tab and click on disabled in Status column to enable it.


Example


This example basically describes how to send an SMS through Twilio utilizing WSO2 Twilio Connector. First of all you should have to setup a trial account to test this scenario in Twilio if you haven't an account yet please create one. Once you created an account you can able to get Account SID and Auth Token when you go to Dashboard Console. These tokens are essential to initialize the connector in your Proxy Service.

For enabling a phone number to send and receive SMS in Twilio click here. Please refer this  for more information.

To use the Twilio connector, add the <twilio.init> element in your configuration before any other Twilio operations. This Twilio configuration authenticates with Twilio by specifying the SID and auth token of your master Twilio account. You can find your SID and token by logging into your Twilio account and going to the API Credentials section on the dashboard.

<twilio.init>
    <accountSid>ACba8bc05eacf94afdae398e642c9cc32d</accountSid>
    <authToken>AC5ef8732a3c49700934481addd5ce1659</authToken>
</twilio.init>

For best results, save the Twilio configuration as a local entry. You can then easily reference it with the configKey attribute in your Twilio operations. For example, if you saved the above <twilio.init> entry as a local entry named MyTwilioConfig, you could reference it from an operation like as follows.

1. Go to Local Entries under Service Bus in Main tab and click on Add Local Entries.
2. Then Click on Add in-lined XML Entry and give configuration as below.


3. Now click on Save button to save the content.

4. Configure your proxy as below.

<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
       name="testTwillio"
       transports="https http"
       startOnLoad="true"
       trace="disable">
   <description/>
   <target>
      <inSequence>
         <property name="name"
                   expression="get-property('myName')"
                   scope="default"
                   type="STRING"/>
         <property name="phone"
                   expression="get-property('myPhone')"
                   scope="default"
                   type="STRING"/>
         <property name="smsContent"
                   expression="fn:concat('WSO2 Twilio Connector : SMS Generated! - Name : ', get-property('name'))"
                   scope="default"
                   type="STRING"/>
         <twilio.sendSms configKey="MyTwilioConfig">
            <body>{get-property('smsContent')}</body>
            <to>{get-property('phone')}</to>
            <from>+14843160720</from>
         </twilio.sendSms>
         <respond/>
      </inSequence>
   </target>
</proxy>

If configKey is not saved or updated, please go to <ESB_HOME>/repository/deployment/server/synapse-configs/default/proxy-services directory and open your proxy service xml file and apply changes there and save it.

5. For testing the proxy service, click on Try this service and Send the message via SOAP UI.



6. Finally you can see the server output as below.



Tuesday, May 10, 2016

Task scheduling through WSO2 ESB 4.9.0

Introduction

WSO2 ESB is capable of scheduling and executing tasks periodically. A task can be scheduled to run n number of times in a given t time duration. Also we can schedule a task to run just once after WSO2 ESB starts. If we want to get more control in task scheduling then we can use cron-expression. Let's say as an example we can schedule a task to run everyday at 5 PM or on 25th at 5 PM every month, likewise.

Example

As a first step we have to create a sample back-end service. Here I use a sample service which exists in WSO2 ESB samples folder.

step 1


If you go to  <ESB_HOME>/samples/axis2Server/src  directory,  you will see several back-end samples are available there. They can be built and deployed using Ant from each service directory. You can do this by typing "ant" without quotes on a console from a selected sample directory.  Here I will choose SimpleStockQuoteService service.


Step 2 


As a next step, go to <ESB_HOME>/samples/axis2Server directory and execute axis2server.sh (for Linux) to start the Axis 2 server. This starts the Axis2 server with the HTTP transport listener on port 9000 and HTTPS on 9002 respectively.

Step 3 


Now add a sample sequence in the WSO2 ESB as below.
Click on Sequences under Service Bus in Manage menu and click Add Sequences



Then switch to the source view by clicking on  switch to source view and replace the following content and click save and close button to save the content.

<?xml version="1.0" encoding="UTF-8"?>
<sequence name="iterateSequence" xmlns="http://ws.apache.org/ns/synapse">
    <iterate attachPath="//m0:getQuote"
        expression="//m0:getQuote/m0:request" preservePayload="true"
        xmlns:m0="http://services.samples"
        xmlns:ns="http://org.apache.synapse/xsd" xmlns:ns3="http://org.apache.synapse/xsd">
        <target>
            <sequence>
                <call>
                    <endpoint>
                        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                    </endpoint>
                </call>
                <log level="custom">
                    <property
                        expression="//ns:return/ax21:lastTradeTimestamp/child::text()"
                        name="Stock_Quote_on" xmlns:ax21="http://services.samples/xsd"/>
                    <property
                        expression="//ns:return/ax21:name/child::text()"
                        name="For_the_organization" xmlns:ax21="http://services.samples/xsd"/>
                    <property
                        expression="//ns:return/ax21:last/child::text()"
                        name="Last_Value" xmlns:ax21="http://services.samples/xsd"/>
                </log>
            </sequence>
        </target>
    </iterate>
</sequence>



Step 4 


As a next step, add a Scheduled Task by clicking on Scheduled Tasks under Service Bus in Manage menu. And set its configuration as below.


Step 5


As final step click on Schedule button and task will start execution according to the Interval. Here in this example task will run 50 times and start in 10 seconds. 

Friday, May 6, 2016

Service Task Example in WSO2 Business Process Server

This tutorial illustrates how to model a business process with Service Tasks. Here as an example I will describe a sample bonus payment process.

Steps of the use-case


1. Obtaining the customer information with their salary and working period
2. Adding (working period * random number) to the salary of the employee
3. Manager approval (approve/reject) the bonus amount

The above components can be matched with the components in activiti pallet section as below.

Start Event : Filling the details about the employee such as employee id, name, salary and the working period.
Service Task : use to automate the calculation mention in step 2
User Task : is used to approve or reject the bonus amount for the given employee

Prerequisites


  • Java
  • WSO2 BPS
  • Eclipse activiti-designer plugin

Implementing the java class  to be used in Service Task


First create a maven project in eclipse and apply the following dependency to the pom.xml file.
(The jar file should be copied into <BPS_HOME>/repository/components/lib folder before starting the BPS Server)

<dependency>
<groupId>org.activiti</groupId>
<artifactId>activiti-engine</artifactId>
<version>5.19.0</version>
</dependency>

Java class implementation.

package org.wso2.bps.serviceTask;

import java.util.Random;

import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;

/**
 * Service task to calculate Bonus for employees
 *
 */
public class App implements JavaDelegate {
public void execute(DelegateExecution execution) throws Exception {
int salary = Integer.parseInt((String) execution.getVariable("employeeSalary"));
int numOfWorkingDays = Integer.parseInt((String) execution.getVariable("workingPeriod")); 
Random randomGenerator = new Random();
int value = randomGenerator.nextInt(10);
int result = salary + (numOfWorkingDays * value);
execution.setVariable("result", result);
}
}

Modeling the process utilizing eclipse activiti-designer tool


First create an activiti project in eclipse (See the steps below)

  1. Go to File -> New -> Other - > Activiti and select Activiti Project.
  2. Then enter activiti project name and click Finish.
  3. Right click on the created project and select New -> Other -> Activiti Diagram and click Next.
  4. Give a name for the process and click Finish.


Design the user-case using the pallet components dragging and dropping to the canvas layer in the tool as showing in the following figure.

Configuration of each components


Configure properties tab of the start event as below.

Form tab - Define the variables to be initialized in the start event


Main config tab -  Define the initiator of the process




 Configure properties tab of the service task as below.

Main config tab - the relevant java class that contains the logic should be specified here.  You should have to create the java class before configure the main config of the service task. (I will explain this class implementation later.)



Configure the properties tab of the user task as below.

Form tab
(Here the result variable coming from the Service task)


Main config tab - Assign a candidate group for the user task. For the claiming purpose you should have to create a user and assign the candidate group role to him and login with the newly created user to approve the bonus amount when process execution comes to the user task.



Save the project and right click on the activiti project in package-explorer in eclipse and click Create Deployment Artifacts.

Now you can see that a .bar file is generated inside of the deployment folder in the project.


Deploying and testing the bonus payment process using WSO2 BPS 


Start the BPS Server
Log in the management console and navigate to Home>Manage>Add>BPMN. Upload the .bar file to deploy it as seen below. 



Create a new user called kermit and assign him to the bonusApproval role.







Login to the BPMN-explorer using admin/admin credentials (default admin user credentials) and start the bonus payment Process.






Now login to the BPMN-explorer using kermit/kermit credentials to approve the bonus payment.