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

How to protect your APIs with self contained access token (JWT) using WSO2 API Manager and WSO2 Identity Server

In a typical enterprise information system, there is a high chance that people will use different types of systems built by different vendors to implement certain types of functionalities. The APIs might be hosted in an API Manager developed by vendor A and the user management can be implemented using a different vendor (vendor B). In this type of a situation, one system will not be able to directly contact the other system but they want to use both systems in tandem. Self-contained access tokens are used in these types of situations where applications can get the token from one system and use that in another system to access protected resources. In this scenario, the second system does not need to make a contact to the first system over the network to validate the user information since the token is self-contained and it has relevant details about the user. This will improve the token processing time significantly since it completely removes the network interaction. The below fig...

WSO2 ESB creating a response for a "GET" request

When you are creating REST APIs with WSO2 ESB, you may need to send some response message back to the user when something goes wrong. In this kind of scenario, you can create a payload inside the ESB and send it back. For doing this, you can use the below configuration. <api xmlns=" http://ws.apache.org/ ns/synapse " name="LoopBackProxy" context="/loopback">    <resource methods="POST GET">       <inSequence>          <property name="NO_ENTITY_BODY" scope="axis2" action="remove"></property>          <log level="full"></log>          <payloadFactory media-type="xml">             <format>                <m:messageBeforeLoopBack xmlns:m=" http://services...

WSO2 ESB usage of get-property function

What are Properties? WSO2 has a huge set of mediators but property mediator is mostly used mediator for writing any proxy service or API. Property mediator is used to store any value or xml fragment temporarily during life cycle of a thread for any service or API. We can compare “Property” mediator with “Variable” in any other traditional programming languages (Like: C, C++, Java, .Net etc). There are few properties those are used/maintained by ESB itself and on the other hand few properties can be defined by users (programmers). In other words, we can say that properties can be define in below 2 categories: ESB Defined Properties User Defined Properties. These properties can be stored/defined in different scopes, like: Transport Synapse or Default Axis2 Registry System Operation Generally, these properties are read by get-properties() function. This function can be invoked with below 2 variations. get-property(String propertyName) get-property(String scop...