Skip to main content

10 Minute tutorial for extending the WSO2 ESB

WSO2 ESB is a smart, light-weight enterprise integration engine which you can use to accomplish most of your enterprise level integration scenarios. You can have a good understanding on the usage of the WSO2 ESB from this tutorial. Here I am going to discuss about extending the basic functionality of the WSO2 ESB by interfering the messages received from  the ESB.

What is a Custom Mediator?


Enterprise Service Bus (ESB) is basically a message mediation engine in which messages are received from different applications and then processed and route them to another application or server. WSO2 ESB provides a rich set of functions for achieving the message mediation requirements a specific enterprise might encounter. But as in other aspects of the life, there can be exceptions. Sometimes you may need to extend the functionality of the ESB to your specific requirement. Custom mediator is a simple Java code we write for this purpose.

How to write a Custom Mediator?


First you need to create a java class file to infer the mediation work flow by extending the AbstractMediator class. Here is an example class you can use to interfere

package org.wso2.carbon.mediator;
import org.apache.synapse.MessageContext;
import org.apache.synapse.Mediator;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.xml.namespace.QName;
public class DiscountQuoteMediator implements Mediator {
    private static final Log log = LogFactory.getLog(DiscountQuoteMediator.class);
    private String discountFactor="10";
    private String bonusFor="10";
    private int bonusCount=0;
    public DiscountQuoteMediator(){}
    public boolean mediate(MessageContext mc) {
        String price= mc.getEnvelope().getBody().getFirstElement().getFirstElement().
                getFirstChildWithName(new QName("http://services.samples/xsd","last")).getText();
        //converting String properties into integers
        int discount=Integer.parseInt(discountFactor);
        int bonusNo=Integer.parseInt(bonusFor);
        double currentPrice=Double.parseDouble(price);
        //discounting factor is deducted from current price form every response
        Double lastPrice = new Double(currentPrice - currentPrice * discount / 100);
        //Special discount of 5% offers for the first responses as set in the bonusFor property
        if (bonusCount <= bonusNo) {
            lastPrice = new Double(lastPrice.doubleValue() - lastPrice.doubleValue() * 0.05);
            bonusCount++;
        }
        String discountedPrice = lastPrice.toString();
        mc.getEnvelope().getBody().getFirstElement().getFirstElement().getFirstChildWithName
                (new QName("http://services.samples/xsd","last")).setText(discountedPrice);
        System.out.println("Quote value discounted.");
        System.out.println("Original price: " + price);
        System.out.println("Discounted price: " + discountedPrice);
        return true;
    }
    public String getType() {
        return null;
    }
    public void setTraceState(int traceState) {
        traceState = 0;
    }
    public int getTraceState() {
        return 0;
    }
    public void setDiscountFactor(String discount) {
        discountFactor=discount;
    }
    public String getDiscountFactor() {
        return discountFactor;
    }
    public void setBonusFor(String bonus){
        bonusFor=bonus;
    }
    public String getBonusFor(){
        return bonusFor;
    }
}

How to build your Custom mediator for deploy in WSO2 ESB?


Now you have written the class for adding a surcharge value to the receiving message using the above java class. Now you need to package this in to a jar file and copy that to the classpath of the WSO2 ESB. For this you can use two approaches for building the jar file.

1. Create the mediator as a jar file

All you need to do is package your java class files using the following maven script. Just create the following folder structure and run the following command in your parent directory which contains the pom file.

Create a folder called src/main/java/org/wso2/carbon/mediator. Place the source file inside src/main/java/org/wso2/carbon/mediator and pom.xml at the same level as src folder. 


directory structure
================

classmediator(Your folder)
        - src/main/java/org/wso2/carbon/mediator/DiscountQuoteMediator.java
        -pom.xml

pom.xml
================

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.wso2.carbon.mediator</groupId>
<artifactId>org.wso2.carbon.mediator</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>org.wso2.carbon.mediator</name>
<url>http://maven.apache.org</url>
<repositories>
       <repository>
           <id>wso2-maven2-repository</id>
           <url>http://dist.wso2.org/maven2</url>
       </repository>
       <repository>
           <id>apache-Incubating-repo</id>
           <name>Maven Incubating Repository</name>
           <url>http://people.apache.org/repo/m2-incubating-repository</url>
       </repository>
       <repository>
           <id>apache-maven2-repo</id>
           <name>Apache Maven2 Repository</name>
           <url>http://repo1.maven.org/maven2/</url>
       </repository>
   </repositories>

   <build>
       <plugins>
           <plugin>
               <groupId>org.apache.maven.plugins</groupId>
               <artifactId>maven-compiler-plugin</artifactId>
               <version>2.0</version>
               <configuration>
                   <source>1.5</source>
                   <target>1.5</target>
               </configuration>
           </plugin>
       </plugins>
   </build>

   <dependencies>
       <dependency>
           <groupId>org.apache.synapse</groupId>
           <artifactId>synapse-core</artifactId>
           <version>2.1.1-wso2v7</version>
       </dependency>
   </dependencies>
</project>

By issuing the command mvn clean install you should be able to compile the source. Resulting jar file will be created at target folder. 

Now copy the jar file into ESB_HOME/repository/components/lib folder.


2. Create the mediator as an osgi bundle.

This is the recommended way of deploying custom mediators in WSO2 ESB. All you need to do is package your java class files using the following maven script. Just create the following folder structure and run the following command in your parent directory which contains the pom file.

