http://www.developer.com/

Back to article

Mule - The Open Source Enterprise Integration Solution


March 26, 2009

Mule - The Open Source Enterprise Integration Solution?

Backgorund

Service Oriented Architecture (SOA) is a new architectural approach for building distributed systems that deliver application functionality as loosely coupled services. Till recently it was mere hype, but today it's a reality. The use of SOA has been moved from the laboratory level to enterprises level in order to seamlessly integrate disparate applications and create a common platform for carrying out mission critical business processes for the enterprises. The large enterprises are looking at SOA to maximize their returns by reducing complexity and cost of change and improving the leverage & reuse of assets within and outside the enterprise.

In order for enterprises to realize the benefits of SOA, the enterprises will need a robust infrastructure like Enterprise Service Bus (or simply ESB). What is an ESB? Wikipedia says "An ESB generally provides an abstraction layer on top of an implementation of an enterprise messaging system, which allows integration architects to exploit the value of messaging without writing code". The ESB forms the backbone of the SOA system and provides necessary infrastructure for building SOA applications. It acts as a transit system or bus through which different applications talk to each other using different protocols and message formats.

Readers, please understand this point clearly, The ESB does not attempt to implement SOA but provides the features such as connectivity, message routing, and transformation onto which futuristic applications can be built. It also helps in virtualizing business services and the virtualized services are then exposed to peers, business partners and customers. This promotes flexibility in the transport layer and enables loose coupling and easy connection between services.

Architecture

In order for us to call something an ESB, it should have some basic components and provide certain services. The following figure shows a typical ESB model. It contains enterprise data and applications which are virtualized and exposed to the external world as secured business processes and shared services.



Click here for larger image

Having set the context of ESB, this article attempts, in a high level, to provide a peek into certain issues with commercial ESBs and how "open source" ESBs such as Mule may be entrusted to do the required job.

Issues with Commercial ESB Products

Several major vendors provide implementations for ESB in the market as part of their SOA suites. However, these products are the evolution of their existing messaging products or extensions of their application servers. To put it simply, the vendor ESB implementations depend on their other propietary infrastructure and will lock in the customer forever. These products have been architected in a way that integration with other vendor's products is difficult and sometimes it may not be possible at all.

SOA is an architectural style and is not a product. However, vendors have been focusing on promoting their products in the SOA space instead of relying on SOA principles. Hence, the right selection of products is a must if you want to realize the full benefits of SOA. Otherwise, the enterprises will end up only in implementing what is popularly known as "Vendor Driven Architecture (VDA)".

Meantime, the commercial ESB products are often quite expensive. They provide turnkey solutions such as adapters for several legacy and today's other major enterprise integration issues. However, these products come with a high price tag.

Mule - Open Source ESB

Introduction to Mule

One alternative for commercial ESB could be a reliable, open source ESB. In the market, there are several open source products available that compete not only within the open source community but also with commercial ones. Mule ESB is one of the most prominent ESB products in the open source category and also claims to be the most used in the open source ESB product category.

Mule is open source, well documented, tried and tested. It is vendor neutral and can be plugged into any number of vendor implementations. It comes with built-in support for lots of protocols such as HTTP, JMS, SOAP, SMTP and many more. With the robust architecture that Mule has, it supports seamless integration of applications of different natures.

Different real world applications use different protocols and message formats. This can make the application integration really difficult. In order to solve this integration problem, Mule provides a framework that converts data into messages that get routed to other applications and the entire thing is controlled through configurations. The real advantage of this framework is that it separates the business logic (usually implemented by enterprises) from the messaging logic that is responsible for routing messages between applications. When the destination application needs a different message format, Mule uses constructs called "Transformations" that transforms the message from source format to destination format.

Mule also comes with lots of pre bundled transformers like XSLT. It also allows developers to plug in their own transformers within Mule context.

The following diagram shows a sample integration of applications that use different technologies and message formats.



Click here for larger image

Mule Components

In order to appreciate the value of Mule and use it effectively, you would need to understand its architecture and core components. This section attempts to provide a glimpse into the important Mule components.

Model

Model is like a container that manages the services. A model can contain any number of services and it allows a service to talk to another service.

Inbound router

Inbound routers specify how messages are routed to the service. The service can typically have any number of inbound routers. For example, one router may listen to HTTP and another one may listen to SOAP and so forth. Mule has lots of built-in inbound routers and hence the user will have to just configure the right router that he/she wants to use.

Service component

The service component can be of any type, from a POJO to an object in another framework, for example "Spring". An important note here is that the component does not need to contain any Mule specific code.

Outbound router

The outbound router will route the message to the next application. The routing of outbound messages may be controlled using Filters.

Filters

Filters control the routing of the message to the appropriate destinations. It specifies conditions which should be met by the message in order to get routed to a particular destination.

Transformers

Transforms transform data from one format to another format. They are required when the format/type of received data is different from what the service component expects. There are lots of built-in transformers within Mule. The user can also build his/her own transformers using the Mule Transformer APIs.

The following figure will show you the core components of a Mule service. Please note that for clarity purpose, only one service is shown in the Model. But in the real case, there can be more than one service within the Model.



Click here for larger image

Features

Mule's features give it the edge over its competitors. The features list includes but not limited to:

  • Mule service components can be of any type; from a POJO class to an object managed in another framework like spring
  • Existing components can be used as such without any change. Components do not need to contain any mule specific code.
  • Business logic (i.e., payload) is separated from the messaging logic that routes the payload between different applications.
  • Message can be of any type (POJO, Spring, etc.) and not necessarily as a SOAP message.
  • There is no vendor lock-in as Mule does not depend on a particular vendor and it can be integrated with any vendor infrastructure.
  • It provides connectivity over several protocols; HTTP, SOAP, JMS, SMTP, FTP, POP3 and many more.
  • It is content based and rules based routing.
  • It supports integration with Spring and BPM.

Sample - Expose POJO as Axis Web Service

Let's see how we can easily implement a sample scenario using Mule that would exemplify the core components such as routers and service components. The scenario is about a "Portfolio Manager" that manages stock market investor's stock portfolio.

Though there may be better way of implementing this, this sample implementation however aims to use a single component that is implemented as POJO and expose it over Axis Web Service. For benefit of understanding, Axis belongs to Apache Community and is a SOAP messaging framework that provides platform to develop web services and client utilities. For more information on Axis, please read http://ws.apache.org/axis.

Installation

You are required to download and install Mule for executing the sample programs. The binaries can be downloaded from this link http ://www.mulesource.org/display/MULE/Download. The installation of Mule is as simple as extracting the zip file into your local directory. Mule version 2.1.2 is what we used in implementing this sample.

Configuration

In order to expose as a service, you would need to choose an inbound router, service component and an optional outbound router. As Mule separates the data from messaging, coding is not required mostly and most of the work can be achieved using configurations itself. The following configuration shows how you can configure inbound and outbound routers along with the service component.

<mule …>
…
<custom-transformer name="LoginStatusToStringUsername"  class="samples.utils.LoginStatusToStringUsername"/>
…
…
<service name="PortfolioService">
            
<inbound>               
    <axis:inbound-endpoint address="http://localhost:7070/services"/> 
    <stdio:inbound-endpoint system="IN" />  
    <vm:inbound-endpoint path="portfolio" transformer-refs="LoginStatusToStringUsername"/>                             
            </inbound>            
            <component class="samples.services.PortfolioManager"/>
            <outbound>
      <pass-through-router>
                    <stdio:outbound-endpoint system="OUT"/>
                </ pass-through -router>
            </outbound>
        </service>
</mule>

The above xml file configures a service, namely, "PortfolioService". The service component is just a POJO class, named 'samples.services.PortfolioManager'. It uses three inbound routers to receive requests from other applications.

The first inbound router is "axis" that exposes the component as an Axis Web Service. After deploying the service, the WSDL can be accessed from http://localhost:7070/services/PortfolioService?wsdl. Mule takes care of things that are required to expose the component as service. Hence you just configure them and leave the worries of all the plumbing works involved in web service enablement to Mule.

The second inbound router is "stdio" (stands for Standard Input and Output) that receives requests from the Windows Console. While you start the Mule server, Mule will initialize the service and start an input stream listener that will read input from a windows console. Please be aware that this listener is only available for testing purpose and not recommended for production use.

The third inbound router is "vm" (stands for virtual machine) which can receive the requests from another application that runs in the same JVM. This router deserves more explanation as it uses transformation too. The "LoginStatusToStringUsername" transformer transforms "samples.businessobjects.LoginStatus" to "java.lang.String" (i.e. username that portfolio service expects). The assumption here is that the calling application would return the 'samples.businessobjects.LoginStatus' but the receiving application, (i.e., PortfolioService) need 'java.lang.String'. Hence it demands a transformer. The java code for the transformer (LoginStatusToStringUsername) is given below:

package samples.utils;
import org.mule.api.transformer.TransformerException;
import org.mule.transformer.AbstractTransformer;
import samples.businessobjects.LoginStatus;
public class LoginStatusToStringUsername extends AbstractTransformer {
 
 public LoginStatusToStringUsername() {
  super();
  this.registerSourceType(LoginStatus.class);
  this.setReturnClass(String.class);
 }
 
 protected Object doTransform(Object src, String encoding)
   throws TransformerException {
  LoginStatus status = (LoginStatus)src;
  if( status != null ){
   return status.getUsername();
  }  
  return "";   
 }
}

Now that we understand how easy it is to expose a component as an Axis web service and how the service component can also receive input from another mule component. Finally, the output of this component is routed to a Windows console. If required, the response can be routed to another mule component using following statement within the <outbound> element.