Create a folder called src/main/java/org/wso2/carbon/mediator. Place the source file inside src/main/java/org/wso2/carbon/mediator and pom.xml at the same level as src folder. 


directory structure
================

classmediator(Your folder)
        - src/main/java/org/wso2/carbon/mediator/DiscountQuoteMediator.java
        -pom.xml

pom.xml
=================

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.wso2.carbon.mediator</groupId>
<artifactId>org.wso2.carbon.mediator</artifactId>
<packaging>bundle</packaging>
<version>1.0-SNAPSHOT</version>
<name>org.wso2.carbon.mediator</name>
<url>http://maven.apache.org</url>
 <repositories>
         <repository>
             <id>wso2-maven2-repository</id>
             <url>http://dist.wso2.org/maven2</url>
         </repository>
         <repository>
             <id>apache-Incubating-repo</id>
             <name>Maven Incubating Repository</name>
             <url>http://people.apache.org/repo/m2-incubating-repository</url>
         </repository>
         <repository>
             <id>apache-maven2-repo</id>
             <name>Apache Maven2 Repository</name>
             <url>http://repo1.maven.org/maven2/</url>
         </repository>
     </repositories>

     <build>
         <plugins>
             <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-compiler-plugin</artifactId>
                 <version>2.0</version>
                 <configuration>
                     <source>1.5</source>
                     <target>1.5</target>
                 </configuration>
             </plugin>
             <plugin>
                 <groupId>org.apache.felix</groupId>
                 <artifactId>maven-bundle-plugin</artifactId>
                 <version>1.4.0</version>
                 <extensions>true</extensions>
                 <configuration>
                     <instructions>
                         <Bundle-SymbolicName>org.test</Bundle-SymbolicName>
                         <Bundle-Name>org.test</Bundle-Name>
                         <Export-Package>
                             org.wso2.carbon.mediator.*,
                         </Export-Package>
                         <Import-Package>
                             *; resolution:=optional
                         </Import-Package>
                     </instructions>
                 </configuration>
             </plugin>
         </plugins>
     </build>

     <dependencies>
         <dependency>
             <groupId>org.apache.synapse</groupId>
             <artifactId>synapse-core</artifactId>
             <version>2.1.1-wso2v7</version>
         </dependency>
     </dependencies>
</project>

By issuing the command mvn clean install you should be able to compile the source. Resulting jar file will be created at target folder. 

Now copy the jar file into ESB_HOME/repository/components/dropins/ folder.

How to test your Custom Mediator working?



Now you have successfully created and deployed the Custom mediator. Now start the ESB and send a sample request to see your mediator working.


ant stockquote -Dsymbol=IBM -Dmode=quote -Daddurl=http://localhost:8280

(You need to setup the backend service using this sample guide)

Comments

Popular posts from this blog

WSO2 ESB tuning performance with threads

I have written several blog posts explaining the internal behavior of the ESB and the threads created inside ESB. With this post, I am talking about the effect of threads in the WSO2 ESB and how to tune up threads for optimal performance. You can refer [1] and [2] to understand the threads created within the ESB. [1] http://soatutorials.blogspot.com/2015/05/understanding-threads-created-in-wso2.html [2] http://wso2.com/library/articles/2012/03/importance-performance-wso2-esb-handles-nonobvious/ Within this blog post, I am discussing about the "worker threads" which are used for processing the data within the WSO2 ESB. There are 2 types of worker threads created when you start sending the requests to the server 1) Server Worker/Client Worker Threads 2) Mediator Worker (Synapse-Worker) Threads Server Worker/Client Worker Threads These set of threads will be used to process all the requests/responses coming to the ESB server. ServerWorker Threads will be used to pr

How puppet works in your IT infrstructure

What is Puppet? Puppet is IT automation software that helps system administrators manage infrastructure throughout its lifecycle, from provisioning and configuration to orchestration and reporting. Using Puppet, you can easily automate repetitive tasks, quickly deploy critical applications, and proactively manage change, scaling from 10s of servers to 1000s, on-premise or in the cloud. How the puppet works? It works like this..Puppet agent is a daemon that runs on all the client servers(the servers where you require some configuration, or the servers which are going to be managed using puppet.) All the clients which are to be managed will have puppet agent installed on them, and are called nodes in puppet. Puppet Master: This machine contains all the configuration for different hosts. Puppet master will run as a daemon on this master server. Puppet Agent: This is the daemon that will run on all the servers, which are to be managed using p

How to configure timeouts in WSO2 ESB to get rid of client timeout errors

WSO2 ESB has defined some configuration parameters which controls the timeout of a particular request which is going out of ESB. In a particular  scneario, your client sends a request to ESB, and then ESB sends a request to another endpoint to serve the request. CLIENT->WSO2 ESB->BACKEND The reason for clients getting timeout is that ESB timeout is larger than client's timeout. This can be solved by either increasing the timeout at client side or by decreasing the timeout in ESB side. In any of the case, you can control the timeout in ESB using the below properties. 1) Global timeout defined in synapse.properties (ESB_HOME\repository\conf\) file. This will decide the maximum time that a callback is waiting in the ESB for a response for a particular request. If ESB does not get any response from Back End, it will drop the message and clears out the call back. This is a global level parameter which affects all the endpoints configured in ESB. synapse.global_timeout_inte