<outbound>
 <chaining-router>
  <vm:outbound-endpoint path="another_ application_inbound_router" />                    
                         <stdio:outbound-endpoint system="OUT"/>
 </chaining-router>
</outbound>

Service Component - POJO class

The service component is a simple POJO class named "sample.services.PortfolioManager" that has a single operation nameed'getPortfolio'. The operation takes 'username' as an input. Depending on the user name, the operation will return a different portfolio. The code snippet for PortfolioManager is given below:

package samples.services;
import java.util.Hashtable;
import java.util.Map;
public class PortfolioManager implements PortfolioManagerIntf{
 private static Map portfolioMap = new Hashtable();
 static{
  String stockDetailsPER = "Name: PER, Qty: 100, BoughtPrice: 12, CurrentPrice: 13";
  String stockDetailsHPQ = "Name: HPQ, Qty: 50, BoughtPrice: 20, CurrentPrice: 30";
  String stockDetailsIBM = "Name: IBM, Qty: 100, BoughtPrice: 60, CurrentPrice: 91";
  String stockDetailsWIT = "Name: WIT, Qty: 25, BoughtPrice: 35, CurrentPrice: 7";
  String stockDetailsINFY = "Name: INFY, Qty: 25, BoughtPrice: 35, CurrentPrice: 25";
  
  portfolioMap.put( "portfolio1", new String[]{ stockDetailsPER, stockDetailsHPQ, stockDetailsIBM } );
  portfolioMap.put( "portfolio2", new String[]{ stockDetailsPER, stockDetailsWIT, stockDetailsINFY } );
  portfolioMap.put( "portfolio3", new String[]{ stockDetailsPER } ); //default
 }
 
 public String[] getPortfolio( String username ) {
  String[] portfolioBO = null;  
  if( username == null || username.equals( "" ) ) {
   portfolioBO = (String[]) portfolioMap.get("portfolio3" );
  } else if( username.charAt( 0 ) <= 'm' || username.charAt( 0 ) <= 'M' )  {
   portfolioBO = (String[]) portfolioMap.get("portfolio1" );
  } else {
   portfolioBO = (String[]) portfolioMap.get("portfolio2" );
  }
  return portfolioBO;
 }
}

Build file

The following build file will help you compile all related classes and bundle them into a jar file. You could run the "ant jar" in a command prompt for deploying the mule component into the mule server (simply copying the jar into correct place in the mule installation). All that you need to do is to configure the "mule.home" property with the correct value.

<?xml version="1.0" ?>
<project name="mulesamples" default="jar">
<property name="mule.home" location="C:\Apps\MuleSource\mule-2.1.2" />
<property name="mule.lib.user.home" location="${mule.home}\lib\user" />
<property name="build.dest" location="build" />
<property name="mule.samples.jar" location="mule-samples.jar" />
<target name="clean">
 <delete file="${mule.samples.jar}"/>
</target>
<target name="jar" depends="clean">
 <jar destfile="${mule.samples.jar}"
       basedir="${build.dest}"
       includes="samples/**"
       excludes="**/Test.class" />  
  <copy todir="${mule.lib.user.home}" flatten="true">
      <resources>
        <file file="${mule.samples.jar}"/>
      </resources>
  </copy>
</target> 
</project>

Running samples

After Mule is installed and ant build is run with the target "jar", you are ready to start the Mule server. When the Mule server is started successfully, you can test it if you can access the WSDL successfully. For example, try accessing http://localhost:7070/services/PortfolioService?wsdl. You can use the following command for running the mule server.

call "%MULE_BASE%\bin\mule.bat" -config conf\mule-config.xml

Summary

Mule is open source ESB that comes with lot of pre-built bindings, adapters and transformers that helps in cutting development and integration cost to a great extent. The existing Java classes and Spring beans can be directly used within Mule without any change, because Mule separates messaging logic completely from the business logic. Exposing the application through different interfaces is really easy. Mule has existed for quite some time. It has improved a lot and become more robust over time.

A large community is available to help you and there is commercial support too. There are plenty of materials such as presentations, articles, tutorials which are available to get you started. It is easy to install, configure and use. It has a number of relevant features out of the box. The users can simply configure, codelessly, in most cases and use the features right out of the box.

References

Disclaimer

The views and opinions expressed in this article are entirely of the author's and do not necessarily represent the views of the company that he works for. The sample code and configuration are given for example purpose only and the author is not responsible for any potential loss of data or other damages. Please use the samples at your discretion.

About the author

Ayyappan Gandhirajan is working as an Architect with Perot Systems, Bangalore, India. He has a Masters degree in Software Systems from BITS, Pilani and a Bachelors degree in Electronics & Communications from MK University, India. He has more than 10 years of profound experience in architecting, designing and implementing multi-tier applications using Service Oriented Architecture (SOA), Web Services, JAVA, JEE, IBM, BEA and Open Source stack of products. He can be reached at G_Ayyapparaj@yahoo .com or Ayyappan .Gandhirajan@ps.net.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date