Anda di halaman 1dari 601

Space Details

Key: MULE2USER
Name: Mule 2.x User Guide
Description: Mule Users Guide for the 2.x release line

Creator (Creation Date): ross (Jan 30, 2008)


Last Modifier (Mod. Date): tcarlson (Apr 15, 2008)
Available Pages
• Using Expressions
• Expressions Configuration Reference
• Home
• About Transports
• Available Transports
• BPM Transport
• CXF Transport
• Building a CXF Web Service
• CXF Transport Configuration Reference
• Enabling WS-Addressing
• Enabling WS-Security
• Proxying Web Services
• Using a Web Service Client as an Outbound Endpoint
• Using a Web Service Client Directly
• Using HTTP GET Requests
• Using MTOM
• EJB Transport
• Email Transport
• File Transport
• FTP Transport
• HTTP Transport
• HTTPS Transport
• IMAP Transport
• IMAPS Transport
• JDBC Transport
• JDBC Transport Examples
• JDBC Transport Performance Benchmark Results
• Jetty Transport
• Jetty SSL transport
• JMS Transport
• Mule WMQ Transport
• Multicast Transport
• PGP Module
• POP3 Transport
• POP3S Transport

Document generated by Confluence on Oct 27, 2008 21:07 Page 1


• Quartz Transport
• RMI Transport
• Servlet Transport
• SMTP Transport
• SMTPS Transport
• SOAP Transport
• SSL Transport
• STDIO Transport
• TCP Transport
• UDP Transport
• VM Transport
• WSDL Transport
• XMPP Transport
• Choosing the Right Topology
• Configuration Overview
• Configuration Reference
• Asynchronous Reply Router Configuration Reference
• Catch All Strategy Configuration Reference
• Component Configuration Reference
• Endpoint Configuration Reference
• Exception Strategy Configuration Reference
• Filters Configuration Reference
• Global Settings Configuration Reference
• Inbound Router Configuration Reference
• Model Configuration Reference
• Notifications Configuration Reference
• Outbound Router Configuration Reference
• Properties Configuration Reference
• Service Configuration Reference
• Transactions Configuration Reference
• Configuring a Mule Instance
• Configuring Endpoints
• Mule Endpoint URIs
• Using Filters
• Configuring a Transport
• Configuring Retry Policies
• Configuring Security
• Controlling the Infrastructure with Mule Galaxy
• Creating a Custom XML Namespace
• Creating Additional Extensions
• Project Archetype
• Creating Custom Routers

Document generated by Confluence on Oct 27, 2008 21:07 Page 2


• Creating Custom Transformers
• Creating Transports
• Transport Archetype
• Customizing a Transport
• Deployment Scenarios
• Deploying Mule to WebLogic
• Deploying Mule to WebSphere
• Embedding Mule in a Java Application or Webapp
• JBoss Integration
• Mule as MBean
• Developing Service Components
• Entry Point Resolver Configuration Reference
• Error Handling
• Functional Testing
• Installing a Standalone Mule Instance
• Installing Upgrades and Hot Fixes
• Internationalizing Strings
• Introduction to Extending Mule
• Introduction to Testing Mule
• JavaRebel Integration
• Jmx Management
• Models
• Mule Agents
• Mule Instances
• Mule Server Notifications
• Offline Documentation
• Profiling Mule
• Resource Adapter
• Streaming
• Suggested Reading
• Third-party Software in Mule
• Transaction Management
• Transport Service Descriptors
• Tuning Performance
• Unit Testing
• Using IDEs
• Using JMS with Mule
• Configuring JMS
• ActiveMQ Integration
• Fiorano Integration
• Integrating SwiftMQ with Mule
• JBoss Jms Integration

Document generated by Confluence on Oct 27, 2008 21:07 Page 3


• OpenJms Integration
• SeeBeyond JMS Server Integration
• SonicMQ Integration
• Sun JMS Grid Integration
• Tibco EMS Integration
• WebLogic JMS Integration
• WebSphere MQ Integration
• Using Mule HQ
• Installing Mule HQ with an External Database
• Mule HQ Agent Settings
• Using Mule Modules
• Acegi Module
• JAAS Module
• JBoss Transaction Manager
• Scripting Module
• Spring Extras Module
• SXC Module
• XML Module
• Using Mule with Spring
• Sending and Receiving Mule Events in Spring
• Using Spring Beans as Service Components
• Using the Mule Client
• Using the Mule RESTpack
• Architecting RESTful HTTP applications
• Making Sense of REST
• Using Transformers
• DomToXml Transformer
• JXPath Transformer
• Transformers Configuration Reference
• XmlObject Transformers
• XmlPrettyPrinter Transformer
• XSLT Transformer
• Web Services
• Axis
• Axis SOAP Styles
• Axis SOAP Transports
• Axis Transport
• Axis Web Services and Mule
• Configuring Axis
• Using .NET Web Services with Mule
• Web Service Wrapper
• Working with Services
• Configuring Components

Document generated by Confluence on Oct 27, 2008 21:07 Page 4


• Configuring Java Components
• Configuring the Service
• MEPs
• Mule Messaging Styles
• Using Message Routers
• Component Bindings
• Using the WireTap Inbound Router
• XML Configuration
• Escape URI Credentials
• PGP Security
• Jaas Security
• Setting up LDAP Provider for Acegi
• Component Authorization Using Acegi
• Architecture Guide
• Explanation of MULE_SERVICE_METHOD

Document generated by Confluence on Oct 27, 2008 21:07 Page 5


Using Expressions

This page last changed on Oct 24, 2008 by jackie.wheeler.

Using Expressions
[ Using Expressions with Transformers ] [ Using Expression Filters ] [ Using Expression Routers ] [ Adding
Expression Support to Custom Modules ] [ Creating Custom Expression Evaluators ]

This page is ready for review

Expressions allow you to extract information from the current message or determine how to handle the
message. Expressions are very useful with routers and filters for defining routing logic and for filtering
out unwanted messages.

Mule provides several default expression evaluators, allowing you to embed expression logic in a variety
of expression languages, or you can create your own evaluators to support additional languages.

This page describes how to use expressions and how to create custom expression evaluators. For more
details on how to configure expressions, see Expressions Configuration Reference.

Using Expressions with Transformers


This section describes the transformers that support expressions. For more information on transformers,
see Using Transformers.

Expression Transformer

The expression transformer executes one or more expressions on the current message where the result
of the expression(s) will become the payload of the current message.
For example, imagine you have a service component with a message signature that accepts three
arguments:

Public class ShippingService


{
public ShippingConfirmation makeShippingRequest(Customer customer, Item[] items, DataHandler
supportingDocumentation)
{
//do stuff
}
}

And the message being passed to you component looks like this:

public interface ShippingRequestMessage


{
public Customer getCustomer();
public Item[] getShippingItems();
//etc
}

The <expression-transformer> can be used to extract the fields from the ShippingRequestMessage
to invoke the ShippingService. Note that we can only get two of the arguments from the
ShippingRequestMessage: Customer and Item[]. The supporting documentation, which could be
something like a Microsoft Word or Excel document, is an attachment to the ShippingRequestMessage.
Attachments can be associated with any message within Mule.

<expression-transformer>
<return-argument evaluator="bean" expression="customer"/>
<return-argument evaluator="bean" expression="shippingItems"/>
<return-argument evaluator="attachment" expression="supportingDocs" required="false"/>
</expression-transformer>

Document generated by Confluence on Oct 27, 2008 21:07 Page 6


Here we execute three separate expressions to obtain the three arguments required to invoke the
ShippingService.makeShippingRequest() method. The first two expressions use the bean evaluator
to extract objects from the message. The last argument uses the attachment evaluator to obtain a
single attachment. Note that supportDocuments can be null, so we set required="false" on the return
argument.

Message Properties Transformer

The <message-properties-transformer> allows you to add, remove, or rename properties dynamically


or statically on the current message. For example:

<message-properties-transformer>
<add-property name="GUID" value="#[xpath:/msg/header/ID]-#[xpath:/msg/body/@ref]"/>
</message-properties-transformer>

The above expressions extract the <ID> element value and the ref attribute on the <body> element,
setting the result as a message property named GUID.

XSLT Transformer

The XSLT transformer processes the XML payload of the message through XSLT. Using expressions, you
can inject information about the current message into the XSLT as a parameter. For example:

<mulexml:xslt-transformer name="xslt" xslFile="./conf/xsl/cd-listing.xsl">


<mulexml:context-property key="title" value="#[header:ListTitle]"/>
<mulexml:context-property key="rating" value="#[header:ListRating]"/>
</mulexml:xslt-transformer>

When executed, the headers ListTitle and ListRating from the current message are added to the
XSLT context as parameters called title and rating, respectively. You can reference these parameters
inside the XSLT using the <xsl:param> element:

<xsl:param name="title"/>
<xsl:param name="rating"/>

Using Expression Filters


Expression filters can be used in content-based routing to assert statements on the current message and
route the message accordingly. Expression filters work in the same way as other types of Mule filters and
have the same expression attributes as listed above. The expression on the filter must evaluate to true or
false. For example:

<expression-filter evaluator="header" expression="my-header!=null"/>

As usual, you can use AND, OR, and NOT filters to combine expressions.

<and-filter>
<expression-filter evaluator="header" expression="origin-country=USA"/>
<expression-filter evaluator="groovy" expression="payload.purchase.amount > 10000"/>
</and-filter>

Note that expression filters support a sub-set of all expression evaluators, because filters should only
evaluate against the current message. For example, there is no point in using a function expression on
a filter. The supported expression evaluators are: bean, custom, exception-type, groovy, header, jxpath,
ognl, payload-type, regex, wildcard, and xpath. For more information on expression evaluators, see
Expressions Configuration Reference.

For more information on filters, see Using Filters.

Document generated by Confluence on Oct 27, 2008 21:07 Page 7


Using Expression Routers
Expression routers use expressions to determine where to route a message. Usually, outbound routers
will support expressions. This section describes each of the Mule routers that support expressions. For
more information on routers, see Using Message Routers.

Expression Recipient List Router

The <expression-recipient-list> router will evaluate an expression on the current message to obtain
a list of one or more recipients to send the current message. Following is an example of an XML message:

<message>
<header>
<routing-slip>
<recipient>http://mycompany.com/service1</recipient>
<recipient>http://mycompany.com/service2</recipient>
</routing-slip>
</header>
<body>
...
<body>
</message>

The following router configuration extracts recipients from this message. This type of routing is commonly
referred to as content-based routing.

<outbound>
<expression-recipient-list-router evaluator="xpath" expression="/message/header/routing-slip/
recipient" />
</outbound>

Best Practice

This example uses physical addresses for endpoints in the message. In a real production
scenario, you would use logical endpoint names that map to physical endpoint addresses.
These can be configured in your Mule configuration file or in the Mule Galaxy centralized
registry.

Expression Message Splitter Router

The <expression-message-splitter> router can be used to route different parts of the current message
to different destinations. Let's say our current message is a FruitBowl that contains different fruit that
should be delivered to different places.

FruitBowl fruitBowl = new FruitBowl();


fruitBowl.addFruit(new Orange());
fruitBowl.addFruit(new Apple());
fruitBowl.addFruit(new Banana());
fruitBowl.addFruit(new Banana());

Now we have a FruitBowl containing an apple, an orange, and two bananas. When Mule receives
this object, we want to route the fruit to different locations: the AppleService, BananaService, and
OrangeService.

<service name="Distributor">
<inbound>
<jms:inbound-endpoint queue="distributor.queue"/>
</inbound>
<outbound>
<!-- FruitBowl.getFruit() List -->
<expression-splitter-router evaluator="bean" expression="fruit">
<vm:outbound-endpoint path="apple.service.queue">
<payload-type-filter expectedType="org.mule.tck.testmodels.fruit.Apple"/>
</vm:outbound-endpoint>

Document generated by Confluence on Oct 27, 2008 21:07 Page 8


<vm:outbound-endpoint path="banana.service.queue">
<payload-type-filter expectedType="org.mule.tck.testmodels.fruit.Banana"/>
</vm:outbound-endpoint>
<vm:outbound-endpoint path="orange.service.queue">
<payload-type-filter expectedType="org.mule.tck.testmodels.fruit.Orange"/>
</vm:outbound-endpoint>
</expression-splitter-router>
</outbound>
</service>

Notice that each of our outbound endpoints has a filter defined. This allows the splitter router to validate
that the right object is routed to the right service. In this example, the AppleService and OrangeService
will receive one request (fruit object) each and the BananaService will receive two. If the filters were
not defined, the splitter router would send each object to the next endpoint in the list in a round robin
fashion.

Adding Expression Support to Custom Modules


The ExpressionEvaluatorManager is responsible for maintaining a list of supported Expression
Evaluators and resolving expressions at runtime. If you are adding support for expressions in your
custom Mule extensions, you will need access to this object. This is currently a static class so all methods
can be called statically, for example:

Object result = ExpressionEvaluatorManager.evaluate("#[xpath://foo/bar]", muleMessage);

For more information, see the Javadocs for ExpressionEvaluatorManager .

Note that in Mule 2.2, the ExpressionEvaluatorManager will be available from the MuleContext using
muleContext.getExptessionManager(). For more information follow issue MULE-3801@JIRA.

Creating Custom Expression Evaluators


It's very easy to add support for custom expressions inside Mule. This section describes how to create,
register, and use custom expression evaluators.

Creating the Custom Evaluator

First, you need to implement your custom expression evaluator by implementing ExpressionEvaluator .
This is a simple strategy interface:

public interface ExpressionEvaluator extends NamedObject


{
Object evaluate(String expression, Object message);
}

Note that this interface implements NamedObject, which allows the evaluator to be named. This name
maps to the evaluator part of an expression.

The arguments on the evaluate method are self-explanatory. The expression argument is the
expression to evaluate on the current message being passed in. The message is of type Object rather
than MuleMessage. This means your expression evaluator will explicitly check the message type.

The API may change in Mule 2.2 to accept a MessageAdapter instead, making things a little
easier. See MULE-3842@JIRA.

Lets take the header expression evaluator as a concrete example. This evaluator will only produce a
result if a MuleMessage object is passed in. It will assume that the expression will contain a name of a
header to return.

public class MessageHeaderExpressionEvaluator implements ExpressionEvaluator


{
public static final String NAME = "header";

Document generated by Confluence on Oct 27, 2008 21:07 Page 9


public Object evaluate(String expression, Object message)
{
Object result = null;
if (message instanceof MessageAdapter)
{
result = ((MessageAdapter) message).getProperty(expression);
}
return result;
}

public String getName()


{
return NAME;
}

public void setName(String name)


{
throw new UnsupportedOperationException("setName");
}
}

Here, we cast the message received to a MessageAdapter and look up the message header. Note
that the name of the expression evaluator is fixed as "header" so the setName method throws an
UnsupportedOperationException.

Registering the Custom Evaluator

Now that you have created your custom expression evaluator, you need to register it with Mule. There are
two ways of doing this, depending on how you are configuring your Mule instance.

If you are using XML configuration, you can just configure your expression evaluator as a bean, and Mule
will discover it.

<spring:beans>
<spring:bean class="org.mule.expressions.MessageHeaderExpressionEvaluator"/>
</spring:beans>

If you want your expression evaluator to be loaded automatically by Mule when your module (JAR) is on
the class path, you need to add a registry-bootstrap.properties file to your JAR under the following
directory:

/META-INF/services/org/mule/config

The contents of the registry-bootstrap.properties should look something like this:

object.1=org.mule.util.expression.MessageHeaderExpressionEvaluator

When Mule starts, it will discover this bootstrap file before loading any configuration and will install any
objects listed in the file into the local registry.

Using the Custom Evaluator

Finally, to use the custom evaluator, you use the customEvaluator attribute as follows:

<expression-transformer>
<return-argument evaluator="custom" customEvaluator="myEval" expression="foo"/>
</expression-transformer>

When embedding the expression, you can use normal syntax:

#[myEval:foo]

Document generated by Confluence on Oct 27, 2008 21:07 Page 10


Expressions Configuration Reference

This page last changed on Oct 24, 2008 by jackie.wheeler.

Expressions Configuration Reference


[ Expression Attributes ] [ Syntax ] [ Spring Property Placeholders and Expressions ] [ Expression
Evaluator Reference ]

This page is ready for review

This page provides reference information for configuring expressions.

Expression Attributes
The XML configuration elements in Mule that support expressions have three common attributes that
define the expression to execute, the evaluator to use, and the option of defining a custom evaluator.

Attribute Description

expression The expression to evaluate. The syntax of this


attribute will change depending on the evaluator
being used.

evaluator The expression evaluator to use. Expression


evaluators must be registered with the
ExpressionEvaluatorManager before they can be
used. Using the custom evaluator allows you to
define your custom evaluator via the custom-
evaluator attribute. Note that some evaluators
such as Xpath, Groovy, and Bean are loaded
from other Mule modules (XML and Scripting,
respectively). These modules must be on your
classpath before their evaluators can be used.

custom-evaluator The name of a custom evaluator to use. This


evaluator must be registered in the local registry
before it can be used.

Expressions can be used in a number of other scenarios such as filters, routing, and endpoints.

Syntax
There are two ways of specifying expressions depending on where the expression is being used. Typically,
expression-based elements such as the expression transformer, expression filter, and expression-based
routers such as the expression message splitter, will have specific attributes for expression, evaluator,
and custom-evaluator. For example:

<expression-filter evaluator="header" expression="my-header!=null"/>

For these elements, only a single expression can be set for the element.

When defining expressions for things like property values, multiple expressions can be defined using the
following syntax:

#[<evaluator>:<expression>]

Document generated by Confluence on Oct 27, 2008 21:07 Page 11


The syntax here requires that an expression is preceded with #[, then the evaluator is defined, followed
by a colon (:) and the expression to execute. Finally, the expression is terminated with a ]. Multiple
expressions can be defined as a string. For example:

<message-properties-transformer>
<add-property name="GUID" value="#[xpath:/msg/header/ID]-#[xpath:/msg/body/@ref]"/>
</message-properties-transformer>

Syntax Change between Mule 2.0 and Mule 2.1

In Mule 2.0 the syntax for expressions used a dollar sign and curly braces i.e. ${xpath://
foo/bar}. This has been replaced in Mule 2.1 with the syntax described above, #[xpath://
foo/bar]. This change was made so that Mule expressions would not conflict with Spring
Property placeholders that use the ${...} syntax.

Spring Property Placeholders and Expressions


Spring and Mule have had long-time support for property placeholders that allow developers to inject
static properties into their configuration when their application starts up. The property values are defined
in Java property files that are passed into the framework on start up. The following example shows a
properties file that defines configuration information used by a Mule endpoint:

MyApplication.properties

web.proxy.host=192.168.2.2
web.proxy.port=8081

The Mule configuration file can embed these properties as placeholders.

<mule ...>
<http:connector name="HttpConnector" proxyHostname="${web.proxy.host}"
proxyPort="${web.proxy.port}"/>
</mule>

These property placeholders are resolved during the start-up phase of your application. Mule expressions
are evaluated continuously for every message received or sent.

Expression Evaluator Reference


Following are the default expression evaluators that are loaded at runtime. Not all expression evaluators
are supported by every type of expression-based object. For example, the attachment evaluator is
available to routers but not filters.

Name Example Comments

attachment #[attachment:supporting-docs] Not supported by expression


filters.

attachments #[attachments:attach1,attach2] Returns a java.util.Map of


attachments. Not supported by
expression filters.

attachments-list #[attachments- Returns a java.util.List


list:attach1,attach2] of attachments objects. Not
supported by expression filters.

bean #[bean:fruit.isWashed] The bean property expression.


Use "." or "/" as element
delimiter.

endpoint #[endpoint:myEP.address] Use endpointName.property,


e.g.,

Document generated by Confluence on Oct 27, 2008 21:07 Page 12


endpoint:endpointName.address.
endpoint:endpointName.foobar.
Not supported by expression
filters.

exception-type #[exception- Matches an exception type. Only


type:java.lang.RuntimeException] supported by expression filters.

function #[function:dateStamp(dd-MM- Performs a function: now, date,


yyyy)] datestamp, systime, uuid,
hostname, ip, or count. Not
supported by expression filters.

groovy #[groovy:payload.fruit.washed]

header #[header:Content-Type] Evaluates the specified part of


the message header.

headers #[headers:Content- Returns a jaa.util.Map of


Type,Content-Length] headers. Not supported by
expression filters.

headers-list #[headers-list:Content- Returns a java.util.List of


Type,Content-Length] header values. Not supported by
expression filters.

jxpath #[jxpath:/fruit] JXPath expression that works on


both XML/DOM and Beans.

map-payload #[map-payload:key] Returns a value from within a


java.util.Map payload. Not
supported by expression filters.

message #[message.correlationId] Available expressions


are id, correlationId,
correlationSequence,
correlationGroupSize, replyTo,
payload, encoding, exception.
Not supported by expression
filters.

mule #[mule:serverId] Available expressions are


serviceName, modelName,
inboundEndpoint, serverId,
clusterId, domainId, workingDir,
homeDir. Not supported by
expression filters.

ognl #[ognl:[MULE:0].equals(42)] or Set the evaluator attribute


on the <expression-filter>
element to ognl when specifying
an OGNL filter.

payload #[payload:com.foo.RequiredType] If expression is provided, it will


be a class to be class loaded.
The class will be the desired
return type of the payload.
See getPayload(Class) in
MuleMessage . Not supported by
expression filters.

payload-type #[payload:java.lang.String] Matches the type of the payload.


Only supported by expression
filters.

Document generated by Confluence on Oct 27, 2008 21:07 Page 13


regex #[regex:the quick brown (.*)] Only supported by expression
filters.

wildcard #[wildcard:*.txt] Only supported by expression


filters.

xpath #[xpath://fruit] The expression is an XPath


expression.

Currently there is no way to configure namespaces for XML expressions. In Mule 2.2 it will
be possible to define global namespaces that will be accessible to all XML expressions. For
more information please follow (and vote) on this issue MULE-3303@JIRA.

Document generated by Confluence on Oct 27, 2008 21:07 Page 14


Home

This page last changed on Oct 20, 2008 by jackie.wheeler.

Some of the 2.0 documentation is still under construction. If you have content you can add, please
contact us to become a site editor.

Getting Started Using Transports


(Click the arrow to expand the topics from the • About Transports
Getting Started guide, including an introduction • Available Transports
to Mule, steps to get started, and migration • Configuring a Transport
information.) • Customizing a Transport

Click here Mule Deployment


to expand...
Architecture
• Introduction
° What is Mule?
• Mule Instances
° Understanding the Messaging
• Deployment Scenarios
Framework • Choosing the Right Topology
° Understanding the Mule Architecture
° Understanding the Logical Data Flow
° Integrating Mule into Your Environment Mule Administration
° Summary

• Getting Started • Installing a Standalone Mule Instance


° Quick Start
• Installing Upgrades and Hot Fixes
° Download Page
• Managing and Monitoring Deployments
° Installing Mule
° Using Mule HQ
° Running Mule
° Setting Up Eclipse
° Examples
JMX Management
°
° Basic Usage
• Controlling the Infrastructure with Mule
° What's New in This Release
Galaxy
° Migrating Mule

Extending Mule
Using Mule
• Introduction to Extending Mule
• Creating Transports
• Creating Additional Extensions
• Configuring Mule
° Configuration Overview
• Creating a Custom XML Namespace
° XML Configuration
• Internationalizing Strings
° Configuring a Mule Instance
• Using MuleForge
° Configuring Endpoints
° Using Transformers Testing Mule
° About Models

• Working with Services


° Configuring the Service
• Introduction to Testing Mule
° Configuring Components
• Functional Testing
° Using Message Routers
• Unit Testing
° Using Filters
• Running Benchmark Tests
° Mule Messaging Styles
• Profiling Mule
° Using Web Services
° Using Spring Beans as Service Development Tools
Components
• Customizing Behavior
° Developing Service Components
• Developer's Guide
° Creating Custom Transformers
• Using IDEs
° Creating Custom Routers
• Using Maven
• JavaRebel Integration

Document generated by Confluence on Oct 27, 2008 21:07 Page 15


°Creating Custom Filters
°Using Interceptors
Reference
• Beyond the Basics
° Using Expressions • Glossary
° Using Mule with Spring • Configuration Reference
° Using JMS with Mule • API Reference
° Using the Mule RESTpack • Test API Reference
° Using Mule Modules • Third-party Software in Mule
° Error Handling • Suggested Reading
° Configuring Security • Distribution Contents
° Using the Mule Client
° Tuning Performance
° Managing Transactions
Documentation for Previous
° Using Agents Releases
° Mule Server Notifications

Click a link below to view the documentation for


that release.

Mule 1.x

• Getting Started
• User Guide

Document generated by Confluence on Oct 27, 2008 21:07 Page 16


About Transports

This page last changed on Jul 01, 2008 by jackie.wheeler.

About Transports
A transport is responsible for carrying messages from application to application in the Mule framework.
A transport provides a set of functionality that handles messages on a specific channel. For example, the
HTTP transport handles messages sent via the HTTP protocol, whereas the File transport picks up files
placed on the server's file system.

The heart of a transport is the connector. The connector maintains the configuration and state for
the transport. When receiving messages, a connector uses a message receiver, which reads the
data, packages it as a message, and passes it to the service component's inbound router. When
sending messages, the connector uses a message dispatcher, which receives the messages and routing
instructions from the service component's outbound router and sends the message to the next service
component or application.

Related Topics
Available Transports
Configuring a Transport
Customizing a Transport
Creating Transports

Document generated by Confluence on Oct 27, 2008 21:07 Page 17


Available Transports

This page last changed on Oct 17, 2008 by jackie.wheeler.

Available Transports
[ Mule Transports ] [ Transports Feature Matrix ]

Following is a list of known transports (also called "providers") for Mule. Some functionality is contained
within modules instead of transports--see Using Mule Modules. For more information on transports, see
the following topics:

• About Transports
• Configuring a Transport
• Creating Transports

If you have created a transport for Mule and would like to share it with the Mule community, please
contact us.

Mule Transports

Transport Description

AS400 DQ Transport Connectivity to IBM AS400 Data Queue messaging


server. This transport is available on MuleForge.

Axis Transport Allows Mule managed components to be published


as Axis services and allows components to invoke
web services using Axis client calls.

BPM Transport Allows Mule events to initiate and/or advance


processes in a Business Process Management
System (BPMS) a.k.a. Process Engine.

CXF Transport Provides support for web service integration via


Apache CXF.

EJB Transport Allows EJB invocations to be made using outbound


endpoints.

Email Transport This transport supplies various email connectivity


options.

File Transport This transport allows files to be read and written


to directories on the local file system. The
connector can be configured to filter the file
it reads and the way files are written, such
as whether binary output is used or the file is
appended to.

FTP Transport Allows files to be read / written to a remote FTP


server.

HTTP Transport This transport supplies HTTP transport of Mule


messages between applications and other Mule
servers.

HTTPS Transport A secure version of the HTTP transport.

IMAP Transport Connectivity to IMAP mail folders.

Document generated by Confluence on Oct 27, 2008 21:07 Page 18


IMAPS Transport A secure version of the IMAP transport.

JCR Transport A transport that reads from, writes to, and


observes JCR 1.0 containers. This transport is
available on MuleForge.

JDBC Transport A transport for JDBC connectivity. Some of its


features are available only in Mule Enterprise
Edition.

Jetty Transport Provides support for exposing services over HTTP


by embedding a light-weight Jetty server. For
inbound endpoints only.

Jetty SSL Transport A secure version of the Jetty transport.

JMS Transport A Mule transport for JMS connectivity. Mule itself


is not a JMS server but can use the services of
any JMS 1.1 or 1.02b compliant server such
as ActiveMq, OpenJms, Joram, JBossMQ, and
commercial vendors such as WeblogicMQ,
WebsphereMQ, SonicMQ, SeeBeyond, etc.

Multicast Transport Allows your components to receive and send


events via IP multicast groups.

POP3 Transport Connectivity to POP3 inboxes.

POP3S Transport A secure version of the POP3 transport.

Quartz Transport Provides scheduling facilities with cron /


interval definitions and allows Mule events to be
scheduled/rescheduled.

RMI Transport Enables events to be sent and received over RMI


via JRMP.

Servlet Transport Provides facilities for Mule components to listen


for events received via a servlet request. There
is also a servlet implementation that uses the
Servlet transport to enable REST style services
access. This transport is now bundled with the
HTTP transport.

SMTP Transport Connectivity to SMTP servers.

SMTPS Transport A secure version of the SMTP transport.

SOAP Transport Enables your components to be exposed as web


services and to act as SOAP clients. The SOAP
transport supports CXF and Apache Axis.

SSL Transport Provides secure socket-based communication


using SSL or TLS.

STDIO Transport This transport provides connectivity to streams


such as System.in and System.out and is useful
for testing.

TCP Transport Enables events to be sent and received over TCP


sockets.

Document generated by Confluence on Oct 27, 2008 21:07 Page 19


UDP Transport Enables events to be sent and received as
datagram packets.

VM Transport Enables event sending and receiving over VM,


embedded memory, or persistent queues.

A Mule transport for WebSphere MQ. This


WebSphere transport is available with Mule Enterprise version
MQ Transport 1.6 and later.

WSDL Transport Invokes remote web services by obtaining the


service WSDL. Mule will create a dynamic proxy
for the service and then invoke it.

XMPP Transport Provides connectivity over the XMPP (Jabber)


instant messaging protocol.

Transports Feature Matrix


The following table shows the different messaging styles and options that each of the Mule transports
support. The headings are described below the table.

Transport Receive Dispatch Request Request/ Transactions


Streaming Inbound Outbound
Events Events Events Response MEPs MEPs
Events

Axis In- Out-Only


Only In- Out-
Out In- In Out-
Optional- Optional-
Out In

BPM In- Out-Only


Only In-
Out In-
Optional-
Out

CXF In- Out-Only


Only In- Out-
Out In- In Out-
Optional- Optional-
Out In

EJB In-Only Out-Only


Out-
In Out-
Optional-
In

Email In-Only Out-Only

File In-Only Out-Only

FTP In-Only Out-Only

HTTP In- Out-


Out In- In Out-

Document generated by Confluence on Oct 27, 2008 21:07 Page 20


Optional- Optional-
Out In

HTTPS In- Out-


Out In- In Out-
Optional- Optional-
Out In

IMAP In-Only

IMAPS In-Only

JDBC In- Out-Only


Only In- Out-
Out In- In Out-
Optional- Optional-
Out In

Jetty In-
Only In-
Out In-
Optional-
Out

Jetty SSL In-


Only In-
Out In-
Optional-
Out

JMS In- Out-Only


Only In- Out-
Out In- In Out-
Optional- Optional-
Out In

Multicast In- Out-


Out In- In Out-
Optional- Optional-
Out In

POP3 In-Only

POP3S In-Only

Quartz In-Only Out-Only

RMI In-Only Out-Only


Out-In

Servlet In-
Only In-
Out In-
Optional-
Out

SMTP Out-Only

SMTPS Out-Only

Document generated by Confluence on Oct 27, 2008 21:07 Page 21


SOAP In- Out-Only
Only In- Out-
Out In- In Out-
Optional- Optional-
Out In

STDIO In-Only Out-Only

TCP In- Out-


Out In- In Out-
Optional- Optional-
Out In

UDP In- Out-


Out In- In Out-
Optional- Optional-
Out In

VM In- Out-Only
Only In- Out-
Out In- In Out-
Optional- Optional-
Out In

XMPP In- Out-Only


Only In- Out-
Out In- In Out-
Optional- Optional-
Out In

Heading Descriptions

Transport - The name/protocol of the transport


Receive Events - Whether the transport can receive events and can be used for an inbound endpoint
Dispatch - Whether events can be sent asynchronously
Request - Whether this endpoint can be queried directly with a request
Request/Response - Whether this endpoint can be queried directly with a request and return a
response (implementation of the request() method in MessageRequester)
Transactions - Whether transactions are supported by the transport. Transports that support
transactions can be configured in a distributed two-phase commit (distributed) transaction.
Streaming - Whether this transport can stream data between endpoints. This allows for very efficient
processing of large data.
Inbound and Outbound MEPs - The messaging exchange patterns (MEPs) supported by the inbound
and outbound endpoints of the transport. See Mule Messaging Styles for more information on the
messaging styles Mule supports and how they map to MEPs.

Document generated by Confluence on Oct 27, 2008 21:07 Page 22


BPM Transport

This page last changed on Oct 07, 2008 by jackie.wheeler.

BPM Transport
[ Features ] [ Usage ] [ Integration with BPM Engines ] [ Configuration ] [ Connector ]

The BPM transport allows Mule events to initiate and/or advance processes in a Business Process
Management System (BPMS), also known as a process engine. It also allows executing processes to
generate Mule events. For a high-level introduction to Business Process Management with Mule and the
concepts involved, see the presentation from MuleCon 2007.

To see the BPM Connector in action (with JBoss jBPM), take a look at the LoanBroker BPM example
(available in the full Mule distribution).

Javadocs for the BPM transport are available here .

Features
• Incoming Mule events can launch new processes, advance or terminate running processes.
• A running process can generate synchronous or asynchronous Mule events.
• Endpoints of type "bpm://MyProcess" are used to intelligently route process-generated events within
Mule.
• Synchronous responses from Mule are automatically fed back into the running process.
• Mule can interact with different running processes in parallel.

BPEL

The connector can only integrate with BPM engines that provide a Java API. If you need to
integrate with a BPEL engine that only exposes SOAP endpoints (i.e., "a black box"), you
will need to use standard web services. For an example, see MULE and Oracle SOA BPEL
Integration.

Usage

Sending events to the BPMS

The basic URI for a new process is:

bpm://ProcessType

For a running process, use:

bpm://ProcessType/ProcessID

Initiate a new process of type "MyBigProcess"

bpm://MyBigProcess

Advance an already running process with ID = 4561

bpm://MyBigProcess?processId=4561&action=advance

(advance is the default action for an already-running process) or just

bpm://MyBigProcess/4561

Update process variables (without advancing the process)

bpm://MyBigProcess/4561?action=update

Document generated by Confluence on Oct 27, 2008 21:07 Page 23


Abort a running process (this might not be supported by every BPMS)

bpm://MyBigProcess/4561?action=abort

In a real system, you will most likely want to set the "processId" dynamically as a property
on the message.

Incoming Messages to the BPMS

When a message is received by the BPMS, two things automatically happen:

• The message payload is stored in a process variable named "incoming"


• The endpoint on which the message was originally received by Mule is stored in a process variable
named "incomingSource"

These process variables may then be used to drive the logic of the running process.

Generating Events from the BPMS

The actual syntax for generating events from a running process will depend on the BPMS used.

Messages generated by a running process will be received by Mule on the best-matching endpoint
available. For example, suppose a Mule message is generated by the running process called
"MyBigProcess" with ID = 4561. The incoming message would preferably be received by this endpoint:

bpm://MyBigProcess/4561

and if not, then by this endpoint:

bpm://MyBigProcess

and finally, if the "allowGlobalReceiver" property is true, by this endpoint:

bpm://*

The new message will then be routed from the component on which it is received (unless the
connector's allowGlobalDispatcher property is true). If the message is synchronous, the response will
automatically be sent back to the generating process.

Integration with BPM Engines


One of the basic design principles of Mule is to promote maximum flexibility for the user. Based on this,
the user should ideally be able to "plug in" any BPM engine to use with Mule. Unfortunately, there is no
standard JEE specification to enable this. JSR-207 was one attempt but has made no progress. BPEL has
also tried to solve this, but like JBI, is exclusive to SOAP web services and XML, which defeats Mule's
flexibility principle.

Therefore, until such a specification ever emerges, the Mule BPM Transport simply defines its own.

public interface BPMS


{
// Start a new process.
public Object startProcess(Object processType, Map processVariables);

// Advance an already-running process.


public Object advanceProcess(Object processId, Object transition, Map processVariables);

// Update the variables/parameters for an already-running process.


public Object updateProcess(Object processId, Map processVariables);

// Abort a running process (end abnormally).


public void abortProcess(Object processId);

// MessageService is a callback method used to generate Mule messages from your process.
public void setMessageService(MessageService msgService);

Document generated by Confluence on Oct 27, 2008 21:07 Page 24


}

Any BPM engine that implements the interface ( org.mule.transport.bpm.BPMS ) can "plug in" to Mule via
the BPM transport. The JBoss jBPM engine is available with Mule.

Integration with JBoss jBPM

For general information on jBPM and how to configure it, refer to http://docs.jboss.com/jbpm/v3/
userguide

The org.mule.transport.bpm.jbpm.Jbpm
class implements the BPMS interface for jBPM and must be set as the bpms property on your connector.
You can browse the rest of the Javadocs for Mule's jBPM integration here .

Configuration

The recommended way to configure jBPM with Mule is using Spring and Spring's jBPM Module

<?xml version="1.0" encoding="UTF-8"?>


<mule xmlns="http://www.mulesource.org/schema/mule/core/2.1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:bpm="http://www.mulesource.org/schema/mule/bpm/2.1"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-
context-2.5.xsd
http://www.mulesource.org/schema/mule/core/2.1 http://www.mulesource.org/schema/mule/core/2.1/
mule.xsd
http://www.mulesource.org/schema/mule/bpm/2.1 http://www.mulesource.org/schema/mule/bpm/2.1/mule-
bpm.xsd">

<bpm:connector name="jBpmConnector" bpms-ref="jbpm" />

<!-- BPMS object for Mule's BPM Connector -->


<spring:bean id="jbpm" class="org.mule.transport.bpm.jbpm.Jbpm" destroy-method="destroy">
<spring:property name="jbpmConfiguration">
<spring:ref local="jbpmConfig" />
</spring:property>
</spring:bean>

<!-- jBPM Configuration -->


<spring:bean id="jbpmConfig"
class="org.springmodules.workflow.jbpm31.LocalJbpmConfigurationFactoryBean">
<spring:property name="sessionFactory">
<spring:ref local="jbpmSessionFactory" />
</spring:property>
<spring:property name="configuration">
<spring:value>jbpm.cfg.xml</spring:value>
</spring:property>
<spring:property name="processDefinitions">
<spring:list>
<spring:bean id="loanBroker"
class="org.springmodules.workflow.jbpm31.definition.ProcessDefinitionFactoryBean">
<spring:property name="definitionLocation">
<spring:value>loan-broker-process.xml</spring:value>
</spring:property>
</spring:bean>
</spring:list>
</spring:property>
<spring:property name="createSchema">
<spring:value>false</spring:value>
</spring:property>

Document generated by Confluence on Oct 27, 2008 21:07 Page 25


</spring:bean>

<!-- JBPM Hibernate SessionFactory -->


<spring:bean id="jbpmSessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<spring:property name="dataSource">
<spring:ref local="jbpmDataSource" />
</spring:property>
<spring:property name="mappingLocations">
<spring:value>classpath*:/org/jbpm/**/*.hbm.xml</spring:value>
</spring:property>
<spring:property name="typeDefinitions">
<spring:ref local="jbpmTypes" />
</spring:property>
<spring:property name="hibernateProperties">
<spring:props>
<spring:prop key="hibernate.dialect">org.hibernate.dialect.DerbyDialect</spring:prop>
<spring:prop key="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</
spring:prop>
<!-- Create/update the database tables automatically when the JVM starts up -->
<spring:prop key="hibernate.hbm2ddl.auto">update</spring:prop>
</spring:props>
</spring:property>
</spring:bean>

<!-- JBPM Datasource -->


<spring:bean id="jbpmDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<spring:property name="driverClassName">
<spring:value>org.apache.derby.jdbc.EmbeddedDriver</spring:value>
</spring:property>
<spring:property name="url">
<spring:value>jdbc:derby:muleEmbeddedDB;sql.enforce_strict_size=true</spring:value>
</spring:property>
</spring:bean>

<!-- JBPM data types -->


<spring:bean id="jbpmTypes" class="org.springframework.orm.hibernate3.TypeDefinitionBean">
<spring:property name="typeName">
<spring:value>string_max</spring:value>
</spring:property>
<spring:property name="typeClass">
<spring:value>org.jbpm.db.hibernate.StringMax</spring:value>
</spring:property>
</spring:bean>

</mule>

If you want to configure jBPM without using Spring, you create the org.mule.transport.bpm.jbpm.Jbpm
wrapper based on your jBPM instance and set it as the bpms property on the BPM connector:

ProcessConnector connector = new ProcessConnector();

BPMS bpms = new org.mule.transport.bpm.jbpm.Jbpm(yourJbpmInstance);


connector.setBpms(bpms);

MuleManager.getInstance().registerConnector(connector);

Generating a Mule Message from jBPM

Use the org.mule.transport.bpm.jbpm.actions.SendMuleEvent ActionHandler to generate a Mule message


from your jBPM process:

<process-definition name="sendMessageProcess">

Document generated by Confluence on Oct 27, 2008 21:07 Page 26


<description>Generates a simple Mule event.</description>

<start-state name="start">
<transition to="sendMessage" />
</start-state>

<state name="sendMessage">
<event type="node-enter">
<action class="org.mule.transport.bpm.jbpm.actions.SendMuleEvent">
<endpoint>file:///tmp</endpoint>
<payload>Message in a bottle.</payload>
<synchronous>false</synchronous>
</action>
</event>
<transition to="end" />
</state>

<end-state name="end" />

</process-definition>

jBPM Action Handlers for Mule

The primary way of adding custom functionality to jBPM is via ActionHandlers. The BPM transport
provides a few such ActionHandlers, which are useful for integrating your jBPM process with Mule.

SendMuleEvent : Sends a Mule message to the specified endpoint. If the message is synchronous, the
response from Mule will be automatically stored in the "incoming" process variable.

StoreIncomingData : Stores the incoming message payload into the specified variable.

ValidateMessageSource : Throws an exception if the message's source is not as expected.

ValidateMessageType : Throws an exception if the incoming message's class is not as expected.

Configuration
Following is a simple configuration example:

<?xml version="1.0" encoding="UTF-8"?>


<mule xmlns="http://www.mulesource.org/schema/mule/core/2.1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:bpm="http://www.mulesource.org/schema/mule/bpm/2.1"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-
context-2.5.xsd
http://www.mulesource.org/schema/mule/core/2.1 http://www.mulesource.org/schema/mule/core/2.1/
mule.xsd
http://www.mulesource.org/schema/mule/bpm/2.1 http://www.mulesource.org/schema/mule/bpm/2.1/mule-
bpm.xsd">

<bpm:connector name="jBpmConnector" bpms-ref="jbpm" />

<model name="bpm_example">
<!-- Messages sent to the process engine -->
<service name="ToBPMS">
<inbound>
<inbound-endpoint address="Incoming1"/>
<inbound-endpoint address="Incoming2"/>
</inbound>
<log-component/>

Document generated by Confluence on Oct 27, 2008 21:07 Page 27


<outbound>
<filtering-router>
<outbound-endpoint address="bpm://MyProcess" synchronous="false" />
</filtering-router>
</outbound>
</service>

<!-- Messages generated from the process engine -->


<service name="FromBPMS">
<inbound>
<inbound-endpoint address="bpm://MyProcess" />
</inbound>
<log-component/>
<outbound>
<bpm:outbound-router>
<outbound-endpoint address="Outgoing1"/>
<outbound-endpoint address="Outgoing2"/>
<outbound-endpoint address="Outgoing3"/>
</bpm:outbound-router>
</outbound>
</service>
</model>
</mule>

Message Properties

Property Description Default Required

processType The name of the yes


process

processId The unique ID of the yes, unless action =


running process "start"

action Action to perform on "advance" if processId no


the BPMS: "start" / exists, otherwise "start"
"advance" / "update" /
"abort"

transition Transition to take if no


more than one exit
path is available for the
current process state

Connector

Attributes of <connector...>

Name Type Required Default Description

bpms-ref name (no spaces) no A reference to


the underlying
BPMS, which must
implement the
org.mule.transport.bpm.BPMS
interface to
exchange
messages through

Document generated by Confluence on Oct 27, 2008 21:07 Page 28


Mule using the
BPM transport.

allowGlobalReceiver boolean no false The global


receiver allows
an endpoint of
type "bpm://*"
to receive any
incoming message
to the BPMS,
regardless of the
process. If this is
false, the process
name must be
specified for each
endpoint. For
example, "bpm://
MyProcess" will
only receive
messages for
the process
"MyProcess".

allowGlobalDispatcherboolean no false If false, any


message
generated by
the process is
routed from
the component
on which it is
received. If true, a
process can send
messages to any
endpoint on any
component.

processIdField string no This field will be


used to correlate
messages with
processes.

Document generated by Confluence on Oct 27, 2008 21:07 Page 29


CXF Transport

This page last changed on Sep 04, 2008 by jackie.wheeler.

CXF Transport
[ Introduction ] [ Features ] [ Using the CXF Transport ] [ Troubleshooting ] [ Suggested Reading ]

Introduction
The Mule CXF Transport provides support for web service integration via Apache CXF. Apache CXF is an
open source services framework that helps you build and develop services using front-end programming
APIs, like JAX-WS. These services can speak a variety of protocols such as SOAP, XML/HTTP, RESTful
HTTP, or CORBA and work over a variety of transports such as HTTP, JMS or JBI.

Note: The CXF transport requires Java 5.0.

Features
The CXF transport is an evolution of the XFire transport, which was available with earlier versions of Mule.
The CXF transport includes the following features:

• Integrated Installer: CXF and XFire have some conflicting libraries and therefore cannot both be
deployed in the same instance of Mule. The Mule Enterprise installer allows you to install CXF when
you're installing Mule and handles all library changes for you. This is an enhancement over the
snapshot version of the CXF transport on MuleForge.
• Bookstore Example: A complete example of using the CXF transport to send complex objects.
• MTOM Support: The CXF transport supports SOAP Message Transmission Optimization Mechanism
(MTOM), which specifies an optimized method for sending binary data as part of a SOAP message.
• Complete Functional Tests: The functional tests have been converted from XFire to CXF.

Using the CXF Transport


Use the following links for information on configuring and using the CXF transport with your
implementation of Mule.

Building a CXF Web Service


Using a Web Service Client as an Outbound Endpoint
Using a Web Service Client Directly
Using HTTP GET Requests
Using MTOM
Proxying Web Services
Enabling WS-Addressing
Enabling WS-Security
Bookstore Example
Configuration Reference

Troubleshooting
This section includes common problems and solutions you might encounter when using the CXF transport.

I've received a "java.lang.IllegalArgumentException: wrong number of arguments" when


using the CXF outbound endpoint

The CXF outbound endpoint uses the CXF generated to client to send messages. Because of this, your
message payload must match the signature of the operation being invoked. This error results when the
payload does not match the signature.

Here's an example. If you have an operation on the client like this:

Document generated by Confluence on Oct 27, 2008 21:07 Page 30


public void sendData(String data1, String data2, String data3);

Your message payload must be like this:

Object payload = new Object[] { "data1", "data2", "data3" };

My WSDL does not have the correct service address (i.e. its localhost instead of foo.com)

If you are doing WSDL-first development, ensure that your @WebService annotation on your service
implementation has the correct serviceName, targetNamespace, and portName attributes. If these are
not correct, CXF cannot navigate your WSDL, find the address, and replace it with the address currently
being used.

Your WebService annotation should look like this:

@WebService(serviceName = "YourServiceName",
portName = "YourPortName",
targetNamespace = "http://your-namespace",
endpointInterface = "your.endpoint.Interface",
wsdlLocation = "your.wsdl")

Suggested Reading

XFire->CXF Migration Guide


XFire and Celtix Merge FAQ

Document generated by Confluence on Oct 27, 2008 21:07 Page 31


Building a CXF Web Service

This page last changed on Oct 15, 2008 by dan.diephouse@mulesource.com.

Building a CXF Web Service


[ Creating a JAX-WS Service ] [ Configuring Mule to Use the Web Service ] [ Using WSDL-first
Methodologies ] [ Changing the Data Binding ] [ Setting the Binding URI ] [ Changing the Default
Message Style ]

This page describes how to build a CXF web service and use it in Mule.

Creating a JAX-WS Service


The JAX-WS specification is a series of APIs and annotations to help you build web services. This section
describes how to create a very simple JAX-WS web service.

First, you write the service interface. For example, you could write an operation called "sayHello" that
says "Hello" to whoever submits their name.

package org.example;

import javax.jws.WebService;

@WebService
public interface HelloWorld {
String sayHi(String text);
}

Your implementation would then look like this:

package demo.hw.server;

import javax.jws.WebService;

@WebService(endpointInterface = "demo.hw.server.HelloWorld",
serviceName = "HelloWorld")
public class HelloWorldImpl implements HelloWorld {

public String sayHi(String text) {


return "Hello " + text;
}
}

Configuring Mule to Use the Web Service


To configure Mule to use the service, simply declare your service and use a CXF endpoint as shown in the
following example:

<mule xmlns="http://www.mulesource.org/schema/mule/core/2.1" xmlns:xsi="http://www.w3.org/2001/


XMLSchema-instance"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:cxf="http://www.mulesource.org/schema/mule/cxf/2.1"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.mulesource.org/schema/mule/core/2.1
http://www.mulesource.org/schema/mule/core/2.1/mule.xsd
http://www.mulesource.org/schema/mule/cxf/2.1
http://www.mulesource.org/schema/mule/cxf/2.1/mule-cxf.xsd">
<model name="CxfExample">
<service name="helloService">
<inbound>

Document generated by Confluence on Oct 27, 2008 21:07 Page 32


<inbound-endpoint address="cxf:http://localhost:63081/hello" />
</inbound>
<component>
<singleton-object class="org.example.HelloServiceImpl" />
</component>
</service>
...

If you go to "http://localhost:63081/hello?wsdl", you will see the WSDL that CXF generates for you.

If you want to use a POJO instead of creating a JAX-WS service, you could host the POJO as a service
component in Mule and use the simple front-end client with its CXF inbound endpoint. You would
configure the POJO as follows:

<inbound-endpoint address="cxf:http://localhost:63081/hello" frontend="simple" />

The frontend property can be "jaxws" (the default) or "simple".

Using WSDL-first Methodologies


In addition to the code-first approach outlined above, you can also use CXF to do WSDL-first services.
While the details are out of the scope of this guide, the CXF distribution includes many examples of how
to do this.

First, you generate your web service interface from your WSDL. You can do this using the WSDL to Java
tool from CXF or the Maven plugin.

Next, you write a service implementation class that implements your service interface. You can then use
this implementation class in the Mule configuration exactly as in the previous example.

Supplying the Original WSDL to CXF

You can supply your original WSDL to CXF by using the @WebService attribute:

WebService(endpointInterface = "demo.hw.server.HelloWorld",
serviceName = "HelloWorld",
wsdlLocation="foo/bar/hello.wsdl")
public class HelloWorldImpl implements HelloWorld

Another way is to specify the wsdlLocation property on the endpoint:

<cxf:inbound-endpoint address="http://localhost:63081/hello" wsdlLocation="foo/bar/hello.wsdl" />

CXF is able to locate this WSDL inside your webapp, on the classpath, or on the file system.

Changing the Data Binding


You can use the databinding property on an endpoint to configure the data binding to use with that
service. Following are the types of data bindings available with CXF:

1. AegisDatabinding
2. JAXBDatabinding (Default)
3. StaxDatabinding

You specify the databinding class to use as follows:

<cxf:inbound-endpoint address="cxf:http://localhost:18080/mule/CxfService">
<cxf:databinding>
<spring:bean class="org.apache.cxf.aegis.databinding.AegisDatabinding"/>
</cxf:databinding>
</cxf:inbound-endpoint>

Document generated by Confluence on Oct 27, 2008 21:07 Page 33


Setting the Binding URI
The bindingUri attribute specifies how your service operations are mapped to resources. You configure
this attribute as follows:

<inbound-endpoint address="cxf:http://localhost:18080/mule/CxfService" bindingUri="http://


www.w3.org/2003/05/soap/bindings/HTTP/" />

Changing the Default Message Style


By default, CXF uses the Document/Literal message style. However, you can change the service to be
exposed as RPC instead of document or to send complex types as wrapped instead of literal. To change
the message style, you set the @SOAPBinding annotation on the service's interface, specifying the style,
use, and optionally the parameterStyle.

In the following example, the parameter style is set to BARE. This means that each parameter is placed
into the message body as a child element of the message root. This is WRAPPED by default.

@SOAPBinding(style=SOAPBinding.Style.DOCUMENT,
use=SOAPBinding.Use.LITERAL,
parameterStyle=SOAPBinding.ParameterStyle.BARE)
@WebService
public interface Echo
{
String echo(String src);
}

For more information on the supported message styles, go to Optional Annotations.

Document generated by Confluence on Oct 27, 2008 21:07 Page 34


CXF Transport Configuration Reference

This page last changed on Aug 05, 2008 by jackie.wheeler.

Table of Contents

Click here to expand...

• CXF Transport
• ° Connector
° - Attributes of <connector...>
° Inbound endpoint
° - Attributes of <inbound-endpoint...>
° Outbound endpoint
° - Attributes of <outbound-endpoint...>
° Endpoint
° - Attributes of <endpoint...>
° Features
° Wrapper component
° - Attributes of <wrapper-component...>
° Stax

CXF Transport
Apache CXF is an open source services framework. CXF helps you build and develop services using
frontend programming APIs, like JAX-WS. These services can speak a variety of protocols such as SOAP,
XML/HTTP, RESTful HTTP, or CORBA and work over a variety of transports such as HTTP, JMS or JBI.
The Mule CXF Transport is an evolution of Mule's XFire Transport which provides support for the use of
web service integration via Apache CXF. The Mule CXF connector also provides support for WS-Security,
WS-Addressing and WS-Reliable-Messaging.

Connector

Attributes of <connector...>

Name Type Required Default Description

defaultFrontend string no jaxws The CXF frontend


that is used
to build an
internal service
representation
from your Java
classes. The
default is "jaxws".
The "simple"
frontend is also
supported.

configurationLocationstring no The location of a


CXF configuration
file, if any needs
to be supplied.

initializeStaticBusInstance
boolean no Initialize the static
CXF Bus with a
Bus configured to
use Mule for all
transports. This

Document generated by Confluence on Oct 27, 2008 21:07 Page 35


will affect any
CXF generated
clients that you
run standalone.
Defaults to false.

Inbound Endpoint

Attributes of <inbound-endpoint...>

Name Type Required Default Description

frontend jaxws/simple no The CXF frontend


that is used
to build an
internal service
representation
from your Java
classes. The
default is "jaxws".
The "simple"
frontend is also
supported.

bindingUri string no The binding that


should be used
for this service.
It defaults to the
soap binding by
default.

endpointName string no The WSDL


endpoint name of
your service.

serviceClass string no The class CXF


should use to
construct it's
service model.
This is optional
and by default
it will use the
implementation
class of your
component.

serviceName string no The WSDL service


name of your
service.

applyFiltersToProtocolboolean no Whether or not to


apply the filters
to the protocol
endpoint.

applyTransformersToProtocol
boolean no Whether or not
to apply the
transformers
to the protocol
endpoint.

Document generated by Confluence on Oct 27, 2008 21:07 Page 36


applySecurityToProtocol
boolean no Whether or not
to apply the
security filter
to the protocol
endpoint.

proxy boolean no Whether or not


this outbound
endpoint is acting
as a web service
proxy. If so, it
will expect raw
xml as the input
parameter and
return an XML
stream as the
output.

mtomEnabled boolean no Whether or


not MTOM
(attachment
support) is
enabled for this
endpoint.

wsdlLocation string no The location of


the WSDL for your
service. If this
is a server side
endpoint it will
served to your
users.

Outbound Endpoint

Attributes of <outbound-endpoint...>

Name Type Required Default Description

wsdlPort string no The WSDL port


you wish to use to
communicate to
the service.

clientClass string no The name of the


client class that
CXF generated
using CXF's
wsdl2java tool.
You must use
wsdl2java if you
do not have both
the client and
the server in
the same JVM.
Otherwise, this
can be optional
if the endpoint
address is the

Document generated by Confluence on Oct 27, 2008 21:07 Page 37


same in both
cases.

operation string no The operation you


wish to invoke
on the outbound
endpoint.

proxy boolean no Whether or not


this outbound
endpoint is acting
as a web service
proxy. If so, it
will expect raw
xml as the input
parameter and
return an XML
stream as the
output.

mtomEnabled boolean no Whether or


not MTOM
(attachment
support) is
enabled for this
endpoint.

wsdlLocation string no The location of


the WSDL for your
service. If this
is a server side
endpoint it will
served to your
users.

Endpoint

Attributes of <endpoint...>

Name Type Required Default Description

frontend jaxws/simple no The CXF frontend


that is used
to build an
internal service
representation
from your Java
classes. The
default is "jaxws".
The "simple"
frontend is also
supported.

bindingUri string no The binding that


should be used
for this service.
It defaults to the
soap binding by
default.

Document generated by Confluence on Oct 27, 2008 21:07 Page 38


endpointName string no The WSDL
endpoint name of
your service.

serviceClass string no The class CXF


should use to
construct it's
service model.
This is optional
and by default
it will use the
implementation
class of your
component.

serviceName string no The WSDL service


name of your
service.

applyFiltersToProtocolboolean no Whether or not to


apply the filters
to the protocol
endpoint.

applyTransformersToProtocol
boolean no Whether or not
to apply the
transformers
to the protocol
endpoint.

applySecurityToProtocol
boolean no Whether or not
to apply the
security filter
to the protocol
endpoint.

wsdlPort string no The WSDL port


you wish to use to
communicate to
the service.

clientClass string no The name of the


client class that
CXF generated
using CXF's
wsdl2java tool.
You must use
wsdl2java if you
do not have both
the client and
the server in
the same JVM.
Otherwise, this
can be optional
if the endpoint
address is the
same in both
cases.

operation string no The operation you


wish to invoke
on the outbound
endpoint.

Document generated by Confluence on Oct 27, 2008 21:07 Page 39


proxy boolean no Whether or not
this outbound
endpoint is acting
as a web service
proxy. If so, it
will expect raw
xml as the input
parameter and
return an XML
stream as the
output.

mtomEnabled boolean no Whether or


not MTOM
(attachment
support) is
enabled for this
endpoint.

wsdlLocation string no The location of


the WSDL for your
service. If this
is a server side
endpoint it will
served to your
users.

Features

Wrapper Component
The WebServiceWrapperComponent class allows you to send
the result of a web service call to another endpoint.

Attributes of <wrapper-component...>

Name Type Required Default Description

address string no TODO

addressFromMessageboolean no Specifies that the


URL of the web
service will be
obtained from the
message itself.

wsdlPort string no The WSDL port


you wish to use to
communicate to
the service.

operation string no The operation you


wish to invoke
on the outbound
endpoint.

Document generated by Confluence on Oct 27, 2008 21:07 Page 40


Stax

Attributes of <stax...>

Name Type Required Default Description

xmlInputFactory string no

xmlOutputFactory string no

Document generated by Confluence on Oct 27, 2008 21:07 Page 41


Enabling WS-Addressing

This page last changed on May 21, 2008 by jackie.wheeler.

Enabling WS-Addressing
To enable your services to use WS-Addressing, you must supply an additional configuration file to the CXF
connector to tell it to enable WS-Addressing on your service and/or client.

To configure the connector:

<mule-configuration id="myId" version="1.0">


<description>JAX-WS Test</description>

<connector name="cxf" className="org.mule.providers.soap.cxf.CxfConnector">


<properties>
<property name="configurationLocation" value="your-cxf-config.xml" />
</properties>
</connector>

... your mule descriptors ..


</mule-configuration>

Next, you create a configuration file using the same name as the value you specified in the connector's
configurationLocation property. This file will look something like this:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:c="http://cxf.apache.org/core"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:wsa="http://cxf.apache.org/ws/addressing"
xmlns:http="http://cxf.apache.org/transports/http/configuration"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans.xsd
http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
http://cxf.apache.org/ws/addressing http://cxf.apache.org/schemas/ws/addressing.xsd
http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/
http-conf.xsd">

<jaxws:server name="{http://example.org/}HelloWorldPort" createdFromAPI="true">


<jaxws:features>
<wsa:addressing usingAddressingAdvisory="true"/>
</jaxws:features>
</jaxws:server>

<jaxws:client name="{http://example.org/}HelloWorldPort" createdFromAPI="true">


<jaxws:features>
<wsa:addressing usingAddressingAdvisory="true"/>
</jaxws:features>
</jaxws:client>

</beans>

CXF looks through this Spring configuration file and applies the properties to your clients and servers. It
uses the name attribute of the <server> or <client> to determine which service to apply these properties
to. In the above example, it is enabling the WS-Addressing feature on any service that has a port name
of "{http://example.org/}HelloWorldPort". You can determine your service's port name by looking at the
WSDL and looking for the <wsdl:port/> element. The value in the brackets ({}) are the targetNamespace
of your WSDL. The value after the brackets will are the "name" attribute on the <port> element.

Document generated by Confluence on Oct 27, 2008 21:07 Page 42


Manipulating WS-Addressing Headers

To manipulate the WS-Addressing headers inside the messages, you can write a JAX-WS handler or a CXF
interceptor. For a quick start, see the WS-Addressing sample inside the CXF distribution.

Document generated by Confluence on Oct 27, 2008 21:07 Page 43


Enabling WS-Security

This page last changed on Oct 13, 2008 by dan.diephouse@mulesource.com.

Enabling WS-Security
This page describes how to configure a client and service to use WS-Security. You should already have a
basic client and server running. For further information on how to configure WS-Security with CXF, you
should consult the CXF documentation which goes into more detail on how to configure the CXF service
interceptors.

UsernameToken Scenario
The UsernameToken feature in WS-Security is an interoperable way to exchange security tokens inside
a SOAP message. The following section describes how to configure the client and server to exchange a
username/password security token.

Server Configuration

On the server side, you do the following:

• Create a Mule service for your component implementation


• Configure the WSS4JInInterceptor and the SAAJInInterceptor. The former is responsible for checking
the security of your message.
• Write a server PasswordCallback that verifies the password.

You configure the server in the Mule configuration file. Following is an example:

<service name="greeterService">
<inbound>
<cxf:inbound-endpoint address="http://localhost:63081/services/greeter">
<cxf:inInterceptors>
<spring:bean class="org.apache.cxf.binding.soap.saaj.SAAJInInterceptor" />
<spring:bean class="org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor">
<spring:constructor-arg>
<spring:map>
<spring:entry key="action" value="UsernameToken" />
<spring:entry key="passwordCallbackRef" value-ref="serverCallback" />
</spring:map>
</spring:constructor-arg>
</spring:bean>
</cxf:inInterceptors>
</cxf:inbound-endpoint>
</inbound>
<component>
<singleton-object class="org.apache.hello_world_soap_http.GreeterImpl" />
</component>
</service>

The <cxf:inInterceptors> element configures the incoming interceptors on the service. The
WSS4JInInterceptor performs the security operations on the incoming SOAP message. The
"action" parameter controls which actions it performs on the incoming message - in this case the
"UsernameToken" action specifies that it will verify the username token via a specified password callback.
The password callback is specified by the "passwordCallbackRef" property, which is detailed in the next
section. The SAAJInInterceptor is also installed here. It enables the use of SAAJ, an in-memory DOM
document format, which is required by WSS4J.

Server callbacks verify passwords by supplying the password with which the incoming password will be
compared.

import java.io.IOException;

import javax.security.auth.callback.Callback;

Document generated by Confluence on Oct 27, 2008 21:07 Page 44


import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;

import org.apache.ws.security.WSPasswordCallback;

public class ServerPasswordCallback implements CallbackHandler


{

public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {

WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];

if (pc.getIdentifer().equals("joe")) {
// set the password on the callback. This will be compared to the
// password which was sent from the client.
pc.setPassword("password");
}
}
}

This allows you to write custom code which can load and compare passwords from custom backends,
such as databases or LDAP.

Client Configuration

On the client side, you do the following:

• Set up the CXF outbound endpoint


• Configure the CXF client so that it uses ws-security
• Set up a ClientPasswordCallback that supplies the password for the invocation

Following is a simple example that configures a CXF outbound endpoint:

<cxf:outbound-endpoint address="http://localhost:63081/services/greeter"
name="clientEndpoint"
clientClass="org.apache.hello_world_soap_http.SOAPService"
wsdlPort="SoapPort"
wsdlLocation="classpath:/wsdl/hello_world.wsdl"
operation="greetMe">
<cxf:outInterceptors>
<spring:bean class="org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor" />
<spring:bean class="org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor">
<spring:constructor-arg>
<spring:map>
<spring:entry key="action" value="UsernameToken" />
<spring:entry key="user" value="joe" />
<spring:entry key="passwordType" value="PasswordDigest" />
<!-- The callback supplies the password so its not stored in our config file -->
<spring:entry key="passwordCallbackRef" value-ref="clientCallback" />
</spring:map>
</spring:constructor-arg>
</spring:bean>
</cxf:outInterceptors>
</cxf:outbound-endpoint>

Configure the CXF Client to Use WS-Security


To use WS-Security, you add a configuration section to your "my-cxf-config.xml" file.

Note: if your client and your server are on separate machines, you create two separate files and then a
CXF connector configuration on each one.

<jaxws:client name="{http://apache.org/hello_world_soap_http}SoapPort" createdFromAPI="true">


<jaxws:outInterceptors>
<bean class="org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor" />

Document generated by Confluence on Oct 27, 2008 21:07 Page 45


<bean class="org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor">
<constructor-arg>
<map>
<entry key="action" value="UsernameToken" />
<entry key="user" value="joe" />
<entry key="passwordType" value="PasswordDigest" />
<!-- The callback supplies the password so its not stored in our config file -->
<entry key="passwordCallbackRef" value-ref="clientCallback" />
</map>
</constructor-arg>
</bean>
</jaxws:outInterceptors>
</jaxws:client>

<bean id="clientCallback" class="org.mule.providers.soap.cxf.wssec.ClientPasswordCallback"/>

The above configuration specifies the following:

• CXF should invoke the UsernameToken action.


• The user name is "joe"
• Send the password in digest form.
• Use the "clientCallback" bean to supply the password. (see below)

Client Password Callback

Following is a simple example client password callback that sets the password to use for the outgoing
invocation:

import java.io.IOException;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;

import org.apache.ws.security.WSPasswordCallback;

public class ClientPasswordCallback implements CallbackHandler


{
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];

// set the password for our message.


pc.setPassword("yourpassword");
}
}

Document generated by Confluence on Oct 27, 2008 21:07 Page 46


Proxying Web Services

This page last changed on Oct 15, 2008 by jackie.wheeler.

Proxying Web Services


Normally when building web services, you'll databind the XML to POJOs. A CXF component might receive
an OrderRequest object, or you might send an OrderRequest object via a CXF outbound router. But often
it is useful to work with the XML directly when building web services or consuming other web services.
The CXF transport includes the ability to do this.

While many times you can proxy web services without using CXF (for instance, by forwarding requests
from one HTTP endpoint to another), there are several cases where you might want to use CXF proxies:

• To work directly with the SOAP body


• To take advantage of the CXF web service standards support to use WS-Security or WS-Addressing
• To enforce WS-Policy assertions
• To easily service a WSDL associated with your service
• To transform a SOAP body

Server-side Proxying
To proxy a web service so you can work with the raw XML, you can create a simple inbound endpoint:

<cxf:inbound-endpoint address="http://localhost:63081/services/Echo" proxy="true"/>

This will make the SOAP body available as the Mule message payload as an XMLStreamReader.

Client-side Proxying
Similarly, you can create an outbound endpoint to send raw XML payloads:

<cxf:outbound-endpoint address="http://localhost:63081/services/Echo"
proxy="true"/>

Example: Routing Messages Based on SOAPAction Headers


with Transformations
This example shows how you can use message routing with CXF web service proxying to handle web
service requests that use an old message format. It will listen on the "http://localhost:63081/service"
endpoint and send the SOAP body to the outbound routers. If the message has a SOAPAction header of
"http://acme.com/v2/bid", it will send the message directly to the web service. If the header has a value
of "http://acme.com/v1/bid", it will apply XSLT transformations to convert the message on the way out
and on the way back in.

<service name="routeBasedOnSoapAction">
<inbound>
<cxf:inbound-endpoint address="http://localhost:63081/service" proxy="true"/>
</inbound>
<outbound>
<filtering-router>
<cxf:outbound-endpoint address="http://localhost:63081/services/Echo"
proxy="true"
remoteSync="true"/>
<message-property-filter pattern="SOAPAction=http://acme.com/v2/bid"/>
</filtering-router>
<filtering-router>
<cxf:outbound-endpoint address="http://localhost:63081/services/Echo"
proxy="true"
remoteSync="true">

Document generated by Confluence on Oct 27, 2008 21:07 Page 47


<transformers>
<mule-xml:xslt-transformer xsl-file="v1-to-v2.xsl"
returnClass="org.mule.module.xml.transformer.DelayedResult"/>
</transformers>
<response-transformers>
<mule-xml:xslt-transformer xsl-file="v2-to-v1.xsl"
returnClass="org.mule.module.xml.transformer.DelayedResult"/>
</response-transformers>
</cxf:outbound-endpoint>
<message-property-filter pattern="SOAPAction=http://acme.com/v1/bid"/>
</filtering-router>
</outbound>
</service>

Document generated by Confluence on Oct 27, 2008 21:07 Page 48


Using a Web Service Client as an Outbound Endpoint

This page last changed on Oct 15, 2008 by jackie.wheeler.

Using a Web Service Client as an Outbound


Endpoint
You can use a CXF-generated client as an outbound endpoint. First, you generate a CXF client using the
WSDL to Java tool from CXF or the Maven plugin.

Next, you configure the client as an outbound endpoint using the following properties:

• clientClass: The client class generated by CXF, which extends javax.xml.ws.Service.


• port: The WSDL port to use for communicating with the service
• wsdlLocation: The location of the WSDL for the service. CXF uses this to configure the client.
• operation: The operation name to invoke on the web service. The objects that you pass to the
outbound router must match the signature of the method for this operation. If your method takes
multiple parameters, they must be put in an Object[] array.

Following is a simple example:

<service name="csvPublisher">
<inbound>
<inbound-endpoint address="file://./books?pollingFrequency=100000&amp;autoDelete=false"/>
</inbound>
<component class="org.mule.example.bookstore.publisher.CsvBookPublisher"/>
<outbound>
<outbound-pass-through-router>
<cxf:outbound-endpoint
address="http://localhost:63081/services/greeter"
clientClass="org.apache.hello_world_soap_http.SOAPService"
wsdlPort="SoapPort"
wsdlLocation="classpath:/wsdl/hello_world.wsdl"
operation="greetMe"/>
</outbound-pass-through-router>
</outbound>
</service>

Document generated by Confluence on Oct 27, 2008 21:07 Page 49


Using a Web Service Client Directly

This page last changed on Oct 15, 2008 by jackie.wheeler.

Using a Web Service Client Directly


This page describes how to use a standalone CXF-generated client with Mule. This approach is different
from the outbound router approach, which is typically a more appropriate fit for most applications.

There are two ways to use CXF clients. First, you can generate a client from WSDL using the CXF WSDL
to Java tool. Second, if you've built your service via "code-first" methodologies, you can use the service
interface to build a client proxy object.

When using a CXF client, it automatically discovers the Mule instance (provided you're in the same JVM/
Classloader) and uses it for your transport. Therefore, if you've generated a client from WSDL, invoking a
service over Mule can be as simple as the following:

HelloWorldService service = new HelloWorldService();


HelloWorld hello = service.getSoapPort();

// Possibly set an alternate request URL:


// ((BindingProvider) greeter).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
"http://localhost:63081/greeter");
String sayHi = hello.sayHi();

Building a Client Proxy


Following is an example of how to construct a client using the service that was developed in Building a
CXF Web Service:

QName SERVICE_NAME = new QName("http://server.hw.demo/", "HelloWorld");


QName PORT_NAME = new QName("http://server.hw.demo/", "HelloWorldPort");

Service service = Service.create(SERVICE_NAME);

// Endpoint Address
String endpointAddress = http://localhost:63081/hello";

// Add a port to the Service


service.addPort(PORT_NAME, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress);

HelloWorld hw = service.getPort(HelloWorld.class);

System.out.println(hw.sayHi("World"));

Additional Resources
• Developing a JAX-WS consumer
• WSDL to Java
• CXF Maven plugin

Document generated by Confluence on Oct 27, 2008 21:07 Page 50


Using HTTP GET Requests

This page last changed on Oct 15, 2008 by jackie.wheeler.

Using HTTP GET Requests


CXF has built-in support for understanding GET requests, which use the following format:

http://host/service/OPERATION/PARAM_NAME/PARAM_VALUE

For example:

@WebService(endpointInterface = "org.mule.samples.echo.components.EchoService",
serviceName = "echo")
public class EchoComponent implements EchoService
{
public String echo(String string)
{
return string;
}
}

The above Echo service is hosted in Mule on the endpoint cxf:http://localhost:65081/services/EchoUMO,


so you can access the service from a simple web browser by typing the following:

http://localhost:65081/services/EchoUMO/echo/string/hello

This will send the value "hello" for the string parameter to the echo() method.

Document generated by Confluence on Oct 27, 2008 21:07 Page 51


Using MTOM

This page last changed on Sep 19, 2008 by jackie.wheeler.

Using MTOM
This page is ready for review

This page describes the basics of how to use MTOM inside your service. For more information, go to the
MTOM documentation for CXF. Portions of the examples on this page are from that guide.

For a WSDL-first service, the general process is as follows:

1. Write your WSDL


2. Generate your server stubs
3. Configure the CXF endpoint in Mule

Writing an MTOM-enabled WSDL


To get started, write a WSDL like you would normally. Use xsd:base64Binary schema types to represent
any binary data that you want to send.

Normally, when you are transferring binary data, you write a schema type like this:

<element name="yourData" type="xsd:base64Binary"


xmime:expectedContentTypes="application/octet-stream"/>

To tell CXF to treat this binary type as an attachment, you must add an xmime:expectedContentTypes
attribute to it:

<schema targetNamespace="http://mediStor.org/types/"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xmime="http://www.w3.org/2005/05/xmlmime">

<element name="yourData" type="xsd:base64Binary"


xmime:expectedContentTypes="application/octet-stream"/>
...
</schema>

Generating Server Stubs


After writing your WSDL, you run wsdl2java on it to generate server stubs. To do this, download the CXF
distribution, extract it, and then enter the following command:

$ ./apache-cxf-2.0.5-incubator/bin/wsdl2java -d outputDirectory path/to/your.wsdl

This command generates a server stub. If the base64Binary type is an argument to one of your
operations, CXF will generate a method like this:

public void yourOperation(DataHandler handler) {


...
}

You can use this DataHandler method to access the attachment data by calling
"handler.getInputStream();".

Configure the CXF Endpoint


When you configure the endpoint, set the mtomEnabled attribute to true to enable MTOM:

<service name="mtomService">

Document generated by Confluence on Oct 27, 2008 21:07 Page 52


<inbound>
<cxf:inbound-endpoint address="http://localhost:63081/services/mtomService" mtomEnabled="true" />
</inbound>
<component>
<singleton-object class="org.mule.transport.cxf.testmodels.TestMtomImpl" />
</component>
</service>

Document generated by Confluence on Oct 27, 2008 21:07 Page 53


EJB Transport

This page last changed on Oct 15, 2008 by jackie.wheeler.

EJB Transport
The EJB transport allows EJB session beans to be invoked as part of an event flow. Components can be
given an EJB outbound endpoint, which will invoke the remote object and optionally return a result.

The Javadoc for this transport can be found here .

Connector
The Mule EJB Connector provides connectivity for EJB beans.

Attributes of <connector...>

Name Type Required Default Description

pollingFrequency long no Period (ms)


between polling
connections.

securityManager- name (no spaces) no Bean reference


ref to the security
manager that
should be used.

securityPolicy string no The security


policy (file name)
used to enable
connections.

serverClassName name (no spaces) no The target class


name.

serverCodebase string no The target


method.

For example:

<ejb:connector name="ejb" jndiContext-ref="jndiContext" securityPolicy="rmi.policy" />

Using the EJB Connector


EJB endpoints are configured the same way as RMI endpoints. Note that only outbound endpoints can use
the EJB transport. For a given endpoint, you must provide the following information:

• registry host
• registry port
• remote home name
• remote method name

These values will be used to establish the dispatcher connection. For example:

<ejb:endpoint host="localhost" port="1099" object="SomeService" method="remoteMethod"/>

Alternatively, you could use URI-based configuration:

Document generated by Confluence on Oct 27, 2008 21:07 Page 54


<outbound-endpoint address="ejb://localhost:1099/SomeService?method=remoteMethod"/>

If the remoteMethod can take one or more input arguments, you configure them on the endpoint as
list properties. A recommended approach is to use a list of comma-separated values in the property
methodArgumentTypes.

<properties>
<list name="methodArgumentTypes">
<entry value="java.lang.String,java.lang.String,java.math.BigInteger"/>
</list>
</properties>

Multiple arguments are passed in as an array of objects as the payload of the Mule event.

Transformers
There are no specific transformers required for EJB.

Document generated by Confluence on Oct 27, 2008 21:07 Page 55


Email Transport

This page last changed on Sep 17, 2008 by jackie.wheeler.

Email Transport
This page is ready for review

Protocols
Each email protocol has a dedicated transport and configuration schema. The transports can be used to
connect to POP3 and IMAP mailboxes and for sending events over SMTP using the javax.mail API. For
each of the protocols, SSL is supported and is enabled using POP3S, IMAPS, and SMTPS.

The email connectors can be used to send and receive event payloads over Mail protocols and support
protocol features such as attachments, replyTo, CC and BCC addresses, binary content types, and custom
headers.

The Javadoc for the Mail connectors can be found here .

For information about configuring specific endpoints, see the following links:

• SMTP and SMTPS Transport


• POP3 and POP3S Transport
• IMAP and IMAPS Transport

Filters
Filters can be set on an endpoint to filter out any unwanted messages. The Email transport provides a
couple of filters that can either be used directly or extended to implement custom filtering rules.

Filter Description

org.mule.transport.email.filters.AbstractMailFilter A base filter implementation that must be


extended by any other mail filter.

org.mule.transport.email.filters.MailSubjectRegExFilter
Applies a regular expression to a Mail Message
subject.

For more information on filters, see Using Filters.

Transformers
These are transformers specific to this transport. Note that these are added automatically to the Mule
registry
at start up. When doing automatic transformations these will be included when searching for the correct
transformers.

Name Description

email-to-string-transformer Converts an email message to string format.

string-to-email-transformer Converts a string message to email format.

object-to-mime-transformer Converts an object to MIME format.

Document generated by Confluence on Oct 27, 2008 21:07 Page 56


mime-to-bytes-transformer Converts a MIME message to a byte array.

bytes-to-mime-transformer Converts a byte array message to MIME format.

Document generated by Confluence on Oct 27, 2008 21:07 Page 57


File Transport

This page last changed on Oct 15, 2008 by jackie.wheeler.

File Transport
The File transport allows files to be read and written to and from directories on the local file system. The
connector can be configured to filter the file it reads and the way files are written, such as whether binary
output is used or the file is appended.

Connector
The File connector configures the default behavior for File endpoints that reference the connector. If there
is only one File connector configured, all File endpoints will use that connector.

Attributes of <connector...>

Name Type Required Default Description

writeToDirectory string no The directory path


where the file
should be written
on dispatch. This
path is usually set
as the endpoint
of the dispatch
event, however
this allows you to
explicitly force a
single directory for
the connector.

readFromDirectory string no The directory


path where the
file should be
read from. This
path is usually set
as the inbound
endpoint, however
this allows you to
explicitly force a
single directory for
the connector.

autoDelete boolean no By default, when a


file is received it is
read into a String
or byte[]. The file
is moved if the
moveToDirectory
is set, otherwise
it is deleted. To
access the File
object set this
property to false
and specify a
NoActionTransformer
transformer for
the connector.

Document generated by Confluence on Oct 27, 2008 21:07 Page 58


Mule will not
delete the file,
so it is up to the
component to
delete it when
it is done. If the
moveToDirectory
is set, the file is
first moved, then
the File object of
the moved file
is passed to the
component. It is
recommended
that a
moveToDirectory
is specified when
turning autoDelete
off.

outputAppend boolean no Whether the


output should be
appended to the
existing file.

serialiseObjects boolean no Determines


whether objects
should be
serialized to the
file or not. If not
the raw bytes or
text is written.

streaming boolean no Should a


FileInputStream
be sent as the
message payload
or a File?

pollingFrequency long no The frequency


in milliseconds
that the read
directory should
be checked.
Note that the
read directory
is specified by
the endpoint
of the listening
component.

fileAge long no Miniumum age


(ms) for a file to
be processed.
This can be useful
when consuming
large files. It tells
Mule to wait for
a period of time
before consuming
the file allowing
the file to be
completely written

Document generated by Confluence on Oct 27, 2008 21:07 Page 59


before the file is
porcessed.

moveToPattern string no The pattern to


use when moving
a read file to
an new location
determined by the
moveToDirectory
property. This can
use the patterns
supported by the
filename-parser
configured for this
connector

moveToDirectory string no The directory path


where the file
should be written
once it has been
read. If this is not
set the file read is
deleted.

comparator class name no Sort incoming files


using the specified
comparator,
such as
comparator="org.mule.transp
The class must
implement the
java.util.Comparator
interface.

reverseOrder boolean no Whether the


comparator
order should be
reversed.

outputPattern string no The pattern to use


when writing a file
to disk. This can
use the patterns
supported by the
filename-parser
configured for this
connector

Child Elements of <connector...>

Name Cardinality Description

abstract-filenameParser 0..1 A placeholder for flename parser


elements.

Document generated by Confluence on Oct 27, 2008 21:07 Page 60


Inbound Endpoint

Attributes of <inbound-endpoint...>

Name Type Required Default Description

path string no A file drectory


location.

pollingFrequency long no The frequency


in milliseconds
that the read
directory should
be checked.
Note that the
read directory
is specified by
the endpoint
of the listening
component.

fileAge long no Miniumum age


(ms) for a file to
be processed.
This can be useful
when consuming
large files. It tells
Mule to wait for
a period of time
before consuming
the file allowing
the file to be
completely written
before the file is
porcessed.

moveToPattern string no The pattern to


use when moving
a read file to
an new location
determined by the
moveToDirectory
property. This can
use the patterns
supported by the
filename-parser
configured for this
connector

moveToDirectory string no The directory path


where the file
should be written
once it has been
read. If this is not
set the file read is
deleted.

comparator class name no Sort incoming files


using the specified
comparator,
such as

Document generated by Confluence on Oct 27, 2008 21:07 Page 61


comparator="org.mule.transp
The class must
implement the
java.util.Comparator
interface.

reverseOrder boolean no Whether the


comparator
order should be
reversed.

Outbound Endpoint

Attributes of <outbound-endpoint...>

Name Type Required Default Description

path string no A file drectory


location.

outputPattern string no The pattern to use


when writing a file
to disk. This can
use the patterns
supported by the
filename-parser
configured for this
connector

Endpoint

Attributes of <endpoint...>

Name Type Required Default Description

path string no A file drectory


location.

pollingFrequency long no The frequency


in milliseconds
that the read
directory should
be checked.
Note that the
read directory
is specified by
the endpoint
of the listening
component.

fileAge long no Miniumum age


(ms) for a file to
be processed.
This can be useful
when consuming
large files. It tells
Mule to wait for

Document generated by Confluence on Oct 27, 2008 21:07 Page 62


a period of time
before consuming
the file allowing
the file to be
completely written
before the file is
porcessed.

moveToPattern string no The pattern to


use when moving
a read file to
an new location
determined by the
moveToDirectory
property. This can
use the patterns
supported by the
filename-parser
configured for this
connector

moveToDirectory string no The directory path


where the file
should be written
once it has been
read. If this is not
set the file read is
deleted.

comparator class name no Sort incoming files


using the specified
comparator,
such as
comparator="org.mule.transp
The class must
implement the
java.util.Comparator
interface.

reverseOrder boolean no Whether the


comparator
order should be
reversed.

outputPattern string no The pattern to use


when writing a file
to disk. This can
use the patterns
supported by the
filename-parser
configured for this
connector

Transformers
These are transformers specific to this transport. Note that these are added automatically to the Mule
registry
at start up. When doing automatic transformations these will be included when searching for the correct
transformers.

Name Description

Document generated by Confluence on Oct 27, 2008 21:07 Page 63


file-to-byte-array-transformer Reads the contents of a java.io.File into a byte
array (byte[]).

file-to-string-transformer Reads the contents of a java.io.File into a


java.lang.String.

Filters
Filters can be used on inbound endpoints to control which data is received by a service.

Name Description

filename-wildcard-filter This filter can be used to restrict the files being


processed by applying wildcard expressions to the
filename. For example, you can read only .xml
and .txt files by entering the following:

<file:filename-wildcard-filter
pattern="*.txt,*.xml"/>

filename-regex-filter This filter can be used to restrict the files


being processed by applying Java regular
expressions to the filename, such as
pattern="myCustomerFile(.*)".

Filename Parsers
The filenameParser is set on the connector used when writing files to a directory. The parser will
convert the outputPattern attribute to a string using the parser and the current message.

Legacy Filename Parser


The file connector uses this as a default implementation, it understands the following patterns:

• ${DATE} - the current date in the format dd-MM-yy_HH-mm-ss.SS


• ${DATE:yy-MM-dd} - the current date using the specified format
• ${SYSTIME} - The current system time milliseconds
• ${UUID} - A generated Universally unique id
• ${ORIGINALNAME} - The original file name if the file being written was read from another location
• ${COUNT} - An incremental counter.

Expression Filename Parser


ExpressionFilenameParser can use any expression language supported by Mule to construct a file name
for the current message. Expressions can be xpath, xquery, ognl, mvel, header, function, and more. For
example, an xpath expression can be defined to pull a message ID out of an XML message and use that
as the file name:

${xpath:/message/header/@id}

This parser superseeds the legacy-filename-parser from previous releases of Mule. The following
demonstrates how to achieve the same results when using the expression-filename-parser over the
legacy-filename-parser.

• ${DATE} : ${function:dateStamp}
• ${DATE:yy-MM-dd} : ${function:dateStamp(yy-MM-dd)}
• ${SYSTIME} : ${function:systime}
• ${UUID} : ${function:uuid}
• ${ORIGINALNAME} : ${header:originalFilename}

Document generated by Confluence on Oct 27, 2008 21:07 Page 64


• ${COUNT} : ${function:counter} - note that this is a global counter. If you want a local counter per
file connector then you should use the legacy-filename-parser.
• ${[Message Property Name]} : ${header:[Message Property Name]}

Custom Filename Parser


Allows the user to specify custom filename parser. The implementation has to implement
org.mule.transport.file.FilenameParser.

Attributes of <custom-filename-parser...>

Name Type Required Default Description

class name (no spaces) no The


implementation
class name that
implements
org.mule.transport.file.Fil

Expressing File Endpoints


File endpoints can be expressed using standard File URI syntax:

file://<path>[MULE:?params]

For example, to connect to a directory called /temp/files -

Unix

file:///temp/files

Note the extra slash to denote a path from the root (absolute path).

Windows

file:///C:/temp/files

The Unix style will still work in Windows if you map to a single drive (the one Mule was started from).

To specify a relative path use:

file://./temp

or

file://temp

Note only two slashes are used for the protocol, so it's a relative path.

or

file://?address=./temp

To connect to a windows network drive:

file:////192.168.0.1/temp/

Document generated by Confluence on Oct 27, 2008 21:07 Page 65


FTP Transport

This page last changed on Oct 17, 2008 by jackie.wheeler.

Table of Contents

Click here to expand...

• Connector
• ° Attributes of <connector...>
° Child Elements of <connector...>
° Mule Enterprise Connector Attributes

• Endpoint
• ° Attributes of <endpoint...>

• Inbound Endpoint
• ° Attributes of <inbound-endpoint...>

• Outbound Endpoint
• ° Attributes of <outbound-endpoint...>

• Generic FTP Endpoints


• Filename Filters
• ° Property Overrides

Connector
The FTP connector is used to configure the default behavior for FTP endpoints that reference the
connector. If there is only one FTP connector configured, all FTP endpoints will use that connector.

Attributes of <connector...>

Name Type Required Default Description

validateConnections boolean no Causes Mule


to validate
connections before
use.

connectionFactoryClass
class name no A class that
extends
FtpConnectionFactory.
The
FtpConnectionFactory
is responsible
for creating a
connection to
the server using
the credentials
provided by
the endpoint.
The default
implementation
supplied with
Mule uses the
Commons Net
project from
Apache.

pollingFrequency long no How frequently


in milliseconds
to check the

Document generated by Confluence on Oct 27, 2008 21:07 Page 66


read directory.
Note that the
read directory
is specified by
the endpoint
of the listening
component.

outputPattern string no The pattern to use


when writing a file
to disk. This can
use the patterns
supported by the
filename-parser
configured for this
connector

binary boolean no Select/disable


binary file transfer
type.

passive boolean no Select/disable


passive protocol
(more likely to
work through
firewalls).

Child Elements of <connector...>

Name Cardinality Description

file:abstract-filenameParser 0..1 The filenameParser is used


when writing files to an FTP
server. The parser will convert
the outputPattern attribute to
a string using the parser and
the current message. To add a
parser to your configuration,
you import the file namespace
into your XML configuration.
For more information about
filenameParsers, see the File
Transport.

Mule Enterprise Connector Attributes

The following attributes are available on the FTP connector in Mule Enterprise only (as of version 1.6):

moveToDirectory The directory path where the file should be


written after it has been read. If this property is
not set, the file is deleted.

moveToPattern The pattern to use when moving a read file to a


new location as specified by the moveToDirectory
property. This property can use the patterns
supported by the filenameParser configured for
this connector.

Document generated by Confluence on Oct 27, 2008 21:07 Page 67


fileAge Does not process the file unless it's older than the
specified age in milliseconds.

Endpoint

Attributes of <endpoint...>

Name Type Required Default Description

path string no A file location on


the remote server.

user string no If FTP is


authenticated,
this is the
username used for
authenitcation.

password string no The password for


the user being
authenticated.

host string no An IP address


(such as
www.mulesource.com,
localhost, or
192.168.0.1).

port port number no The port number


to connect on.

binary boolean no Select/disable


binary file transfer
type.

passive boolean no Select/disable


passive protocol
(more likely to
work through
firewalls).

pollingFrequency long no How frequently


in milliseconds
to check the
read directory.
Note that the
read directory
is specified by
the endpoint
of the listening
component.

outputPattern string no The pattern to use


when writing a file
to disk. This can
use the patterns
supported by the
filename-parser

Document generated by Confluence on Oct 27, 2008 21:07 Page 68


configured for this
connector

Inbound Endpoint

Attributes of <inbound-endpoint...>

Name Type Required Default Description

path string no A file location on


the remote server.

user string no If FTP is


authenticated,
this is the
username used for
authenitcation.

password string no The password for


the user being
authenticated.

host string no An IP address


(such as
www.mulesource.com,
localhost, or
192.168.0.1).

port port number no The port number


to connect on.

binary boolean no Select/disable


binary file transfer
type.

passive boolean no Select/disable


passive protocol
(more likely to
work through
firewalls).

pollingFrequency long no How frequently


in milliseconds
to check the
read directory.
Note that the
read directory
is specified by
the endpoint
of the listening
component.

Outbound Endpoint

Attributes of <outbound-endpoint...>

Name Type Required Default Description

Document generated by Confluence on Oct 27, 2008 21:07 Page 69


path string no A file location on
the remote server.

user string no If FTP is


authenticated,
this is the
username used for
authenitcation.

password string no The password for


the user being
authenticated.

host string no An IP address


(such as
www.mulesource.com,
localhost, or
192.168.0.1).

port port number no The port number


to connect on.

binary boolean no Select/disable


binary file transfer
type.

passive boolean no Select/disable


passive protocol
(more likely to
work through
firewalls).

outputPattern string no The pattern to use


when writing a file
to disk. This can
use the patterns
supported by the
filename-parser
configured for this
connector

Generic FTP Endpoints


FTP endpoints can be expressed using standard FTP URI syntax:

ftp://<username>:<password>@<hostname[MULE::port]>/[MULE:address]

which would render a URI like this:

ftp://joe:123456@ftp.mycompany.com/~

This URI would connect to the FTP server at mycompany.com with a user name of joe with password
123456 and would work on Joe's home directory.

Escape Your Credentials

When including the user name and password in the endpoint, escape any characters
that are illegal for URIs, such as the @ character. For example, if the user name is
user@myco.com, you should enter it as user%40myco.com.

Document generated by Confluence on Oct 27, 2008 21:07 Page 70


Filename Filters
Filters can be set on the endpoint to control which files are received by the endpoint. The filters are
expressed in a comma-separated list. To set up a filter to only read .XML and .TXT files, you would use
the following code:

<ftp:endpoint user="joe" password="123456" host="ftp.mycompany.com" path="/ftp/incoming">


<file:filename-wildcard-filter pattern="*.txt,*.xml"/>
</ftp:endpoint>

Property Overrides

You can override certain properties when defining FTP endpoints to control the endpoint's configuration.
These properties can be set on the endpoint or the current message (see the appropriate endpoint
attributes).

For example, to set the output pattern:

<ftp:endpoint user="joe" password="123456" host="ftp.mycompany.com" path="/ftp/incoming"


outputPattern="FtpFile-${DATE}.done"/>

Or to specify the same endpoint using a URI:

ftp://joe:123456@ftp.mycompany.com/ftp/done?outputPattern=FtpFile-${DATE}.done

For more information about configuring endpoints, see Configuring Endpoints.

Document generated by Confluence on Oct 27, 2008 21:07 Page 71


HTTP Transport

This page last changed on Oct 15, 2008 by jackie.wheeler.

Table of Contents

Click here to expand...

• HTTP Transport
• ° Connector
° - Attributes of <connector...>
° Inbound Endpoint
° - Attributes of <inbound-endpoint...>
° Outbound Endpoint
° - Attributes of <outbound-endpoint...>
° Endpoint
° - Attributes of <endpoint...>
° Transformers
° Polling Connector
° - Attributes of <polling-connector...>
° Rest Service Component
° - Attributes of <rest-service-component...>
- Child Elements of <rest-service-component...>
° Security
° - Sending Credentials
° Cookies
° Polling HTTP Services
° Handling HTTP Content-Type and Encoding
° - Sending HTTP
- Receiving HTTP
° Including Custom Header Properties
° Getting a Hash Map of Properties

HTTP Transport
The HTTP transport provides support for exposing services over HTTP and making HTTP client requests
from Mule services to external services as part of service event flows. Mule supports inbound, outbound,
and polling HTTP endpooints. These endpoints support all common features of the HTTP spec, such as
ETag processing, cookies, and keepalive. Both HTTP 1.0 and 1.1 are supported.

Connector
Allows Mule to communicate over HTTP. All parts of the HTTP spec are covered by Mule, so you can
expect ETags to be honored as well as keep alive semantics and cookies.

Attributes of <connector...>

Name Type Required Default Description

cookieSpec netscape/rfc2109 no The cookie


specification
to be used by
this connector
when cookies are
enabled.

proxyHostname string no The proxy host


name or address.

Document generated by Confluence on Oct 27, 2008 21:07 Page 72


proxyPassword string no The password
to use for proxy
access.

proxyPort port number no The proxy port


number.

proxyUsername string no The username


to use for proxy
access.

enableCookies boolean no Whether to


support cookies.

Inbound Endpoint
An inbound HTTP endpoint exposes a service over HTTP, essentially making it an HTTP server. If polling of
a remote HTTP service is required, this endpoint should be configured with a polling HTTP connector.

Attributes of <inbound-endpoint...>

Name Type Required Default Description

user string no The user name


(if any) that
will be used to
authenticate
against.

password string no The password for


the user.

host string no The host to


connect to.
For inbound
endpoints, this
should be an
address of a local
network interface.

port port number no The port number


to use when a
connection is
made.

path string no The path for the


HTTP URL.

contentType string no The HTTP


ContentType to
use.

method httpMethodTypes no The HTTP method


to use.

Outbound Endpoint
The HTTP outbound endpoint allows Mule to send requests to external servers or Mule inbound HTTP
endpoints using the HTTP protocol.

Document generated by Confluence on Oct 27, 2008 21:07 Page 73


Attributes of <outbound-endpoint...>

Name Type Required Default Description

user string no The user name


(if any) that
will be used to
authenticate
against.

password string no The password for


the user.

host string no The host to


connect to.
For inbound
endpoints, this
should be an
address of a local
network interface.

port port number no The port number


to use when a
connection is
made.

path string no The path for the


HTTP URL.

contentType string no The HTTP


ContentType to
use.

method httpMethodTypes no The HTTP method


to use.

Endpoint
Configures a 'global' HTTP endpoint that can be referenced by services. Services can augment the
configuration defined in the global endpoint with local configuration elements.

Attributes of <endpoint...>

Name Type Required Default Description

user string no The user name


(if any) that
will be used to
authenticate
against.

password string no The password for


the user.

host string no The host to


connect to.
For inbound
endpoints, this

Document generated by Confluence on Oct 27, 2008 21:07 Page 74


should be an
address of a local
network interface.

port port number no The port number


to use when a
connection is
made.

path string no The path for the


HTTP URL.

contentType string no The HTTP


ContentType to
use.

method httpMethodTypes no The HTTP method


to use.

Transformers
These are transformers specific to this transport. Note that these are added automatically to the Mule
registry
at start up. When doing automatic transformations these will be included when searching for the correct
transformers.

Name Description

http-client-response-to-object-transformer A transformer that converts an HTTP response to


a Mule Message. The payload may be a String,
stream, or byte array.

http-response-to-string-transformer Converts an HTTP response payload into a string.


The headers of the response will be preserved on
the message.

object-to-http-client-request-transformer This transformer will creat a valid HTTP request


using the current message and any HTTP headers
set on the current message.

message-to-http-response-transformer This transformer will creat a valid HTTP response


using the current message and any HTTP headers
set on the current message.

Polling Connector
Allows Mule to poll an external HTTP server and generate events from the result. This is useful for pull-
only web services.

Attributes of <polling-connector...>

Name Type Required Default Description

cookieSpec netscape/rfc2109 no The cookie


specification
to be used by
this connector

Document generated by Confluence on Oct 27, 2008 21:07 Page 75


when cookies are
enabled.

proxyHostname string no The proxy host


name or address.

proxyPassword string no The password


to use for proxy
access.

proxyPort port number no The proxy port


number.

proxyUsername string no The username


to use for proxy
access.

enableCookies boolean no Whether to


support cookies.

pollingFrequency long no The time in


milliseconds to
wait between
each request to
the remote HTTP
server.

checkEtag boolean no Whether the ETag


header from the
remote server is
processed if the
header is present.

discardEmptyContentboolean no Whether Mule


should discard
any messages
from the remote
server that have
a zero content
length. For many
services a zero
length would
mean there was
no data to return.
If the remote
HTTP server does
return content
to say that that
the request is
empty, users
can configure
a conent filter
on the endpoint
to filter these
messages out.

Rest Service Component


The REST service wrapper component ( org.mule.transport.http.components.RESTServiceWrapper )
allows you to proxy REST style services as local Mule components. You can configure this component with
a service URL, and you can use the properties described below to configure the parameters and error
conditions on the service. For an example of how to configure the RESTServiceWrapper and invoke an
ASPX web service hosted by http://www.webservicex.net, see the Stock Quote Example.

Document generated by Confluence on Oct 27, 2008 21:07 Page 76


Attributes of <rest-service-component...>

Name Type Required Default Description

httpMethod GET/POST no GET The HTTP method


to use when
making the
service request.

serviceUrl no The service URL to


use when making
the request. This
should not contain
any parameters,
since these should
be configured on
the component.
The service URL
can contain Mule
expressions, so
the URL can be
dynamic for each
message request.

Child Elements of <rest-service-component...>

Name Cardinality Description

error-filter 0..1 An error filter can be used to


detect whether the response
from the remote service resulted
in an error.

payloadParameterName 0..* If the payload of the message


is to be attached as a URL
parameter, this should be set
to the parameter name. If the
message payload is an array of
objects that multiple parameters
can be set to, use each element
in the array.

requiredParameter 0..* These are parameters that must


be available on the current
message for the request to be
successful. The Key maps to
the parameter name, the value
can be any one of the valid
expressions supported by Mule.

optionalParameter 0..* These are parameters that if


they are on the current message
will be added to the request,
otherwise they will be ignored.
The Key maps to the parameter
name, the value can be any
one of the valid expressions
supported by Mule.

Document generated by Confluence on Oct 27, 2008 21:07 Page 77


Security
You can use the HTTPS transport to create secure connections over HTTP. If you want to secure requests
to your HTTP endpoint, the HTTP connector supports HTTP Basic/Digest authentication methods (as well
as the Mule generic header authentication). To configure HTTP Basic, you configure a Security Endpoint
Filter on an HTTP endpoint.

<inbound-endpoint address="http://localhost:4567">
<acegi:http-security-filter realm="mule-realm" />
</inbound-endpoint>

You must configure the security manager on the Mule instance against which this security filter will
authenticate. For information about security configuration options and examples, see Configuring
Security.

If you want to make an HTTP request that requires authentication, you can set the credentials on the
endpoint:

<inbound-endpoint address="user:password@mycompany.com/secure">
<acegi:http-security-filter realm="mule-realm" />
</inbound-endpoint>

For general information about endpoint configuration, see Configuring Endpoints.

Sending Credentials

If you want to make an HTTP request that requires authentication, you can set the credentials on the
endpoint:

http://user:password@mycompany.com/secure

Cookies
If you want to send cookies along on your outgoing request, simply configure them on the endpoint:

<http:outbound-endpoint address="http://localhost:8080" method="POST">


<properties>
<spring:entry key="Content-Type" value="text/xml" />
<spring:entry key="cookies">
<spring:map>
<spring:entry key="customCookie" value="yes" />
</spring:map>
</spring:entry>
</properties>
</http:outbound-endpoint>

Polling HTTP Services


The HTTP transport supports polling an HTTP URL, which is useful for grabbing periodic data from a page
that changes or to invoke a REST service, such as polling an Amazon Queue.

To configure the HTTP Polling receiver, you include an HTTP polling-connector configuration in your Mule
configuration:

<http:polling-connector name="PollingHttpConnector" pollingFrequency="30000" reuseAddress="true" />

To use the connector in your endpoints, use:

<http:inbound-endpoint user="marie" password="marie" host="localhost" port="61205" connector-


ref="PollingHttpConnector" />

Document generated by Confluence on Oct 27, 2008 21:07 Page 78


Handling HTTP Content-Type and Encoding

Sending HTTP

The following behavior applies when sending POST request bodies as a client and when returning a
response body:

For a String, char[], Reader, or similar:

• If the endpoint has encoding set explicitly, use that


• Otherwise, take it from the message's property Content-Type
• If none of these is set, use the Mule Context's configuration default.
• For Content-Type, send the message's property Content-Type but with the actual encoding set.

For binary content, encoding is not relevant. Content-Type is set as follows:

• If the Content-Type property is set on the message, send that.


• Send "application/octet-stream" as Content-Type if none is set on the message.

Receiving HTTP

When receiving HTTP responses, the payload of the MuleMessage will always be the InputStream of the
HTTP response.

Including Custom Header Properties


When making a new HTTP client request, Mule filters out any existing HTTP request headers because they
are often from a previous request. For example, if you have an HTTP endpoint that proxies another HTTP
endpoint, you wouldn't want to copy the Content-Type header property from the first HTTP request to
the second request.

If you do want to include HTTP headers, you can specify them using the http.custom.headers map
property as follows:

<outbound>
<outbound-pass-through-router>
<outbound-endpoint address="http://localhost:9002/events" connector-ref="HttpConnector">
<properties>
<spring:entry key="http.custom.headers">
<spring:map>
<spring:entry key="Content-Type" value="image/png"/>
<spring:entry key="Accept" value="*.*"/>
</spring:map>
</spring:entry>
</properties>
</outbound-endpoint>
</outbound-pass-through-router>
</outbound>

Getting a Hash Map of Properties


You can use the custom transformer HttpRequestBodyToParamMap on your inbound endpoint to return
the message properties as a hash map of name-value pairs. This transformer handles GET and POST with
application/x-www-form-urlencoded content type.

For example:

<http:inbound-endpoint ...>
<custom-transformer name="myTransformer"
class="org.mule.transport.http.transformers.HttpRequestBodyToParamMap" />
</http:inbound-endpoint>

Document generated by Confluence on Oct 27, 2008 21:07 Page 79


HTTPS Transport

This page last changed on Sep 19, 2008 by jackie.wheeler.

HTTPS Transport
[ HTTPS Connector ] [ Polling Connector ] [ HTTPS Endpoints ]

The Secure HTTP transport provides support for exposing services over HTTP and making HTTP client
requests from Mule services to external services as part of service event flows. Mule supports secure
inbound, secure outbound, and secure polling HTTP endpoints. These endpoints support all common
features of the HTTP spec, such as ETag processing, cookies, and keepalive. Both HTTP 1.0 and 1.1 are
supported.

HTTPS Connector
This connector provides Secure HTTP connectivity on top of what is already provided with the Mule HTTP
Transport. Secure connections are made on behalf of an entity, which can be anonymous or identified by
a certificate. The key store provides the certificates and associated private keys necessary for identifying
the entity making the connection. Additionally, connections are made to trusted systems. The public
certificates of trusted systems are stored in a trust store, which is used to verify that the connection
made to a remote system matches the expected identity.

Property Description

tls-client Configures the client key store with the following


attributes:

• path: The location (which will be resolved


relative to the current classpath and file
system, if possible) of the keystore that
contains public certificates and private keys
for identification
• storePassword: The password used to
protect the keystore
• class: The type of keystore used (a Java
class name)

tls-key-store Configures the direct key store with the following


attributes:

• path: The location (which will be resolved


relative to the current classpath and file
system, if possible) of the keystore that
contains public certificates and private keys
for identification
• class: The type of keystore used (a Java
class name)
• keyPassword: The password used to protect
the private key
• storePassword: The password used to
protect the keystore
• algorithm: The algorithm used by the
keystore

tls-server Configures the trust store. The attributes are:

• path: The location (which will be resolved


relative to the current classpath and file

Document generated by Confluence on Oct 27, 2008 21:07 Page 80


system, if possible) of the trust store that
contains public certificates of trusted servers
• storePassword: The password used to
protect the trust store
• class: The type of trust store used (a Java
class name)
• algorithm: The algorithm used by the trust
store
• factory-ref: Reference to the trust manager
factory
• explicitOnly: Whether this is an explicit trust
store
• requireClientAuthentication: Whether client
authentication is required

tls-protocol-handler Configures the global Java protocol handler. It


has one attribute, property, which specifies the
java.protocol.handler.pkgs system property.

For example:

<https:connector name="httpConnector">
<https:tls-client path="clientKeystore" storePassword="mulepassword" />
<https:tls-key-store path="serverKeystore" keyPassword="mulepassword" storePassword="mulepassword"
/>
<https:tls-server path="trustStore" storePassword="mulepassword" />
</https:connector>
<https:endpoint name="clientEndpoint" host="localhost" port="60202" synchronous="true" connector-
ref="httpConnector" />

Polling Connector
The polling connector allows Mule to poll an external HTTP server and generate events from the
result. This is useful for pull-only web services. This connector provides a secure version of the
PollingHttpConnector. It includes all the properties of the HTTPS connector plus the following optional
attributes:

Attribute Description

pollingFrequency The time in milliseconds to wait between each


request to the remote http server.

checkEtag Whether the ETag header from the remote server


is processed if the header is present.

discardEmptyContent Whether Mule should discard any messages


from the remote server that have a zero content
length. For many services, a zero length would
mean there was no data to return. If the remote
HTTP server does return content to say that the
request is empty, users can configure a content
filter on the endpoint to filter these messages out.

For example:

<http:polling-connector name="PollingHttpConnector" pollingFrequency="2000" />

Document generated by Confluence on Oct 27, 2008 21:07 Page 81


HTTPS Endpoints
An inbound HTTPS endpoint exposes a service securely over HTTPS, essentially making it an HTTP server.
If polling of a remote HTTP service is required, this endpoint should be configured with a polling HTTPS
connector.

An outbound HTTPS endpoint allows Mule to send requests securely using SSL to external servers or Mule
inbound HTTP endpoints using HTTP over SSL protocol.

A global HTTPS endpoint can be referenced by services. Services can augment the configuration defined
in the global endpoint with local configuration elements.

For more information on configuring HTTP endpoints, see HTTP Transport.

Document generated by Confluence on Oct 27, 2008 21:07 Page 82


IMAP Transport

This page last changed on Oct 09, 2008 by jackie.wheeler.

IMAP Transport
The IMAP transport can be used for receiving messages from IMAP inboxes using the javax.mail API.
The IMAPS Transport uses secure connections over SSL/TLS. The IMAP transport uses the same filters
and transformers as the Email Transport.

The Javadoc for this provider can be found here .

IMAP Connector
The IMAP connector is identical to the Email connector.

Endpoints
IMAP and IMAPS endpoints include details about connecting to a IMAP mailbox. You configure the
endpoints just as you would with any other transport, with the following additional attributes:

• user: the user name of the mailbox owner


• password: the password of the user
• host: the IP address of the IMAP server, such as www.mulesource.com, localhost, or 127.0.0.1
• port: the port number of the IMAP server. When using the IMAPS connector, the default port is set to
993.

For example:

<imap:inbound-endpoint user="bob" password="password" host="localhost" port="65433"


checkFrequency="3000"/>

or for IMAPS:

<imaps:inbound-endpoint user="bob" password="password" host="localhost" port="65433"


checkFrequency="3000"/>

This will log into the bob mailbox on localhost on port 65433 using password password and will check
the mailbox for new messages every 30 seconds.

Escape Your Credentials

When including the user name and password in the endpoint, escape any characters
that are illegal for URIs, such as the @ character. For example, if the user name is
user@myco.com, you should enter it as user%40myco.com.

Document generated by Confluence on Oct 27, 2008 21:07 Page 83


IMAPS Transport

This page last changed on Sep 19, 2008 by jackie.wheeler.

IMAPS Transport
TLS/SSL connections are made on behalf of an entity, which can be anonymous or identified by a
certificate. The key store provides the certificates and associated private keys necessary for identifying
the entity making the connection. Additionally, connections are made to trusted systems. The public
certificates of trusted systems are stored in a trust store, which is used to verify that the connection
made to a remote system matches the expected identity.

The IMAPS connector enables IMAP over SSL using the javax.mail APIs. It supports all the elements and
attributes of the IMAP connector plus some required properties for setting up the client key store and the
trust store for the SSL connection.

Property Description

tls-client Configures the client key store with the following


attributes:

• path: The location (which will be resolved


relative to the current classpath and file
system, if possible) of the keystore that
contains public certificates and private keys
for identification
• storePassword: The password used to
protect the keystore
• class: The type of keystore used (a Java
class name)

tls-trust-store Configures the trust store. The attributes are:

• path: The location (which will be resolved


relative to the current classpath and file
system, if possible) of the trust store that
contains public certificates of trusted servers
• storePassword: The password used to
protect the trust store

For example:

<imaps:connector name="imapsConnector">
<imaps:tls-client path="clientKeystore" storePassword="mulepassword" />
<imaps:tls-trust-store path="greenmail-truststore" storePassword="password" />
</imaps:connector>
<model name="test">
<service name="relay">
<inbound>
<imaps:inbound-endpoint user="bob" password="password" host="localhost" port="65436" />
</inbound>
...

For information on configuring endpoints using the IMAPS connector, see IMAP Transport.

The IMAPS transport supports the same filters and transformers as the Email transport.

Document generated by Confluence on Oct 27, 2008 21:07 Page 84


JDBC Transport

This page last changed on Oct 21, 2008 by jackie.wheeler.

JDBC Transport
[ Introduction ] [ Features ] [ Transactions ] [ API Documentation and Notes ] [ Runnable Examples ] [
Performance Results ]

Introduction
The JDBC Transport allows you to send and receive messages with a database using the JDBC protocol.
Common usage includes retrieving, inserting, updating, and deleting database records, as well as
invoking stored procedures.

Some features are available only with the Mule Enterprise version of the JDBC transport, which is
available with version 1.6 and later of Mule Enterprise Edition. These EE-only features are noted below.

Features
The Mule Enterprise JDBC Transport provides key functionality, performance improvements, transformers,
and examples not available in the Mule Community edition. The following table summarizes the feature
differences.

Feature Summary Mule Community Mule Enterprise

Inbound SELECT Retrieve records x x


Queries using the SQL SELECT
statement configured
on inbound endpoints.

Large Dataset Retrieval Enables retrieval x


arbitrarily large
datasets by consuming
records in smaller
batches.

Acknowledgment Supports ACK SQL x x


Statements statements that update
the source or other
table after a record is
read.

Basic Insert/Update/ Individual SQL INSERT, x x


Delete Statements UPDATE, and DELETE
queries specified on
outbound endpoints.
One statement is
executed at a time.

Batch Insert/Update/ Support for JDBC batch x


Delete Statements INSERT, UPDATE, and
DELETE statements, so
that many statements
can be executed
together.

Advanced JDBC-related XML and CSV x


Transformers transformers for easily

Document generated by Confluence on Oct 27, 2008 21:07 Page 85


converting to and
from datasets in these
common formats.

Outbound SELECT Retrieve records using x


Queries SQL SELECT statement
configured on outbound
endpoints. Supports
synchronous queries
with dynamic runtime
parameters.

Stored Procedure Ability to invoke stored x x


Support - Basic procedures. Supports
IN parameters but not
OUT parameters.

Stored Procedure Same as Basic but x


Support - Advanced includes both IN
and OUT parameter
support. OUT
parameters can be
simple data types or
cursors

Unnamed Queries Queries that x x


can be invoked
programmatically
from within service
components or other
Java code. This is the
most flexible option,
but also requires
writing code.

Flexible Data Source Support for x x


Configuration configuration of data
sources through JNDI,
XAPool, or Spring.

Transactions Support for x x


transactions via
underlying Transaction
Manager.

Important Note on Namespaces

When using JDBC EE features, you will need to import the EE namespace for the JDBC transport (http://
www.mulesource.com/schema/mule/jdbc-ee/2.0). For example:

<mule
xmlns:jdbc="http://www.mulesource.com/schema/mule/jdbc/2.0"
xsi:schemaLocation="http://www.mulesource.com/schema/mule/jdbc/2.0 http://www.mulesource.com/
schema/mule/jdbc/2.0/mule-jdbc-ee.xsd">

If you are not using JDBC EE features, then you can stick with the normal CE namespace:

<mule
xmlns:jdbc="http://www.mulesource.org/schema/mule/jdbc/2.0"
xsi:schemaLocation="http://www.mulesource.org/schema/mule/jdbc/2.0 http://www.mulesource.org/
schema/mule/jdbc/2.0/mule-jdbc.xsd">

Document generated by Confluence on Oct 27, 2008 21:07 Page 86


Inbound SELECT Queries

Inbound SELECT queries are queries that are executed periodically (according to the pollingInterval
set on the connector).

Here is an example:

<spring:bean id="jdbcDataSource" class="org.enhydra.jdbc.standard.StandardDataSource" destroy-


method="shutdown">
<spring:property name="driverName" value="oracle.jdbc.driver.OracleDriver"/>
<spring:property name="url" value="jdbc:oracle:thin:user/pass@host:1521:db"/>
</spring:bean>
...
<jdbc:connector name="jdbcConnector" pollingFrequency="10000" dataSource-ref="jdbcDataSource">
<jdbc:query key="selectLoadedMules"
value="SELECT ID, MULE_NAME, RANCH, COLOR, WEIGHT, AGE from mule_source where ID between 0 and 20"/
>
</jdbc:connector>
...
<model name="ExampleModel">
<service name="InboundSelectExample">
<inbound>
<jdbc:inbound-endpoint queryKey="selectMules"/>
</inbound>
<outbound>
<outbound-pass-through-router>
<vm:outbound-endpoint path="out"/>
</outbound-pass-through-router>
</outbound>
</service>
</model>
...

In this example, the inboundSelectQuery would be invoked every 10 seconds (pollingFrequency=10000


ms). Each record from the result set is converted into a Map (consisting of column/value pairs), and this
payload is sent to the VM endpoint shown above.

Inbound SELECT queries are limited because (1) generally, they cannot be called synchronously
(unnamed queries are an exception), and (2) they do not support runtime parameters.

Large Dataset Retrieval

Overview

Large dataset retrieval is a strategy for retrieving large datasets by fetching records in smaller, more
manageable batches. Mule Enterprise Edition provides the key components and transformers needed to
implement a wide range of these strategies.

When To Use It

• When the dataset to be retrieved is large enough to overwhelm memory and connection resources.
• When preserving the order of messages is important.
• When resumable processing is desired (that is, retrieval of the dataset can pick up where it left off,
even after service interruption).
• When load balancing the data retrieval among clustered Mule nodes.

How It Works

Large dataset retrieval does not use conventional inbound SELECT queries to retrieve data. Instead, it
uses a Batch Manager component to compute ID ranges for the next batch of records to be retrieved. An
outbound SELECT query uses this range to actually fetch the records. The Batch Manager also controls

Document generated by Confluence on Oct 27, 2008 21:07 Page 87


batch processing flow to make sure that it does not process the next batch until the previous batch has
finished processing.

The following diagram depicts the typical flow:


!LargeDataset.jpg!
Detailed usage of the large dataset retrieval feature is shown in JDBC Example #4.

Important Limitations

Large dataset retrieval requires that:

1. The source data contains a unique, sequential numeric ID. Records should also be fetched in
ascending order with respect to this ID.
2. There are no large gaps in these IDs (no larger than the configured batch size).

In Combination with Batch Inserts

Combining large dataset retrieval with batch inserts can support simple but powerful ETL use cases. See
Example #4 and JDBC Transport Performance Benchmark Results for more details on how Mule can be
used to transport millions of records an hour from one database table to another.

Acknowledgment (ACK) Statements

ACK statements are optional SQL statements that are paired with inbound SELECT queries. When an
inbound SELECT query is invoked by Mule, the ACK statement is invoked for each record returned by
the query. Typically, the ACK statement is an UPDATE, INSERT, or DELETE.

Continuing the inbound SELECT query example above, the ACK statement would be configured as follows:

...
<jdbc:connector name="jdbcConnector" pollingFrequency="10000" dataSource-ref="jdbcDataSource">
<jdbc:query key="selectLoadedMules"
value="SELECT ID, MULE_NAME, RANCH, COLOR, WEIGHT, PROCESSED from mule_source where ID between 0
and 20"/>
<jdbc:query key="selectMules.ack"
value="update mule_source set PROCESSED='Y' where ID = #[map-payload:ID] "/>

</jdbc:connector>
...

Notice the convention of appending an ".ack" extension to the query name. This convention lets Mule
know which inbound SELECT query to pair with the ACK statement.

Also, note that the ACK statement supports parameters. These parameters are bound to any of the
column values from the inbound SELECT query (such as #[ID] in the case above).

ACK statements are useful when you want an inbound SELECT query to retrieve records from a source
table no more than once. Be careful, however, when using ACK statements with larger result sets. As
mentioned earlier, an ACK statement gets issued for each record retrieved, and this can be very resource-
intensive for even a modest number of records per second (> 100).

Basic Insert/Update/Delete Statements

SQL INSERT, UPDATE, and DELETE statements are specified on outbound endpoints. These statements
are typically configured with parameters, which are bound with values passed along to the outbound
endpoint from an upstream component.

Basic statements execute just one statement at a time, as opposed to batch statements, which execute
multiple statements at a time. Basic statements are appropriate for low-volume record processing
(<20 records per second), while batch statements are appropriate for high-volume record processing
(thousands of records per second).

For example, when a message with a java.util.Map payload is sent to a basic insert/update/delete
endpoint, the parameters in the statement are bound with corresponding entries in the Map. In the

Document generated by Confluence on Oct 27, 2008 21:07 Page 88


configuration below, if the message contains a Map payload with {ID=1,TYPE=1,DATA=hello,ACK=0}, the
following insert will be issued: "INSERT INTO TEST (ID,TYPE,DATA,ACK) values (1,1,'hello',0)".

<jdbc:connector name="jdbcConnector" pollingFrequency="10000" dataSource-ref="jdbcDataSource">


<jdbc:query key="outboundInsertStatement"
value="INSERT INTO TEST (ID, TYPE, DATA, ACK) VALUES (#[map-payload:ID],
#[map-payload:TYPE],#[map-payload:DATA], #[map-payload:ACK])"/>
</jdbc:connector>
...
<model name="ExampleModel">
<service name="outboundInsertExample">
<inbound>
<inbound-endpoint address="vm://doInsert"/>
</inbound>
<outbound>
<outbound-pass-through-router>
<jdbc:outbound-endpoint queryKey="outboundInsertStatement"/>
</outbound-pass-through-router>
</outbound>
</service>
</model>
...

See

Batch Insert/Update/Delete Statements

As mentioned above, batch statements represent a significant performance improvement over their
basic counterparts. Records can be inserted at a rate of thousands per second with this feature.

Usage of batch INSERT, UPDATE, and DELETE statements is the same as for basic statements, except the
payload sent to the VM endpoint should be a List of Maps, instead of just a single Map.

Examples #1 and #4 demonstrate this feature. Batch statements are available in Mule Enterprise Edition
only.

Batch Callable Statements are also supported. Usage is identical to Batch Insert/Update/Delete.

Advanced JDBC-related Transformers

Common integration use cases involve moving CSV and XML data from files to databases and back. This
section describes the transformers that perform these actions. These transformers are available in Mule
Enterprise Edition only.

XML-JDBC Transformer

The XML Transformer converts between XML and JDBC-format Maps. The JDBC-format Maps can be used
by JDBC outbound endpoints (for select, insert, update, or delete operations).

Transformer Details:

Name Class Input Output

XML -> Maps org.mule.providers.jdbc.transformers.XMLToMapsTransformer


java.lang.String (XML) java.util.List
(List of Maps. Each
Map corresponds to a
"record" in the XML.)

Maps -> XML org.mule.providers.jdbc.transformers.MapsToXMLTransformer


java.util.List java.lang.String (XML)

Document generated by Confluence on Oct 27, 2008 21:07 Page 89


(List of Maps. Each Map
will be converted into a
"record" in the XML)

Also, the XML message payload (passed in or out as a String) must adhere to a particular schema format:

<?xml version="1.0" encoding="UTF-8"?>


<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="table">
<xs:complexType>
<xs:sequence>
<xs:element ref="record"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="record">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" ref="field"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="field">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:NMTOKEN">
<xs:attribute name="name" use="required" type="xs:NCName"/>
<xs:attribute name="type" use="required" type="xs:NCName"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:schema>

Here is an example of a valid XML instance:

<table>
<record>
<field name="id" type="java.math.BigDecimal">0</field>
<field name="name" type="java.lang.String">hello</field>
</record>
</table>

The transformer converts each "record" element to a Map of column/value pairs using "fields". The
collection of Maps is returned in a List.

See Example #2, which uses the XML Transformer to convert results from a database query into an XML
document.

CSV-JDBC Transformer

The CSV Transformer converts between CSV data and JDBC-format Maps. The JDBC-format Maps can be
used by JDBC outbound endpoints (for select, insert, update, or delete operations).

Transformer Details:

Name Class Input Output

CSV -> Maps org.mule.providers.jdbc.transformers.CSVToMapsTransformer


java.lang.String java.util.List
(CSV data) (List of Maps. Each
Map corresponds to a
"record" in the CSV)

Maps -> CSV org.mule.providers.jdbc.transformers.MapsToCSVTransformer


java.util.List java.lang.String

Document generated by Confluence on Oct 27, 2008 21:07 Page 90


(List of Maps. Each Map (CSV data)
will be converted into a
"record" in the CSV)

The following table summarizes the properties that can be set on this transformer:

Property Description

delimiter The delimiter character used in the CSV file.


Defaults to comma.

qualifier The qualifier character used in the CSV file.


Used to signify if text contains the delimiter
character.Defaults to double quote.

ignoreFirstRecord Instructs transformer to ignore the first record.


Defaults to false.

mappingFile Location of Mapping file. Required. Can either


be physical file location or classpath resource
name. The DTD format of the Mapping File can
be found at: http://flatpack.sourceforge.net/
flatpack.dtd. For examples of this format, see
http://flatpack.sourceforge.net/documentation/
index.html.

For an example, see Example #1, which uses the CSV Transformer to load data from a CSV file to a
database table.

Outbound SELECT Queries

An inbound SELECT query is invoked on an inbound endpoint according to a specified polling interval. A
major improvement to the inbound SELECT query is the outbound SELECT query, which can be invoked
on an outbound endpoint. As a result, the outbound SELECT query can do many things that the inbound
SELECT query cannot, such as:

1. Support synchronous invocation of queries. For example, you can implement the classic use case of
a web page that serves content from a database using an HTTP inbound endpoint and an outbound
SELECT query endpoint.
2. Allows parameters so that values can be bound to the query at runtime. This requires that the
message contain a Map payload containing key names that match the parameter names. For
example, the following configuration could be used to retrieve an outbound SELECT query:

...
<jdbc:connector name="jdbcConnector" dataSource-ref="jdbcDataSource">
<jdbc:query key="selectMules"
value="select * from mule_source where ID between 0 and #[map-payload:ID]"/>
</jdbc:connector>
...
<model name="ExampleModel">
<service name="selectOutboundExample">
<inbound>
<inbound-endpoint address="vm://mapReceiver"/>
</inbound>
<outbound>
<outbound-pass-through-router>
<jdbc:outbound-endpoint queryKey="selectMules"/>
</outbound-pass-through-router>
</outbound>
</service>
</model>

Document generated by Confluence on Oct 27, 2008 21:07 Page 91


In this scenario, if a Map is sent to the vm://mapReceiver endpoint containing this key/value pair:

key=ID
value=3

The following query is executed:

SELECT * FROM mule_source WHERE ID between 0 and 3

See Examples #2 and #3 for further outbound SELECT query examples. Note that this feature is
available in Mule Enterprise Edition only.

Stored Procedure Support - Basic

Like any other query, stored procedure queries can be listed in the "queries" map. Following is an
example of how stored procedure queries could be defined:

<jdbc:connector name="jdbcConnector" pollingFrequency="10000" dataSource-ref="jdbcDataSource">


<jdbc:query key="storedProc" value="CALL addField()"/>
</jdbc:connector>

To denote that we are going to execute a stored procedure and not a simple SQL query, we must start off
the query by the text CALL followed by the name of the stored procedure.

Parameters to stored procedures can be forwarded by either passing static parameters in the
configuration or using the same syntax as for SQL queries. For example:

<jdbc:query key="storedProc1" value="CALL addFieldWithParams(24)"/>


<jdbc:query key="storedProc2" value="CALL addFieldWithParams(#[map-payload:value])"/>

...
<outbound-pass-through-router>
<jdbc:outbound-endpoint queryKey="storedProc1"/>
</outbound-pass-through-router>
...
<outbound-pass-through-router>
<jdbc:outbound-endpoint address="jdbc://storedProc2?value=25"/>
</outbound-pass-through-router>
...

Stored Procedure Support - Advanced

Mule Enterprise Edition provides advanced stored procedure support not available in Mule Community
Edition. This section describes the advanced support.

OUT Parameters

In Mule Enterprise, you can execute your stored procedures with out and inout scalar parameters. The
syntax for such parameters is:

<jdbc:query key="storedProc1" value="CALL myProc(#[a], #[b;int;inout], #[c;string;out])"/>

You must specify the type of each output parameter (OUT, INOUT) and its data type (int, string, etc.).
The result of such stored procedures is a map containing (out parameter name, value) entries.

See Example #3 for more examples.

Oracle Cursor Support

For Oracle databases only, an OUT parameter can return a cursor. The following example shows how this
works.

Document generated by Confluence on Oct 27, 2008 21:07 Page 92


If you want to handle the cursor as a java.sql.ResultSet, see the "cursorOutputAsResultSet" service
below, which uses the "MapLookup" transformer to return the ResultSet.

If you want to handle the cursor by fetching the java.sql.ResultSet to a collection of Map objects,
see the "cursorOutputAsMaps" service below, which uses both the "MapLookup" and "ResultSet2Maps"
transformers to achieve this result.

<jdbc:connector name="jdbcConnector" pollingFrequency="1000" cursorTypeConstant="-10"


dataSource-ref="jdbcDataSource">
<jdbc:query key="SingleCursor" value="call TEST_CURSOR(#[mules;resultSet;out])"/>
</jdbc:connector>

<custom-transformer class="org.mule.transformer.simple.MapLookup" name="MapLookup">


<spring:property name="key" value="mules"/>
</custom-transformer>

<jdbc:resultset-to-maps-transformer name="ResultSet2Maps"/>

<model name="SPModel">
<service name="cursorOutputAsMaps">
<inbound>
<vm:inbound-endpoint path="returns.maps" responseTransformer-refs="MapLookup ResultSet2Maps"/>
</inbound>
<outbound>
<outbound-pass-through-router>
<jdbc:outbound-endpoint queryKey="SingleCursor"/>
</outbound-pass-through-router>
</outbound>
</service>

<service name="cursorOutputAsResultSet">
<inbound>
<vm:inbound-endpoint path="returns.resultset" responseTransformer-refs="MapLookup"/>
</inbound>
<outbound>
<outbound-pass-through-router>
<jdbc:outbound-endpoint queryKey="SingleCursor"/>
</outbound-pass-through-router>
</outbound>
</service>
</model>

In the above example, note that it is also possible to call a function that returns a cursor ref. For
example, if TEST_CURSOR2() returns a cursor ref, the following statement could be used to get that
cursor as a ResultSet:

<jdbc:query key="SingleCursor" value="call #[mules;resultSet;out] := TEST_CURSOR2()"/>

Important note on transactions: When calling stored procedures or functions that return
cursors (ResultSet), it is recommended that you process the ResultSet within a transaction.

Unnamed Queries

SQL statements can also be executed without configuring queries in the Mule configuration file. For a
given endpoint, the query to execute can be specified as the address of the URI.

MuleMessage msg = eventContext.receiveEvent("jdbc://SELECT * FROM TEST", 0);

Flexible Data Source Configuration

You can use any JDBC data source library with the JDBC Connector. The "myDataSource" reference below
refers to a DataSource bean created in Spring:

<jdbc:connector name="jdbcConnector" pollingFrequency="10000" dataSource-ref="myDataSource">


...

Document generated by Confluence on Oct 27, 2008 21:07 Page 93


</jdbc:connector>

You can also create a JDBC connection pool so that you don't create a new connection to the database for
each message. You can easily create a pooled data source in Spring using xapool. The following example
shows how to create the Spring bean right in the Mule configuration file.

<spring:bean id="pooledDS" class="org.enhydra.jdbc.standard.StandardDataSource" destroy-


method="shutdown">
<spring:property name="driverName" value="oracle.jdbc.driver.OracleDriver"/>
<spring:property name="url" value="jdbc:oracle:thin:user/pass@host:1521:db"/>
</spring:bean>

If you need more control over the configuration of the pool, you can use the standard JDBC classes. For
example, you could create the following beans in the Spring configuration file (you could also create them
in the Mule configuration file by prefixing everything with the Spring namespace):

//create the data source that will establish the connection


<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@mydb:1521:orcl"/>
<property name="username" value="my_user"/>
<property name="password" value="xyz123"/>
</bean>

//create the pool


<bean id="pool" class="org.apache.commons.pool.impl.GenericObjectPool">
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
<property name="maxActive" value="256"/>
<property name="maxIdle" value="100"/>
<property name="whenExhaustedAction" value="2"/>
</bean>

//create a connection factory for the data source


<bean id="dsConnectionFactory" class="org.apache.commons.dbcp.DataSourceConnectionFactory">
<constructor-arg><ref bean="dataSource"/></constructor-arg>
</bean>

//create a poolable connection factory based on the above pool and connection factory
<bean id="poolableConnectionFactory" class="org.apache.commons.dbcp.PoolableConnectionFactory">
<constructor-arg index="0"><ref bean="dsConnectionFactory"/></constructor-arg>
<constructor-arg index="1"><ref bean="pool"/></constructor-arg>
<constructor-arg index="2"><null/></constructor-arg>
<constructor-arg index="3"><null/></constructor-arg>
<constructor-arg index="4"><value>false</value></constructor-arg>
<constructor-arg index="5"><value>true</value></constructor-arg>
</bean>

//create pooling data source based on the poolable connection factory and pool
<bean id="pooledDS" class="org.apache.commons.dbcp.PoolingDataSource" depends-
on="poolableConnectionFactory">
<constructor-arg><ref bean="pool"/></constructor-arg>
</bean>

You could then reference the pooledDS bean in your Mule configuration:

<jdbc:connector name="jdbcConnector" dataSource-ref="pooledDS"/>

To retrieve the data source from a JNDI repository, you would configure the connector as follows:

<spring:beans>
<jee:jndi-lookup id="myDataSource" jndi-name="yourJndiName" environment-ref="yourJndiEnv" />
<util:map id="jndiEnv">
<spring:entry key="java.naming.factory.initial" value="yourJndiFactory" />
</util:map>
</spring:beans>

Document generated by Confluence on Oct 27, 2008 21:07 Page 94


The above example shows how to create the Spring beans right in the Mule configuration file. This
approach would require the following namespaces:

<mule xmlns="http://www.mulesource.org/schema/mule/core/2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jdbc="http://www.mulesource.org/schema/mule/jdbc/2.0"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-2.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-
jee-2.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-
util-2.0.xsd
http://www.mulesource.org/schema/mule/core/2.0 http://www.mulesource.org/schema/mule/core/2.0/
mule.xsd
http://www.mulesource.org/schema/mule/jdbc/2.0 http://www.mulesource.org/schema/mule/jdbc/2.0/mule-
jdbc.xsd">

Transactions
Transactions are supported on JDBC Endpoints. See Transaction Management for details.

API Documentation and Notes

Connector Properties

Property Description Default Required

dataSource-ref Reference to the Yes


JDBC data source
to use. When using
XA transactions, an
XADataSource object
must be provided.

pollingFrequency The delay in No


milliseconds that will
be used during two
subsequent polls to the
database

resultSetHandler-ref Reference to org.apache.commons.dbutils.


No
ResultSetHandler used handlers.MapListHandler
to pass back query
results. For more
information about
this object, see the
examples.

queryRunner-ref Reference to the org.apache.commons.dbutils.


no
QueryRunner to use QueryRunner
when executing a
Query. For more
information about
this object, see the
examples.

Document generated by Confluence on Oct 27, 2008 21:07 Page 95


Notes on Configuring Queries

SQL queries are used by endpoints and should be configured on the connector using the "query" element:

<jdbc:query key="myQuery" value="select * from blah"/>

The queries can be parameterized using the #[...] pattern that follows the Expression Evaluation
Framework.

Runnable Examples
For examples of using the Mule Enterprise version of the JDBC transport, see JDBC Transport Examples.

Performance Results
For information on performance testing on the Mule Enterprise version of the JDBC transport, see JDBC
Transport Performance Benchmark Results.

Document generated by Confluence on Oct 27, 2008 21:07 Page 96


JDBC Transport Examples

This page last changed on Oct 14, 2008 by jackie.wheeler.

JDBC Transport Examples

Setup
The Mule Enterprise JDBC Examples are located in your installation at $MULE_HOME/examples/jdbc.

1. Before running any examples, do the following:

• Run the statements in scripts/tables.ddl to create tables in your favorite database.


• Edit the conf/db.properties file with your database connection configuration.
• Copy your database driver to your $MULE_HOME/lib/user directory.

2. Run the examples using the "jdbc.bat" or "jdbc" shell script provided in this directory. After running the
script, you will see the following:

$ ./jdbc.bat
Examples require that you set up your database first. See README for more details.
After your database is set up, choose one of the following examples to run:
1. Mules are born. Read in 50 baby mules from a CSV File and create records in mule_source table.
2. View Mules. Generate an XML report of Mules. (http://localhost:8080/first20)
3. Clone Mules. Clone mules using a Stored Procedure. (http://localhost:8080/clone)
4. Retire Mules. Send mules to a retirement ranch (a.k.a the mule_target table).
5. Cleanup Mules. Reset tables to run examples again (http://localhost:8080/cleanup).
Select the one you wish to execute and press Enter...

3. Choose the number of the Example you want to run.

The examples are designed to be run in order.

Example 1 - Mules Are Born


This example loads records from a CSV file to the database. The CSV file ("data/mules.csv") contains
information about 50 baby mules born at various local ranches. The goal is to upload these records into a
database table called "mule_source".

Configuration

See conf/jdbc-csv.xml

Features Used

This example uses the CSV Transformer to convert the CSV file into JDBC-format Maps and inserts these
records into the database using a batch INSERT.

Running the Example

To run the example, choose option "1" after starting the Mule server. When the server starts, Mule will
immediately load all the records.

To verify that the example loaded correctly, use your favorite database tool to see that there were 50
records inserted into the mule_source table.

SQL> select count(1) from mule_source;

COUNT(1)
----------

Document generated by Confluence on Oct 27, 2008 21:07 Page 97


50

If you want to run the example again, first delete the records from mule_source.

Example 2 - See the Baby Mules


This example displays the mule records loaded into the database in Example 1.

Configuration

See conf/jdbc-xml-report.xml

Features Used

This example uses an outbound SELECT query to synchronously query the database. The results are
transformed into XML using the XML transformer.

Running the Example

Start the Mule server and choose Example 2. Then, enter the URL http://localhost:8080/first20 into your
web browser. You should see the first 20 mule records presented in XML format.

Example 3 - Mule Cloning

The following example assumes that you are using an Oracle database. However, you can
adapt the stored procedure for other database platforms.

This example shows how to invoke a stored procedure in Mule. This particular stored procedure clones
the records in the mule_source database (doubling the size of the table each time it is run). The goal is to
create a large dataset that we can use in Example 4.

Configuration

See conf/jdbc-stored-procedure.xml

Features Used

This page uses an outbound SELECT query and stored procedure support to synchronously call a stored
procedure.

Running the Example

Before running this example, run the statements in the scripts/oracle_procs.ddl to create the stored
procedure and sequence.

Start the Mule server and choose Example 3. Then, enter the URL http://localhost:8080/clone into
your web browser. You should see the current count of the number of mules in mule_source. Each time
you refresh the page, the number of mules should double. Try refreshing several times until there are
thousands or even millions of mules or more in the table. The mules multiply quickly!

Example 4 - Mass Mule Retirement


This example retires all our mules by transferring them from one database table (mule_source) to
another (mule_target). We can think of this as a simple ETL use case.

Document generated by Confluence on Oct 27, 2008 21:07 Page 98


Configuration

See conf/jdbc-etl.xml

Features Used

This page uses large dataset retrieval, an outbound SELECT query, and batch INSERT statements to
transfer arbitrarily large numbers of records from one table another.

Running the Example

Before running this example, you can optionally change the location of the ID store in jdbc-etl.xml:

<spring:bean id="idStore" class="org.mule.transport.jdbc.util.IdStore">


<spring:property name="fileName" value="/tmp/eg-batches.txt"/>
</spring:bean>

The default location is /tmp/eg-batches.txt on Linux/Unix and c:/tmp/eg-batches.txt on Windows.

Next, for better visibility into batch activity, add the following line to your log4j.properties file (in
$MULE_HOME/conf):

log4j.logger.org.mule.providers.jdbc.components=DEBUG

Finally, start the server and choose Example 4. You should see the batches of records being processed in
the logs:

DEBUG 2008-04-10 20:20:03,625 \[next_batch.2\] org.mule.providers.jdbc.components.BatchManager:


Processing next batch
DEBUG 2008-04-10 20:20:03,625 \[next_batch.2\] org.mule.providers.jdbc.components.BatchManager:
Next range: {lowerId=1, upperId=3000}
DEBUG 2008-04-10 20:20:04,531 \[next_batch.2\] org.mule.providers.jdbc.components.BatchManager:
Processing next batch
DEBUG 2008-04-10 20:20:04,531 \[next_batch.2\] org.mule.providers.jdbc.components.BatchManager:
Next range: {lowerId=3001, upperId=6000}
DEBUG 2008-04-10 20:20:05,531 \[next_batch.2\] org.mule.providers.jdbc.components.BatchManager:
Processing next batch
DEBUG 2008-04-10 20:20:05,531 \[next_batch.2\] org.mule.providers.jdbc.components.BatchManager:
Next range: {lowerId=6001, upperId=9000}

In this example, batches are configured to occur every 1 second, with a batch size of 3000.

Note that if you stop and restart the Mule server, the batches should resume processing where they left
off.

Re-running the Examples


If you want to run these examples again, just delete all records from both mule_source and mule_target
tables, and remove the file "/tmp/eg-batches.txt". In Oracle, this may be most efficiently done by using
truncate, e.g. truncate table mule_source.

Alternatively, if on Oracle, start the server choose "Example 5" to cleanup the tables mule_source and
mule_target. You still need to manually remove the file "/tmp/eg-batches.txt".

Document generated by Confluence on Oct 27, 2008 21:07 Page 99


JDBC Transport Performance Benchmark Results

This page last changed on May 21, 2008 by jackie.wheeler.

JDBC Transport Performance Benchmark


Results
This page describes the performance benchmark results for the Mule Enterprise JDBC transport.

Configuration

Mule Enterprise 1.6 (default 512mb max heap size)

JDK 1.5.0.11

OS Red Hat Enterprise 4.0

Mule CPUs 4-CPU Dell

Database Oracle 10g (separate 4-CPU host)

Mule Configuration See Examples in $MULE_HOME/examples/jdbc.


Used "Simple ETL" use case for this benchmark

Scenario Details
The ETL use case from the Examples directory was used for this benchmark. This example retrieves
records from a table called mule_source and inserts them into a table called mule_target.

The scenario involves processing a backlog of 10 million records in the mule_source table. Records are
read from the source table once every 1 second, at a batch size of 3000 records per read and 3000
records per commit.

Results
Mule took 55 minutes to complete processing of the 10 million record backlog. Therefore, with this
configuration, the Mule Enterprise JDBC Transport could move over 10 million records an hour.

Comparison to Mule Community Edition

Document generated by Confluence on Oct 27, 2008 21:07 Page 100


Document generated by Confluence on Oct 27, 2008 21:07 Page 101
Jetty Transport

This page last changed on Sep 23, 2008 by jackie.wheeler.

Jetty Transport
[ Connector ] [ Endpoints ]

The Jetty transport provides support for exposing services over HTTP by embedding a light-weight Jetty
server. The Jetty SSL transport works the same way but over SSL. You can only define inbound endpoints
with this transport.

The Javadoc for this transport can be found here .

Connector
Allows Mule to expose Mule Services over HTTP using a Jetty HTTP server. A single Jetty server is created
for each connector instance. One connector can serve many endpoints. Users should rarely need to have
more than one Jetty connector. The Jetty connector can be configured using a Jetty XML config file, but
the default configuration is sufficient for most scenarios.

Attributes of <connector...>

Name Type Required Default Description

configFile string no The location of the


Jetty config file
to configure this
connector with.

useContinuations boolean no Whether to use


continuations
to free up
connections
in high load
situations.

For example:

<?xml version="1.0" encoding="UTF-8" ?>


<mule xmlns="http://www.mulesource.org/schema/mule/core/2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jetty="http://www.mulesource.org/schema/mule/jetty/2.0" xsi:schemaLocation="http://
www.mulesource.org/schema/mule/jetty/2.0
http://www.mulesource.org/schema/mule/jetty/2.0/mule-jetty.xsd http://www.mulesource.org/schema/
mule/core/2.0
http://www.mulesource.org/schema/mule/core/2.0/mule.xsd">
<jetty:connector name="httpConnector" useContinuations="true" />
...

Endpoints
Jetty endpoints are configured the same way as HTTP endpoints. Note that only inbound endpoints can
use the Jetty transport.

For example:

<jetty:endpoint name="serverEndpoint" host="localhost" port="60203" path="services/Foo"


synchronous="false" />

Document generated by Confluence on Oct 27, 2008 21:07 Page 102


<model name="main">
<service name="testComponent">
<inbound>
<inbound-endpoint ref="serverEndpoint" />
</inbound>
<test:component appendString="Received" />
</service>
</model>

Document generated by Confluence on Oct 27, 2008 21:07 Page 103


Jetty SSL transport

This page last changed on Sep 23, 2008 by jackie.wheeler.

Jetty SSL Transport


The Jetty SSL transport works exactly the same way as the HTTPS Transport with one additional optional
attribute, configFile, which allows you to specify the location of the Jetty config file to configure this
connector with.

For example, the following configuration specifies the HTTPS and Jetty-SSL connectors:

<?xml version="1.0" encoding="UTF-8" ?>


<mule xmlns="http://www.mulesource.org/schema/mule/core/2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:https="http://www.mulesource.org/schema/mule/https/2.0"
xmlns:jetty="http://www.mulesource.org/schema/mule/jetty-ssl/2.0"
xmlns:test="http://www.mulesource.org/schema/mule/test/2.0"
xsi:schemaLocation="http://www.mulesource.org/schema/mule/test/2.0
http://www.mulesource.org/schema/mule/test/2.0/mule-test.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.mulesource.org/schema/mule/core/2.0
http://www.mulesource.org/schema/mule/core/2.0/mule.xsd
http://www.mulesource.org/schema/mule/https/2.0
http://www.mulesource.org/schema/mule/https/2.0/mule-https.xsd
http://www.mulesource.org/schema/mule/jetty-ssl/2.0
http://www.mulesource.org/schema/mule/jetty-ssl/2.0/mule-jetty-ssl.xsd">
<https:connector name="httpConnector">
<https:tls-client path="clientKeystore" storePassword="mulepassword" />
<https:tls-key-store path="serverKeystore" keyPassword="mulepassword" storePassword="mulepassword"
/>
<https:tls-server path="trustStore" storePassword="mulepassword" />
</https:connector>
<jetty:connector name="jettyConnector">
<jetty:tls-client path="clientKeystore" storePassword="mulepassword" />
<jetty:tls-key-store path="serverKeystore" keyPassword="mulepassword" storePassword="mulepassword"
/>
<jetty:tls-server path="trustStore" storePassword="mulepassword" />
</jetty:connector>
<https:endpoint name="clientEndpoint" host="localhost" port="60202" synchronous="true" connector-
ref="httpConnector" />
<model name="main">
<custom-service name="testComponent" class="org.mule.tck.testmodels.mule.TestSedaService">
<inbound>
<jetty:inbound-endpoint host="localhost" port="60202" synchronous="true" connector-
ref="jettyConnector" />
</inbound>
<test:component appendString="Received" />
</custom-service>
</model>
</mule>

If you do not need this level of security, you can use the Jetty transport instead.

Document generated by Confluence on Oct 27, 2008 21:07 Page 104


JMS Transport

This page last changed on Oct 16, 2008 by jackie.wheeler.

JMS Transport
Table of Contents

Click here to expand...

• JMS Transport
• ° Using Topics, Queues, or Both
° Specifying Credentials
° Specifying Additional Information
° JMS Selectors
° Durable Subscribers
° Overloading JMS Behavior
° Looking Up JMS Objects from JNDI
° JMS Transformers
° JMS Header Properties
° Schema Reference
° Connector
° - Attributes of <connector...>
° Custom Connector
° - Attributes of <custom-connector...>
° Activemq Connector
° - Attributes of <activemq-connector...>
° Activemq Xa Connector
° - Attributes of <activemq-xa-connector...>
° Weblogic Connector
° - Attributes of <weblogic-connector...>
° Websphere Connector
° - Attributes of <websphere-connector...>
° Transaction
° Client Ack Transaction
° Jmsmessage To Object Transformer
° Object To Jmsmessage Transformer
° Inbound Endpoint
° - Attributes of <inbound-endpoint...>
° Outbound Endpoint
° - Attributes of <outbound-endpoint...>
° Endpoint
° - Attributes of <endpoint...>
° Property Filter
° - Attributes of <property-filter...>

This page describes the JMS transport, which provides a standard JMS 1.0.2b and 1.1 connector. This
connector exposes all features defined in the 1.0.2b/1.1 specification. For information on configuring
various types of JMS, such as ActiveMQ, see Configuring JMS. If you are using Oracle AQ, you can use
the JMS transport without any special configuration if you are using Oracle 10 or later. For details, see the
example on the Mule Cookbook.

For more information on JMS, see Using JMS with Mule.

The Javadoc for the JMS transport can be found here .

Using Topics, Queues, or Both


When specifying a destination name in a URI, and JNDI destinations are not being used, the default
destination created is a queue. For example, the following JMS endpoint will manifest itself as a JMS
queue called my.destination.

Document generated by Confluence on Oct 27, 2008 21:07 Page 105


jms://my.destination

To make this destination a topic instead of a queue, you must prepend the destination name with
topic: in the URI. In transport-specific endpoints, you set the topic and queue attributes explicitly. For
example:

jms://topic:my.destination

or

<jms:inbound-endpoint topic="my.destination"/>
<jms:outbound-endpoint queue="my.destination"/>

If you are using a JMS 1.1 compliant server, you can use the same JMS connector for both queues
and topics. If you are using a JMS 1.0.2b server, and you want to use both queues and topics in your
Mule configuration, you must create two JMS connectors: one with a JNDI connection factory that
references a QueueConnectionFactory, and another that references a TopicConnectionfactory. Each
JMS endpoint must reference the correct connector depending on whether the destination is a topic or a
queue. To specify the connector on a JMS endpoint, you add the connector parameter to the URI or the
connector-ref attribute on a transport-specific endpoint:

jms://my.destination?connector=jmsQueueConnector
jms://topic:my.destination?connector=jmsTopicConnector

or

<jms:outbound-endpoint queue="my.destination" connector-ref="jmsQueueConnector"/>


<jms:inbound-endpoint topic="my.destination" connector-ref="jmsTopicConnector"/>

Specifying Credentials
Client connections might require a username and password when creating a connection. This information
can be specified on the URI or transport-specific endpoint as follows:

jms://ross:secret@topic:my.destination

or

<jms:inbound-endpoint topic="my.destination" username="ross" password="secret"/>

Specifying Additional Information


When creating JMS connectors, more information is needed such as ConnectionFactory JNDI details.
This information can be set as parameters on the URI, but this can get difficult to manage and read.
The recommend approach is to set default properties on the connector as described in Looking Up JMS
Objects from JNDI below.

JMS Selectors
You can set a JMS selector as a filter on an endpoint. The JMS selector simply sets the filter expression on
the consumer.

<jms:endpoint queue="important.queue" connector-ref="...">


<jms:selector expression="JMSPriority=9"/>
</jms:endpoint>

Durable Subscribers
You can use durable subscribers by setting the durable attribute on the JMS connector. This attribute
tells the connector to make all topic subscribers durable (it does not apply to queues). You can override
the connector's durable attribute at the endpoint level. For example, you can set durable to false on the
connector and set it to true just on the endpoints that require it.

Document generated by Confluence on Oct 27, 2008 21:07 Page 106


<jms:connector name="jmsTopicConnector" durable="false"/>
...
<jms:inbound-endpoint topic=durable.topic" connector-ref="jmsTopicConnector">
<property key="durable" value="true"/>
</endpoint>

When using a durable subscription, the JMS server requires a durable name to identify this subscriber. By
default, Mule generates the durable name in the following format:

mule.<connector name>.<topic name>

If you want to set the durable name yourself, you can set the durableName property on the endpoint.

<jms:inbound-endpoint topic="durable.topic" connector-ref="jmsTopicConnector">


<property key="durable" value="true"/>
<property key="durableName" value="myDurableSubscription"/>
</jms:inbound-endpoint>

The URI equivalent would be:

jms://topic:durable.topic?durableName=myDurableSubscription

Overloading JMS Behavior


Some JMS servers require a different sequence of calls when creating JMS resources. For example,
Oracle's Advanced Queuingrequires that the connection is started before listeners can be registered.
In this scenario the user can overload the JmsSupport class to customize the way JMS resources are
initialized. Configuring this customization requires that you tell the JMS connector to use a custom
JmsSupport class.

<spring:bean id="customJmsSupport" class="org.foo.jms.CustomJmsSupport"/>

<jms:connector name="jmsConnector">
<property key="jmsSupport" ref="customJmsSupport"/>
</jms:connector>

For more information about configuring different JMS servers, see Configuring JMS.

Looking Up JMS Objects from JNDI


Mule can be configured to look up connection factories, queues, and topics from JNDI. Use the following
connector attributes to configure your JNDI connection:

Connector Attribute Description

jndiInitialFactory Class name of the InitialContextFactory

jndiProviderUrl URL for the JNDI connection

jndiProviderProperties-ref Reference to a Spring map with additional


properties that will be passed on when creating
the InitialContext

connectionFactoryJndiName JNDI lookup name of the connection factory

jndiDestinations Set this flag to true to look up queues or


topics from JNDI. If a queue cannot be found
on JNDI, it well be created using the existing
JMS session (you can prevent this by using the
forceJndiDestinations attribute). The default is
false.

Document generated by Confluence on Oct 27, 2008 21:07 Page 107


forceJndiDestinations Set this connector property to false if you want
Mule to fail if a queue or topic could not be looked
up in JNDI. The default is false.

Note that JNDI configuration on the connector takes precedence over a Spring-configured connection
factory.

Configuration example:

<jms:connector name="jmsJndiConnector"
jndiInitialFactory="com.sun.jndi.ldap.LdapCtxFactory"
jndiProviderUrl="ldap://localhost:10389/"
connectionFactoryJndiName="cn=ConnectionFactory,dc=example,dc=com"
jndiDestinations="true"
forceJndiDestinations="true"/>

JMS Transformers
Transformers for the JMS provider can be found at org.mule.transport.jms.transformers .

Transformer Description

AbstractJmsTransformer This is a base class that provides general JMS


message transformation support. You can
extend this class to create your own specialized
JMS transformers, but usually the defaults are
sufficient.

JMSMessageToObject Converts a javax.jms.Message or sub-type into


an object by extracting the message payload.
Users of this transformer can set different return
types on the transformer to control the way it
behaves:
javax.jms.TextMessage - java.lang.String
javax.jms.ObjectMessage - java.lang.Object
javax.jms.BytesMessage - Byte[]. Note that
the transformer will check if the payload is
compressed and automatically decompress the
message.
javax.jms.MapMessage - java.util.Map
javax.jms.StreamMessage - java.util.Vector of
objects from the Stream Message.

ObjectToJMSMessage Converts any object to a javax.jms.Message


or sub-type. One of the following types of JMS
messages will be created based on the type of
object passed in:
java.lang.String - javax.jms.TextMessage
byte[] - javax.jms.BytesMessage
java.util.Map - javax.jms.MapMessage
java.io.InputStream - javax.jms.StreamMessage
javalang.Object - javax.jms.ObjectMessage

JMS Header Properties


When the message is received and transformed, all the message properties are still available via the
MuleMessage object. To access standard JMS properties such as JMSCorrelationID and JMSRedelivered,
simply use the property name, as shown in the following example:

String corrId = (String) muleMessage.getProperty("JMSCorrelationID");

Document generated by Confluence on Oct 27, 2008 21:07 Page 108


boolean redelivered = muleMessage.getBooleanProperty("JMSRedelivered");

You can access any custom header properties on the message in the same way.

Schema Reference

Connector
A generic connector for sending and receiving messages over JMS queues.

Attributes of <connector...>

Name Type Required Default Description

connectionFactory- name (no spaces) no


ref

redeliveryHandlerFactory-
name (no spaces) no
ref

acknowledgementMode
AUTO_ACKNOWLEDGE/
no AUTO_ACKNOWLEDGE
CLIENT_ACKNOWLEDGE/
DUPS_OK_ACKNOWLEDGE

clientId string no

durable boolean no

noLocal boolean no

persistentDelivery boolean no

honorQosHeaders boolean no

maxRedelivery integer no

cacheJmsSessions boolean no

recoverJmsConnections
boolean no Deprecated. This
attribute is no
longer relevant
for the new retry
policies. See
MULE-3812

eagerConsumer boolean no

specification 1.0.2b/1.1 no 1.0.2b

username string no

password string no

numberOfConsumersinteger no Configures
the number
of concurrent
consumers that
will be used
to receive JMS
messages.

Document generated by Confluence on Oct 27, 2008 21:07 Page 109


(Note: If you
use this attribute
you should not
configure the
'numberOfConcurrentTransacted
which has the
same effect.)

jndiInitialFactory string no Configures the


initial factory
class to use when
connecting to
JNDI.

jndiProviderUrl string no Configures the


URL to use when
connecting to
JNDI.

jndiProviderProperties-
string no Configures a
ref reference to a
Map that contains
additional provider
properties.

connectionFactoryJndiName
string no Configures the
name to use when
looking up the
connection factory
from JNDI.

jndiDestinations boolean no Set this to true


if you want to
lookup queues or
topics from JNDI
instead of creating
them from the
session.

forceJndiDestinationsboolean no If this is set to


true, Mule to fails
when a topic or
queue cannot be
retrieved from
JNDI. If this is set
to false, Mule will
create a topic or
queue from the
JMS session if the
JNDI lookup fails.

Custom Connector

Attributes of <custom-connector...>

Name Type Required Default Description

redeliveryHandlerFactory-
name (no spaces) no
ref

Document generated by Confluence on Oct 27, 2008 21:07 Page 110


acknowledgementMode
AUTO_ACKNOWLEDGE/
no AUTO_ACKNOWLEDGE
CLIENT_ACKNOWLEDGE/
DUPS_OK_ACKNOWLEDGE

clientId string no

durable boolean no

noLocal boolean no

persistentDelivery boolean no

honorQosHeaders boolean no

maxRedelivery integer no

cacheJmsSessions boolean no

recoverJmsConnections
boolean no Deprecated. This
attribute is no
longer relevant
for the new retry
policies. See
MULE-3812

eagerConsumer boolean no

specification 1.0.2b/1.1 no 1.0.2b

username string no

password string no

numberOfConsumersinteger no Configures
the number
of concurrent
consumers that
will be used
to receive JMS
messages.
(Note: If you
use this attribute
you should not
configure the
'numberOfConcurrentTransacted
which has the
same effect.)

jndiInitialFactory string no Configures the


initial factory
class to use when
connecting to
JNDI.

jndiProviderUrl string no Configures the


URL to use when
connecting to
JNDI.

jndiProviderProperties-
string no Configures a
ref reference to a
Map that contains

Document generated by Confluence on Oct 27, 2008 21:07 Page 111


additional provider
properties.

connectionFactoryJndiName
string no Configures the
name to use when
looking up the
connection factory
from JNDI.

jndiDestinations boolean no Set this to true


if you want to
lookup queues or
topics from JNDI
instead of creating
them from the
session.

forceJndiDestinationsboolean no If this is set to


true, Mule to fails
when a topic or
queue cannot be
retrieved from
JNDI. If this is set
to false, Mule will
create a topic or
queue from the
JMS session if the
JNDI lookup fails.

Activemq Connector

Attributes of <activemq-connector...>

Name Type Required Default Description

connectionFactory- name (no spaces) no


ref

redeliveryHandlerFactory-
name (no spaces) no
ref

acknowledgementMode
AUTO_ACKNOWLEDGE/
no AUTO_ACKNOWLEDGE
CLIENT_ACKNOWLEDGE/
DUPS_OK_ACKNOWLEDGE

clientId string no

durable boolean no

noLocal boolean no

persistentDelivery boolean no

honorQosHeaders boolean no

maxRedelivery integer no

cacheJmsSessions boolean no

recoverJmsConnections
boolean no Deprecated. This
attribute is no

Document generated by Confluence on Oct 27, 2008 21:07 Page 112


longer relevant
for the new retry
policies. See
MULE-3812

eagerConsumer boolean no

specification 1.0.2b/1.1 no 1.0.2b

username string no

password string no

numberOfConsumersinteger no Configures
the number
of concurrent
consumers that
will be used
to receive JMS
messages.
(Note: If you
use this attribute
you should not
configure the
'numberOfConcurrentTransacted
which has the
same effect.)

jndiInitialFactory string no Configures the


initial factory
class to use when
connecting to
JNDI.

jndiProviderUrl string no Configures the


URL to use when
connecting to
JNDI.

jndiProviderProperties-
string no Configures a
ref reference to a
Map that contains
additional provider
properties.

connectionFactoryJndiName
string no Configures the
name to use when
looking up the
connection factory
from JNDI.

jndiDestinations boolean no Set this to true


if you want to
lookup queues or
topics from JNDI
instead of creating
them from the
session.

forceJndiDestinationsboolean no If this is set to


true, Mule to fails
when a topic or
queue cannot be
retrieved from

Document generated by Confluence on Oct 27, 2008 21:07 Page 113


JNDI. If this is set
to false, Mule will
create a topic or
queue from the
JMS session if the
JNDI lookup fails.

brokerURL string no

Activemq Xa Connector

Attributes of <activemq-xa-connector...>

Name Type Required Default Description

connectionFactory- name (no spaces) no


ref

redeliveryHandlerFactory-
name (no spaces) no
ref

acknowledgementMode
AUTO_ACKNOWLEDGE/
no AUTO_ACKNOWLEDGE
CLIENT_ACKNOWLEDGE/
DUPS_OK_ACKNOWLEDGE

clientId string no

durable boolean no

noLocal boolean no

persistentDelivery boolean no

honorQosHeaders boolean no

maxRedelivery integer no

cacheJmsSessions boolean no

recoverJmsConnections
boolean no Deprecated. This
attribute is no
longer relevant
for the new retry
policies. See
MULE-3812

eagerConsumer boolean no

specification 1.0.2b/1.1 no 1.0.2b

username string no

password string no

numberOfConsumersinteger no Configures
the number
of concurrent
consumers that
will be used
to receive JMS
messages.

Document generated by Confluence on Oct 27, 2008 21:07 Page 114


(Note: If you
use this attribute
you should not
configure the
'numberOfConcurrentTransacted
which has the
same effect.)

jndiInitialFactory string no Configures the


initial factory
class to use when
connecting to
JNDI.

jndiProviderUrl string no Configures the


URL to use when
connecting to
JNDI.

jndiProviderProperties-
string no Configures a
ref reference to a
Map that contains
additional provider
properties.

connectionFactoryJndiName
string no Configures the
name to use when
looking up the
connection factory
from JNDI.

jndiDestinations boolean no Set this to true


if you want to
lookup queues or
topics from JNDI
instead of creating
them from the
session.

forceJndiDestinationsboolean no If this is set to


true, Mule to fails
when a topic or
queue cannot be
retrieved from
JNDI. If this is set
to false, Mule will
create a topic or
queue from the
JMS session if the
JNDI lookup fails.

brokerURL string no

Weblogic Connector

Attributes of <weblogic-connector...>

Name Type Required Default Description

connectionFactory- name (no spaces) no


ref

Document generated by Confluence on Oct 27, 2008 21:07 Page 115


redeliveryHandlerFactory-
name (no spaces) no
ref

acknowledgementMode
AUTO_ACKNOWLEDGE/
no AUTO_ACKNOWLEDGE
CLIENT_ACKNOWLEDGE/
DUPS_OK_ACKNOWLEDGE

clientId string no

durable boolean no

noLocal boolean no

persistentDelivery boolean no

honorQosHeaders boolean no

maxRedelivery integer no

cacheJmsSessions boolean no

recoverJmsConnections
boolean no Deprecated. This
attribute is no
longer relevant
for the new retry
policies. See
MULE-3812

eagerConsumer boolean no

specification 1.0.2b/1.1 no 1.0.2b

username string no

password string no

numberOfConsumersinteger no Configures
the number
of concurrent
consumers that
will be used
to receive JMS
messages.
(Note: If you
use this attribute
you should not
configure the
'numberOfConcurrentTransacted
which has the
same effect.)

jndiInitialFactory string no Configures the


initial factory
class to use when
connecting to
JNDI.

jndiProviderUrl string no Configures the


URL to use when
connecting to
JNDI.

Document generated by Confluence on Oct 27, 2008 21:07 Page 116


jndiProviderProperties-
string no Configures a
ref reference to a
Map that contains
additional provider
properties.

connectionFactoryJndiName
string no Configures the
name to use when
looking up the
connection factory
from JNDI.

jndiDestinations boolean no Set this to true


if you want to
lookup queues or
topics from JNDI
instead of creating
them from the
session.

forceJndiDestinationsboolean no If this is set to


true, Mule to fails
when a topic or
queue cannot be
retrieved from
JNDI. If this is set
to false, Mule will
create a topic or
queue from the
JMS session if the
JNDI lookup fails.

Websphere Connector

Attributes of <websphere-connector...>

Name Type Required Default Description

connectionFactory- name (no spaces) no


ref

redeliveryHandlerFactory-
name (no spaces) no
ref

acknowledgementMode
AUTO_ACKNOWLEDGE/
no AUTO_ACKNOWLEDGE
CLIENT_ACKNOWLEDGE/
DUPS_OK_ACKNOWLEDGE

clientId string no

durable boolean no

noLocal boolean no

persistentDelivery boolean no

honorQosHeaders boolean no

maxRedelivery integer no

Document generated by Confluence on Oct 27, 2008 21:07 Page 117


cacheJmsSessions boolean no

recoverJmsConnections
boolean no Deprecated. This
attribute is no
longer relevant
for the new retry
policies. See
MULE-3812

eagerConsumer boolean no

specification 1.0.2b/1.1 no 1.0.2b

username string no

password string no

numberOfConsumersinteger no Configures
the number
of concurrent
consumers that
will be used
to receive JMS
messages.
(Note: If you
use this attribute
you should not
configure the
'numberOfConcurrentTransacted
which has the
same effect.)

jndiInitialFactory string no Configures the


initial factory
class to use when
connecting to
JNDI.

jndiProviderUrl string no Configures the


URL to use when
connecting to
JNDI.

jndiProviderProperties-
string no Configures a
ref reference to a
Map that contains
additional provider
properties.

connectionFactoryJndiName
string no Configures the
name to use when
looking up the
connection factory
from JNDI.

jndiDestinations boolean no Set this to true


if you want to
lookup queues or
topics from JNDI
instead of creating
them from the
session.

Document generated by Confluence on Oct 27, 2008 21:07 Page 118


forceJndiDestinationsboolean no If this is set to
true, Mule to fails
when a topic or
queue cannot be
retrieved from
JNDI. If this is set
to false, Mule will
create a topic or
queue from the
JMS session if the
JNDI lookup fails.

Transaction

Client Ack Transaction

Jmsmessage To Object Transformer

Object To Jmsmessage Transformer

Inbound Endpoint

Attributes of <inbound-endpoint...>

Name Type Required Default Description

queue string no The queue name.


This cannot be
used with the
topic attribute
(the two are
exclusive).

topic string no The topic name.


The "topic:" prefix
will be added
automatically. This
cannot be used
with the queue
attribute (the two
are exclusive).

Outbound Endpoint

Attributes of <outbound-endpoint...>

Name Type Required Default Description

queue string no The queue name.


This cannot be
used with the
topic attribute

Document generated by Confluence on Oct 27, 2008 21:07 Page 119


(the two are
exclusive).

topic string no The topic name.


The "topic:" prefix
will be added
automatically. This
cannot be used
with the queue
attribute (the two
are exclusive).

Endpoint

Attributes of <endpoint...>

Name Type Required Default Description

queue string no The queue name.


This cannot be
used with the
topic attribute
(the two are
exclusive).

topic string no The topic name.


The "topic:" prefix
will be added
automatically. This
cannot be used
with the queue
attribute (the two
are exclusive).

Property Filter

Attributes of <property-filter...>

Name Type Required Default Description

propertyName string no

propertyClass string no

expression string no

pattern string no

Document generated by Confluence on Oct 27, 2008 21:07 Page 120


Mule WMQ Transport

This page last changed on Oct 21, 2008 by jackie.wheeler.

Mule WMQ
Transport
[ Messaging Use Cases ] [ Sending Messages on a Local Queue ] [ Sending Messages on a Remote Queue
] [ Inbound Message Handling ] [ Outbound Message Handling ] [ Retrieving the Connection Factory from
JNDI ] [ Known Limitations ]

The Mule Enterprise transport for IBM® WebSphere® MQ (Mule WMQ transport) provides the following
functionality:

• Bi-directional request-response messaging between Websphere MQ and Mule JMS using native MQ
point-to-point.
• Synchronous and asynchronous request-response communications using JMSReplyTo.

This page describes how to configure and use this transport and its connector. It assumes that you
already understand how to configure and use WebSphere MQ. For complete information on MQ, refer to
the MQ Information Center.

Note that the Mule WMQ transport is available only with Mule Enterprise Edition version 1.6 or later. For
information on connecting to WebSphere MQ using the JMS transport, which does not support native MQ
but does provide more functionality and is available with the community edition of Mule, see WebSphere
MQ Integration.

Messaging Use Cases


This section describes the typical use cases for using the Mule WMQ transport.

Sending Messages on a Local Queue

The configuration describes a flow where a service mqSender takes input interactively from the
command line and sends it to a native WebSphere MQ endpoint (mqs://REQUEST.QUEUE). Another
service, mqReceiver, picks up the message from this endpoint and echoes it back to another native
WebSphere MQ endpoint, mqs://RESPONSE.QUEUE.

Configuring request-response behavior requires the following settings:

• The JMSReplyTo property must be set on the outbound side of the mqSender.
• The message type (JMS_IBM_MsgType) property must be set to
com.ibm.mq.MQC.MQMT_REQUEST on the outbound side of the mqSender service.
• The message type (JMS_IBM_MsgType) property must be set to
com.ibm.mq.MQC.MQMT_REPLY on the inbound side of the mqReceiverservice.
• To support local queues, the transportType property in the MQJMSConnector declaration must be
set to JMSC.MQJMS_TP_BINDINGS_MQ.

By default, messages sent from Mule to MQ are sent in native format, and JMS (RFH2) headers are
suppressed. This configuration is applied transparently to the configuration below by the connector
appending a parameter to the MQ destination URI (?targetClient=1). To force JMS behaviour
on the receiving MQ (that is, to use non-native format), use the following attribute setting in the
MQJMSConnector declaration:

<mqs:connector name="..."
...
targetClient="JMSC.MQJMS_CLIENT_JMS_COMPLIANT"
...
/>

Document generated by Confluence on Oct 27, 2008 21:07 Page 121


Note the following additional points about the configuration:

• The mqs URI scheme for endpoints indicates that the MQ transport should be used.
• The queueManager property in the MQJMSConnector declaration matches the MQ QueueManager
set up previously.
• The local queues REQUEST.QUEUE and RESPONSE.QUEUE were set up previously using the
runmqsc utility.

<?xml version="1.0" encoding="UTF-8"?>


<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:stdio="http://www.mulesource.org/schema/mule/stdio/2.2"
xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.2"
xmlns:mqs="http://www.mulesource.com/schema/mule/mqseries/2.2"

xsi:schemaLocation="
http://www.mulesource.com/schema/mule/mqseries/2.2 http://www.mulesource.com/schema/mule/
mqseries/2.2/mule-mqseries-ee.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-2.0.xsd
http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/
mule.xsd
http://www.mulesource.org/schema/mule/stdio/2.2 http://www.mulesource.org/schema/mule/
stdio/2.2/mule-stdio.xsd
http://www.mulesource.org/schema/mule/vm/2.2 http://www.mulesource.org/schema/mule/vm/2.2/mule-
vm.xsd">

<spring:bean name="connectionFactory" class="com.ibm.mq.jms.MQConnectionFactory"/>

<mqs:connector name="mqSeriesConnector"
hostName="winter"
port="1414"
queueManager="HELLO.QMGR"
transportType="JMSC.MQJMS_TP_BINDINGS_MQ"
targetClient="JMSC.MQJMS_CLIENT_NONJMS_MQ"
specification="1.1"
username=""
password=""
disableReplyToHandler="true"
connectionFactory-ref="connectionFactory">
</mqs:connector>

<stdio:connector name="stdioConnector" messageDelayTime="1000" promptMessage="Please enter


something: "/>

<model name="MQ_Series_Example">
<service name="mqSender">
<inbound>
<stdio:inbound-endpoint system="IN"/>
</inbound>
<echo-component/>
<outbound>
<pass-through-router>
<outbound-endpoint address="mqs://REQUEST.QUEUE">
<property key="JMSReplyTo" value="RESPONSE.QUEUE"/>
<property key="JMS_IBM_MsgType" value="1"/> <!-- com.ibm.mq.MQC.MQMT_REQUEST -->
</outbound-endpoint>
</pass-through-router>
</outbound>
</service>

<service name="mqReceiver">
<inbound>
<inbound-endpoint address="mqs://REQUEST.QUEUE">
<property name="JMS_IBM_MsgType" value="2"/> <!-- com.ibm.mq.MQC.MQMT_REPLY -->

Document generated by Confluence on Oct 27, 2008 21:07 Page 122


</endpoint>
</inbound>
<echo-component/>
</service>
</model>
</mule>

The following log output demonstrates the message flow:

INFO 2008-04-10 13:59:21,472 [WrapperListener_start_runner] org.mule.MuleServer: Mule Server


initialized.

Please enter something:


Hello
INFO 2008-04-10 13:59:56,450 [mqSender.2] org.mule.components.simple.LogComponent:
********************************************************************************
* Message received in component: mqSender. Content is: 'Hello' *
********************************************************************************
INFO 2008-04-10 13:59:56,464 [MQJMSConnector.dispatcher.1]
org.mule.providers.mqseries.MQSeriesMessageDispatcher: Connected:
MQSeriesMessageDispatcher{this=504ec1, endpoint=mqs://REQUEST.QUEUE}
INFO 2008-04-10 13:59:56,486 [mqReceiver.2] org.mule.components.simple.LogComponent:
********************************************************************************
* Message received in component: mqReceiver. Content is: 'Hello' *
********************************************************************************
INFO 2008-04-10 13:59:56,487 [mqReceiver.2]
org.mule.providers.DefaultReplyToHandler: Reply Message sent to: queue://HELLO.QMGR/RESPONSE.QUEUE?
targetClient=1

Please enter something:

The following environment variable needs to be set for Mule to run successfully when MQSeries connector
functionality has been configured.

export LD_LIBRARY_PATH=/opt/mqm/java/lib

You must set this variable to the location of the Java library directory shipped with the MQ server
installation.

Sending Messages on a Remote Queue

This use case describes sending a Mule message to a WebSphere MQ QueueManager on a different
machine. After configuring WebSphere MQ with the appropriate queue and channel definitions, you
configure Mule as follows:

<?xml version="1.0" encoding="UTF-8"?>


<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:stdio="http://www.mulesource.org/schema/mule/stdio/2.2"
xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.2"
xmlns:mqs="http://www.mulesource.com/schema/mule/mqseries/2.2"

xsi:schemaLocation="
http://www.mulesource.com/schema/mule/mqseries/2.2 http://www.mulesource.com/schema/mule/
mqseries/2.2/mule-mqseries-ee.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-2.0.xsd
http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/
mule.xsd
http://www.mulesource.org/schema/mule/stdio/2.2 http://www.mulesource.org/schema/mule/
stdio/2.2/mule-stdio.xsd
http://www.mulesource.org/schema/mule/vm/2.2 http://www.mulesource.org/schema/mule/vm/2.2/mule-
vm.xsd">

<spring:bean name="connectionFactory" class="com.ibm.mq.jms.MQConnectionFactory"/>

Document generated by Confluence on Oct 27, 2008 21:07 Page 123


<mqs:connector name="mqSeriesConnector"
hostName="winter"
port="1414"
queueManager="HELLO.QMGR"
channel="HELLO.CHANNEL"
transportType="JMSC.MQJMS_TP_CLIENT_MQ_TCPIP"
targetClient="JMSC.MQJMS_CLIENT_NONJMS_MQ"
specification="1.1"
username=""
password=""
disableReplyToHandler="true"
connectionFactory-ref="connectionFactory">
</mqs:connector>

<stdio:connector name="stdioConnector" messageDelayTime="1000" promptMessage="Please enter


something: "/>

<model name="MQ_Series_Example">
<service name="mqSender">
<inbound>
<stdio:inbound-endpoint system="IN"/>
</inbound>
<echo-component/>
<outbound>
<pass-through-router>
<outbound-endpoint address="mqs://REQUEST.QUEUE">
<property key="JMSReplyTo" value="RESPONSE.QUEUE"/>
<property key="JMS_IBM_MsgType" value="1"/> <!-- com.ibm.mq.MQC.MQMT_REQUEST -->
</outbound-endpoint>
</pass-through-router>
</outbound>
</service>
</model>
</mule>

Note the channel configuration. This is how WebSphere MQ knows to send it to the remotely hosted
queue.

Mule sends the message as follows:

INFO 2008-04-14 15:29:27,572 [WrapperListener_start_runner] org.mule.MuleServer: Mule Server


initialized.

Please enter something:


Hello
INFO 2008-04-14 15:29:30,389 [mqSender.2] org.mule.components.simple.LogComponent:
********************************************************************************
* Message received in component: mqSender. Content is: 'Hello' *
********************************************************************************
INFO 2008-04-14 15:29:30,403 [MQJMSConnector.dispatcher.1]
org.mule.providers.mqseries.MQSeriesMessageDispatcher: Connected:
MQSeriesMessageDispatcher{this=1672bbb, endpoint=mqs://LOCAL.DEF.OF.REMOTE.QUEUE}

Please enter something:

On the receiving side:

[mqm@spring ~]$ /opt/mqm/samp/bin/amqsget ORANGE.QUEUE


Sample AMQSGET0 start
message <Hello>

no more messages
Sample AMQSGET0 end

You can use a the WebSphere MQ utility amqsget to verify the message was received on the remote
queue.

Document generated by Confluence on Oct 27, 2008 21:07 Page 124


Inbound Message Handling
The inbound messages are received by the connector and delivered to the component. If the
disableReplyToHandler property of the connector is not set to true and the inbound message type is
MQMT_REQUEST, the message returned by the component will be sent to the queue specified in the
JMSReplyTo property of the original message. However, if the outbound MQ endpoint exists in the
component, it will override the replyToHandler functionality. By default, disableReplyToHandler is set to
false.

Outbound Message Handling


The outbound endpoint behavior depends on the MQ message type specified in the JMS_IBM_MsgType
endpoint property. If the value of the property is set to MQMT_REPLY or MQMT_DATAGRAM, other
properties will be copied over from the original message and the message will be dispatched to the
queue.

If the message type is MQMT_REQUEST, the connector will check the existence of JMSReplyTo property on
the endpoint. If the property is not set, the temporary queue will be created.

If the remoteSync property is set on the endpoint, the connector will wait for the response on the queue
specified by JMSReplyTo. The timeout can be set using the remoteSyncTimeout setting. If a response is
received by the connector, it will be returned by the component.

Document generated by Confluence on Oct 27, 2008 21:07 Page 125


Retrieving the Connection Factory from JNDI
The connection factory can be loaded explicitly by the connector or from a JNDI registry. To support the
explicit case, the following configuration must be included in the connector declaration:

<spring:bean name="connectionFactory" class="com.ibm.mq.jms.MQConnectionFactory"/>

<mqs:connector ...
connectionFactory-ref="connectionFactory"/>

To support the case where a JNDI registry has been configured to store the connection factory, the
connector declaration should include the following parameters. This is the same as the regular JMS
transport documented here .

Document generated by Confluence on Oct 27, 2008 21:07 Page 126


<mqs:connector ...
jndiInitialFactory="com.sun.jndi.ldap.LdapCtxFactory"
jndiProviderUrl="ldap://localhost:10389/"
connectionFactoryJndiName="cn=ConnectionFactory,dc=example,dc=com"

Known Limitations
The Mule WMQ transport has been implemented as an extension to the JMS transport and has limited
functionality and support for native WebSphere MQ. Following are the features that the Mule WMQ
transport does not currently support:

• Durable topic subscription support


• Local and XA transactions
• Exit handler support
• MQMT_REPORT message type support
• Native WMQ connection pool support
• SSL connection support
• Data compression over channels (for performance throughput gain)
• JMS persistent delivery
• JMS 1.1 feature set certification

Document generated by Confluence on Oct 27, 2008 21:07 Page 127


Multicast Transport

This page last changed on Sep 19, 2008 by jackie.wheeler.

Multicast Transport
The Multicast transport sends and receives Mule events using IP multicasting. The Javadoc for this
transport can be found here .

Connector
The Multicast connector extends the UDP connector with additional optional attributes:

Attribute Description

timeToLive Set the time-to-live value for Multicast packets to


control their scope. It must be in the range 0 to
255 (inclusive).

loopback Whether to enable local loopback of Multicast


datagrams. The option is used by the platform
networking code as a hint for setting whether
Multicast data will be looped back to the local
socket.

Endpoints
You configure Multicast endpoints just as you would with any other transport, with the following additional
attributes:

• host: the IP address of the server, such as www.mulesource.com, localhost, or 127.0.0.1


• port: the port number of the server.

For example, you could configure a global endpoint as follows:

<multicast:endpoint host="224.0.0.1" port="60131" name="serverEndpoint" />

Transformers
The following transformers are used by default for this connector unless a transformer is explicitly set on
the provider.

Transformer Description

ByteArrayToString Converts a byte array to a String

StringToByteArray Converts a String to a byte array

Document generated by Confluence on Oct 27, 2008 21:07 Page 128


PGP Module

This page last changed on Aug 15, 2008 by jackie.wheeler.

This page is under construction

Mon Oct 27 23:07:35 CDT 2008

Detailed Configuration Information


• pgp:security-manager
• pgp:security-provider
• pgp:keybased-encryption-strategy
• pgp:security-filter

<pgp:security-manager ...>

Attributes

Name Type Required Default Description

id no

name no

Child Elements

Name Cardinality Description

pgp:security-provider 1..1 A security manager for PGP


related functionality.

pgp:keybased-encryption- 1..1 TODO


strategy

<pgp:security-provider ...>
A security manager for PGP related functionality.

Attributes

Name Type Required Default Description

name name (no spaces) no

keyManager-ref name (no spaces) no

Document generated by Confluence on Oct 27, 2008 21:07 Page 129


Child Elements

Name Cardinality Description

<pgp:keybased-encryption-strategy ...>
TODO

Attributes

Name Type Required Default Description

name name (no spaces) no

keyManager-ref name (no spaces) no

credentialsAccessor- name (no spaces) no


ref

Child Elements

Name Cardinality Description

<pgp:security-filter ...>
TODO

Attributes

Name Type Required Default Description

strategyName string no

signRequired string no

keyManager-ref name (no spaces) no

credentialsAccessor- name (no spaces) no


ref

Child Elements

Name Cardinality Description

Document generated by Confluence on Oct 27, 2008 21:07 Page 130


POP3 Transport

This page last changed on Oct 09, 2008 by jackie.wheeler.

POP3 Transport
The POP3 transport can be used for receiving messages from POP3 inboxes. The POP3S Transport
connects to POP3 mailboxes using SSL (POP3s) using the javax.mail API. The POP3 transport uses the
same filters and transformers as the Email Transport.

The Javadoc for this provider can be found here .

POP3 Connector
The POP3 connector supports all the common connector attributes and properties as well as the following
additional attributes:

Attribute Description Default Required

backupEnabled Whether to save copies False No


to the backup folder.

backupFolder The folder where No


messages are moved
for audit purposes after
they have been read.

checkFrequency Determines how often 60000 Yes


(in milliseconds) the
POP3 mailbox is polled
for new messages.

mailboxFolder The remote folder to INBOX No


check for email.

deleteReadMessages Whether to delete true No


messages after they
have been downloaded.
If set to false, the
messages are set to
SEEN.

Endpoints
POP3 and POP3S endpoints include details about connecting to a POP3 mailbox. You configure the
endpoints just as you would with any other transport, with the following additional attributes:

• user: the user name of the mailbox owner


• password: the password of the user
• host: the IP address of the POP3 server, such as www.mulesource.com, localhost, or 127.0.0.1
• port: the port number of the POP3 server. If not set for the POP3S connector, the default port is 995.

For example:

<pop3:inbound-endpoint user="bob" password="foo" host="pop.gmail.com" checkFrequency="3000" />

or:

<pop3s:inbound-endpoint user="bob" password="foo" host="pop.gmail.com" checkFrequency="3000" />

Document generated by Confluence on Oct 27, 2008 21:07 Page 131


This will log into the bob mailbox on pop.gmail.com using password foo (using the default port 995 for
the POP3S endpoint) and will check the mailbox for new messages every 30 seconds.

Escape Your Credentials

When including the user name and password in the endpoint, escape any characters
that are illegal for URIs, such as the @ character. For example, if the user name is
user@myco.com, you should enter it as user%40myco.com.

Document generated by Confluence on Oct 27, 2008 21:07 Page 132


POP3S Transport

This page last changed on Sep 19, 2008 by jackie.wheeler.

POP3S Transport
TLS/SSL connections are made on behalf of an entity, which can be anonymous or identified by a
certificate. The key store provides the certificates and associated private keys necessary for identifying
the entity making the connection. Additionally, connections are made to trusted systems. The public
certificates of trusted systems are stored in a trust store, which is used to verify that the connection
made to a remote system matches the expected identity.

The POP3s connector enables POP3 over SSL using the javax.mail APIs. It supports all the elements and
attributes of the POP3 connector plus some required properties for setting up the client key store and the
trust store for the SSL connection.

Property Description

tls-client Configures the client key store with the following


attributes:

• path: The location (which will be resolved


relative to the current classpath and file
system, if possible) of the keystore that
contains public certificates and private keys
for identification
• storePassword: The password used to
protect the keystore
• class: The type of keystore used (a Java
class name)

tls-trust-store Configures the trust store. The attributes are:

• path: The location (which will be resolved


relative to the current classpath and file
system, if possible) of the trust store that
contains public certificates of trusted servers
• storePassword: The password used to
protect the trust store

For example:

<pop3s:connector name="pop3sConnector">
<pop3s:tls-client path="clientKeystore" storePassword="mulepassword" />
<pop3s:tls-trust-store path="greenmail-truststore" storePassword="password" />
</pop3s:connector>
<model name="test">
<service name="relay">
<inbound>
<pop3s:inbound-endpoint user="bob" password="password" host="localhost" port="65436" />
</inbound>
...

For information on configuring endpoints using the POP3S connector, see POP3 Transport.

The POP3S transport supports the same filters and transformers as the Email transport.

Document generated by Confluence on Oct 27, 2008 21:07 Page 133


Quartz Transport

This page last changed on Jul 31, 2008 by jackie.wheeler.

Table of Contents

Click here to expand...

• Quartz Transport
• ° Connector
° - Attributes of <connector...>
- Child Elements of <connector...>
° Inbound endpoint
° - Attributes of <inbound-endpoint...>
- Child Elements of <inbound-endpoint...>
° Outbound endpoint
° - Attributes of <outbound-endpoint...>
- Child Elements of <outbound-endpoint...>
° Endpoint
° - Attributes of <endpoint...>
- Child Elements of <endpoint...>
• Jobs
• ° Event generator job
° - Child Elements of <event-generator-job...>
- Example Configurations
- Example Configurations
° Endpoint polling job
° - Child Elements of <endpoint-polling-job...>
- Example Configurations
° Scheduled dispatch job
° - Child Elements of <scheduled-dispatch-job...>
- Example Configurations
° Custom job
° - Attributes of <custom-job...>
- Example Configurations
° Custom job from message
° - Attributes of <custom-job-from-message...>
- Example Configurations

Quartz Transport
The Quartz transport provides support for scheduling events and for triggering new events. An inbound
quartz endpoint can be used to trigger inbound events that can be repeated, such as every second.
Outbound quartz endpoints can be used to schedule an existing event to fire at a later date. Users can
create schedules using cron expressions, and events can be persisted in a database.
This transport makes use of the Quartz Project at Open Symphony. The Quartz site has more generic
information about how to work with Quartz.
This transport becomes very powerful when using cron expressions to trigger events, and some of the
examples below provide examples of cron expressions. If you are not familiar with cron syntax, here is a
good tutorial.

Connector
The Quartz connector is used to configure the default behavior for Quartz endpoints that reference
the connector. Note if there is only one Quartz connector configured, all Quartz endpoints will use that
connector.

Document generated by Confluence on Oct 27, 2008 21:07 Page 134


Attributes of <connector...>

Name Type Required Default Description

scheduler-ref name (no spaces) no Provides an


implementation
of the Quartz
Scheduler
interface. If no
value is provided,
a scheduler is
retrieved from the
StdSchedulerFactory.
If no properties
are provided, the
getDefaultScheduler
method is called.
Otherwise, a new
factory instance is
created using the
given properties,
and a scheduler
is retrieved using
the getScheduler
method.

Child Elements of <connector...>

Name Cardinality Description

factory-property 0..* Set a property on the factory


(see scheduler-ref).

Inbound Endpoint
A Quartz inbound endpoint can be used to generate events. It is most useful when you want to trigger a
service at a given interval (or cron expression) rather than have an external event trigger the service.

Attributes of <inbound-endpoint...>

Name Type Required Default Description

jobName string no The name to


associate with
the job on the
endpoint. This is
only really used
internally when
storing events.

cronExpression string no The cron


expression to
schedule events
at specified
dates/times.
This attribute or

Document generated by Confluence on Oct 27, 2008 21:07 Page 135


repeatInterval is
required. A cron
expression is a
string comprised
by 6 or 7 fields
separated by
white space.
Fields can contain
any of the allowed
values, along
with various
combinations
of the allowed
special characters
for that field.
The fields are
as follows:
Field Name
MandatoryAllowed
ValuesAllowed
Special Chars
SecondsYES0-59,
-*/
MinutesYES0-59, -
* / HoursYES0-23,
- * / Day of
MonthYES1-31,
-*?/LWC
MonthYES1-12
or JAN-DEC,
- * / Day of
WeekYES1-7 or
SUN-SAT, - * ? / L
C # YearNOempty,
1970-2099, - * /
Cron expressions
can be as simple
as this: * * *
* ? * or more
complex, like
this: 0 0/5
14,18,3-39,52 ?
JAN,MAR,SEP
MON-FRI
2002-2010 Some
examples: 0 0 12
* * ? Fire at 12pm
(noon) every day
0 15 10 ? * * Fire
at 10:15am every
day 0 15 10 * * ?
Fire at 10:15am
every day 0 15
10 * * ? * Fire at
10:15am every
day 0 15 10 *
* ? 2005 Fire at
10:15am every
day during the
year 2005 0 * 14
* * ? Fire every
minute starting at
2pm and ending
at 2:59pm, every

Document generated by Confluence on Oct 27, 2008 21:07 Page 136


day 0 0/5 14 *
* ? Fire every 5
minutes starting
at 2pm and
ending at 2:55pm,
every day

repeatInterval long no The number of


milliseconds
between two
events. This
attribute or
cronExpression is
required.

repeatCount integer no The number of


events to be
scheduled. This
value defaults to
-1, which means
that the events
will be scheduled
indefinitely.

startDelay long no The number of


milliseconds that
will elapse before
the first event is
fired.

Child Elements of <inbound-endpoint...>

Name Cardinality Description

abstract-job 1..1 A placeholder for Quartz jobs


that can be set on the endpoint.

Outbound Endpoint
An outbound Quartz endpoint allows existing events to be stored and fired at a later time/date. If you
are using a persistent event store, the payload of the event must implement java.io.Serializable.
You configure an org.quartz.Job implementation on the endpoint to tell it what action to take. Mule has
some default jobs, but you can also write your own.

Attributes of <outbound-endpoint...>

Name Type Required Default Description

jobName string no The name to


associate with
the job on the
endpoint. This is
only really used
internally when
storing events.

cronExpression string no The cron


expression to

Document generated by Confluence on Oct 27, 2008 21:07 Page 137


schedule events
at specified
dates/times.
This attribute or
repeatInterval is
required. A cron
expression is a
string comprised
by 6 or 7 fields
separated by
white space.
Fields can contain
any of the allowed
values, along
with various
combinations
of the allowed
special characters
for that field.
The fields are
as follows:
Field Name
MandatoryAllowed
ValuesAllowed
Special Chars
SecondsYES0-59,
-*/
MinutesYES0-59, -
* / HoursYES0-23,
- * / Day of
MonthYES1-31,
-*?/LWC
MonthYES1-12
or JAN-DEC,
- * / Day of
WeekYES1-7 or
SUN-SAT, - * ? / L
C # YearNOempty,
1970-2099, - * /
Cron expressions
can be as simple
as this: * * *
* ? * or more
complex, like
this: 0 0/5
14,18,3-39,52 ?
JAN,MAR,SEP
MON-FRI
2002-2010 Some
examples: 0 0 12
* * ? Fire at 12pm
(noon) every day
0 15 10 ? * * Fire
at 10:15am every
day 0 15 10 * * ?
Fire at 10:15am
every day 0 15
10 * * ? * Fire at
10:15am every
day 0 15 10 *
* ? 2005 Fire at
10:15am every
day during the
year 2005 0 * 14

Document generated by Confluence on Oct 27, 2008 21:07 Page 138


* * ? Fire every
minute starting at
2pm and ending
at 2:59pm, every
day 0 0/5 14 *
* ? Fire every 5
minutes starting
at 2pm and
ending at 2:55pm,
every day

repeatInterval long no The number of


milliseconds
between two
events. This
attribute or
cronExpression is
required.

repeatCount integer no The number of


events to be
scheduled. This
value defaults to
-1, which means
that the events
will be scheduled
indefinitely.

startDelay long no The number of


milliseconds that
will elapse before
the first event is
fired.

Child Elements of <outbound-endpoint...>

Name Cardinality Description

abstract-job 1..1 A placeholder for Quartz jobs


that can be set on the endpoint.

Endpoint
A global endpoint that can be used as a template to create inbound and outbound Quartz endpoints.
Common configuration can be set on a global endpoint and then referenced using the @ref attribute on
the local endpoint. Note that because jobs sometimes only work on inbound or outbound endpoints, they
have to be set on the local endpoint.

Attributes of <endpoint...>

Name Type Required Default Description

jobName string no The name to


associate with
the job on the
endpoint. This is
only really used

Document generated by Confluence on Oct 27, 2008 21:07 Page 139


internally when
storing events.

cronExpression string no The cron


expression to
schedule events
at specified
dates/times.
This attribute or
repeatInterval is
required. A cron
expression is a
string comprised
by 6 or 7 fields
separated by
white space.
Fields can contain
any of the allowed
values, along
with various
combinations
of the allowed
special characters
for that field.
The fields are
as follows:
Field Name
MandatoryAllowed
ValuesAllowed
Special Chars
SecondsYES0-59,
-*/
MinutesYES0-59, -
* / HoursYES0-23,
- * / Day of
MonthYES1-31,
-*?/LWC
MonthYES1-12
or JAN-DEC,
- * / Day of
WeekYES1-7 or
SUN-SAT, - * ? / L
C # YearNOempty,
1970-2099, - * /
Cron expressions
can be as simple
as this: * * *
* ? * or more
complex, like
this: 0 0/5
14,18,3-39,52 ?
JAN,MAR,SEP
MON-FRI
2002-2010 Some
examples: 0 0 12
* * ? Fire at 12pm
(noon) every day
0 15 10 ? * * Fire
at 10:15am every
day 0 15 10 * * ?
Fire at 10:15am
every day 0 15
10 * * ? * Fire at
10:15am every

Document generated by Confluence on Oct 27, 2008 21:07 Page 140


day 0 15 10 *
* ? 2005 Fire at
10:15am every
day during the
year 2005 0 * 14
* * ? Fire every
minute starting at
2pm and ending
at 2:59pm, every
day 0 0/5 14 *
* ? Fire every 5
minutes starting
at 2pm and
ending at 2:55pm,
every day

repeatInterval long no The number of


milliseconds
between two
events. This
attribute or
cronExpression is
required.

repeatCount integer no The number of


events to be
scheduled. This
value defaults to
-1, which means
that the events
will be scheduled
indefinitely.

startDelay long no The number of


milliseconds that
will elapse before
the first event is
fired.

Child Elements of <endpoint...>

Name Cardinality Description

abstract-job 0..1 A placeholder for Quartz jobs


that can be set on the endpoint.

Jobs
Jobs are used to perform an action when a time trigger occurs from the Quartz transport. Mule provides a
number of jobs for generating and scheduling events. These are detailed below. Users can also write their
own jobs and hook them in using the custom-job type included with Mule.

Event Generator Job


An inbound endpoint job that will trigger a new event for the service according to the schedule on the
endpoint. This is useful for periodically triggering a service without the need for an external event to
occur.

Document generated by Confluence on Oct 27, 2008 21:07 Page 141


Child Elements of <event-generator-job...>

Name Cardinality Description

payload 0..1 The payload of the newly


created event. The payload can
be a reference to a file, fixed
string, or object configured
as a Spring bean. If this
value is not set, an event
will be generated with an
org.mule.transport.NullPayload
instance.

Example Configurations

Note that the documentation for this example should be embedded within the code.

Click here to expand...


An error occurred: null. The system administrator has been notified.

Example Configurations

Note that the documentation for this example should be embedded within the code.

Click here to expand...


An error occurred: null. The system administrator has been notified.

Endpoint Polling Job


An inbound endpoint job that can be used to periodically read from an external source (via another
endpoint). This can be useful for triggering time-based events from sources that do not support polling or
for simply controlling the rate in which events are received from the source.

Child Elements of <endpoint-polling-job...>

Name Cardinality Description

job-endpoint 0..1 A reference to another


configured endpoint from which
events will be received.

Example Configurations

Note that the documentation for this example should be embedded within the code.

Click here to expand...


An error occurred: null. The system administrator has been notified.

Scheduled Dispatch Job


An outbound job that will schedule a job for dispatch at a later time/date. The event will get dispatched
using the configured endpoint reference.

Document generated by Confluence on Oct 27, 2008 21:07 Page 142


Child Elements of <scheduled-dispatch-job...>

Name Cardinality Description

job-endpoint 0..1 The endpoint used to dispatch


the scheduled event.

Example Configurations

Note that the documentation for this example should be embedded within the code.

Click here to expand...


An error occurred: null. The system administrator has been notified.

Custom Job
A custom job can be configured on inbound or outbound endpoints. You can create and configure your
own job implementation and use it on a Quartz endpoint. A custom job can be configured as a bean in
the XML configuration and referenced using this job.

Attributes of <custom-job...>

Name Type Required Default Description

groupName string no The group name


of the scheduled
job

jobGroupName string no The job group


name of the
scheduled job.

job-ref string no The bean name or


ID of the custom
job to use when
this job gets
executed.

Example Configurations

Note that the documentation for this example should be embedded within the code.

Click here to expand...


An error occurred: null. The system administrator has been notified.

Custom Job From Message


Allows a job to be stored on the current message. This can only be used on outbound endpoints. When
the message is received, the job is read and the job is added to the scheduler with the current message.
This allows for custom scheduling behavior determined by the message itself. Usually the service or a
transformer would create the job on the message based on application-specific logic. Any Mule-supported
expressions can be used to read the job from the message. Typically, you add the job as a header, but an
attachment could also be used.

Document generated by Confluence on Oct 27, 2008 21:07 Page 143


Attributes of <custom-job-from-message...>

Name Type Required Default Description

groupName string no The group name


of the scheduled
job

jobGroupName string no The job group


name of the
scheduled job.

Example Configurations

Note that the documentation for this example should be embedded within the code.

Click here to expand...


An error occurred: null. The system administrator has been notified.

Document generated by Confluence on Oct 27, 2008 21:07 Page 144


RMI Transport

This page last changed on Sep 16, 2008 by jackie.wheeler.

RMI Transport
This page is ready for review

The RMI transport can be used to send and receive Mule events over JRMP. This transport has a
dispatcher that invokes an RMI method and a polling receiver that repeatedly does the same.

You configure the RMI transport as follows:

<mule xmlns="http://www.mulesource.org/schema/mule/core/2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:rmi="http://www.mulesource.org/schema/mule/rmi/2.0"
xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.0"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-2.5.xsd
http://www.mulesource.org/schema/mule/core/2.0 http://www.mulesource.org/schema/mule/core/2.0/
mule.xsd
http://www.mulesource.org/schema/mule/vm/2.0 http://www.mulesource.org/schema/mule/vm/2.0/mule-
vm.xsd
http://www.mulesource.org/schema/mule/rmi/2.0 http://www.mulesource.org/schema/mule/rmi/2.0/mule-
rmi.xsd">

<spring:bean name="jndiFactory" class="org.mule.transport.rmi.MuleRMIFactory"/>

<spring:bean name="jndiContext" factory-bean="jndiFactory" factory-method="create"/>

<rmi:connector name="rmi" jndiContext-ref="jndiContext" securityPolicy="rmi.policy"/>

<rmi:endpoint name="hello" host="localhost" port="1099" object="HelloServer"


method="hello" methodArgumentTypes="java.lang.String"/>

The connector looks for the method and methodArgumentTypes. It uses the payload as the argument.

JNP Connector
If you want to use the Java naming protocol to bind to remote objects, you can use the JNP connector
instead simply by using the jnp namespace.

<mule xmlns="http://www.mulesource.org/schema/mule/core/2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:jnp="http://www.mulesource.org/schema/mule/jnp/2.0"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-2.5.xsd
http://www.mulesource.org/schema/mule/core/2.0 http://www.mulesource.org/schema/mule/core/2.0/
mule.xsd
http://www.mulesource.org/schema/mule/jnp/2.0 http://www.mulesource.org/schema/mule/jnp/2.0/mule-
jnp.xsd">

<spring:bean name="jndiFactory" class="org.mule.transport.rmi.MuleRMIFactory"/>


<spring:bean name="jndiContext" factory-bean="jndiFactory" factory-method="create"/>

<jnp:connector name="jnp" jndiContext-ref="jndiContext" securityPolicy="rmi.policy"/>

Document generated by Confluence on Oct 27, 2008 21:07 Page 145


<jnp:endpoint name="Sender2" host="localhost" port="1099" object="MatchingUMO"
method="reverseString"/>
...

Configuration Reference

Connector

Attributes of <connector...>

Name Type Required Default Description

pollingFrequency long no Period (ms)


between polling
connections.

securityManager- name (no spaces) no Bean reference


ref to the security
manager that
should be used.

securityPolicy string no The security


policy (file name)
used to enable
connections.

serverClassName name (no spaces) no The target class


name.

serverCodebase string no The target


method.

Endpoint

Attributes of <endpoint...>

Name Type Required Default Description

host string no

port port number no

object string no

method string no

methodArgumentTypes
string no

Document generated by Confluence on Oct 27, 2008 21:07 Page 146


Servlet Transport

This page last changed on Oct 14, 2008 by dan.diephouse@mulesource.com.

Servlet Transport
The Servlet transport provides integration with a servlet implementation. The implementing servlet does
the work of receiving a request, and the Servlet transport then hands off the request to any receivers
registered with it. There is no notion of a dispatcher for this connector, as it is triggered by a request and
may or may not return a response. You specify the servlet URL as part of the connector configuration and
then specify the endpoints just like any other HTTP endpoints.

The Javadoc for this transport can be found here . For more information about using Mule with servlet
containers, see Embedding Mule in a Java Application or Webapp. For information on using the RESTlet
connector, click here.

Connector
Servlet connector is a channel adapter between Mule and a servlet engine. It allows the
MuleReceiverServlet to look up components interested in requests it receives via the servlet container.

Attributes of <connector...>

Name Type Required Default Description

servletUrl no The real URL


on which the
servlet container
is bound. If this
is not set, the
WSDL may not
be generated
correctly.

For example:

<servlet:connector name="servletConnector" servletUrl="http://localhost:8180/path/" />

You can also specify the servlet URL as part of the endpoint:

<servlet:inbound-endpoint path="foo" />

or:

<inbound-endpoint address="servlet://foo" />

Servlet endpoints are identical to HTTP endpoints with the exception that they use the servlet: prefix
instead of http:. For more information, see HTTP Transport.

Document generated by Confluence on Oct 27, 2008 21:07 Page 147


SMTP Transport

This page last changed on Oct 14, 2008 by dan.diephouse@mulesource.com.

SMTP Transport
The SMTP transport can be used for sending messages over SMTP using the javax.mail API. See
the SMTPS Transport for a secure version. The implementation supports CC/BCC/ReplyTo addresses,
attachments, custom Header properties, and customizable authentication. It also provides support for
javax.mail.Message transformation.

The Javadoc for this transport can be found here .

SMTP Connector
The POP3 connector supports all the common connector attributes and properties as well as the following
optional element and attributes:

Element Description

header Additional header key/value pairs, added to the


message.

Attribute Description

bccAddresses Comma separated list of addresses for blind


copies.

ccAddresses Comma separated list of addresses for copies.

contentType Mime type for the outgoing message.

fromAddress The from address for the outgoing message.

replyToAddresses The reply-to address for the outgoing message.

subject The default subject for the outgoing message if


none is set in the message.

For example:

<smtp:connector name="smtpConnector" bccAddresses="abc@example.com" ccAddresses="bcd@example.com"


contentType="foo/bar"
fromAddress="cde@example.com" replyToAddresses="def@example.com"
subject="subject">
<smtp:header key="foo" value="bar" />
<smtp:header key="baz" value="boz" />
</smtp:connector>

Generic SMTP(S) Endpoints


SMTP endpoints describe details about the SMTP server and the recipients of messages sent from the
SMTP endpoint. SMTP URIs use the following syntax:

smtp://[user:password@]<smtp server>[MULE::port]?address=<recipient address>

The format is the same for SMTPS:

smtps://[user:password@]<smtp server>[MULE::port]?address=<recipient address>

Document generated by Confluence on Oct 27, 2008 21:07 Page 148


For example:

smtp://muletestbox:123456@smtp.mail.yahoo.co.uk?address=dave@mycomany.com

This will send mail using smtp.mail.yahoo.co.uk (using the default SMTP port) to the address
dave@mycomany.com. The SMTP request is authenticated using the username muletestbox and the
password 123456.

Escape Your Credentials

When including the user name and password in the endpoint, escape any characters
that are illegal for URIs, such as the @ character. For example, if the user name is
user@myco.com, you should enter it as user%40myco.com.

You will probably want to set other information such as subject and fromAddress. These can be set as
parameters on the URI, but we recommend you set them as endpoint properties to make it easier to read
and maintain the configuration.

<outbound>
<outbound-pass-through-router>
<smtp:outbound-endpoint host="localhost" port="65437" from="steve@mycompany.com"
to="bob@example.com" subject="Please verify your account details"/>
</outbound-pass-through-router>
</outbound>

So far, all configuration has been static in that you define all the information in the configuration of the
endpoint. However, you can set several MailProperties to control the settings of the outgoing message.
These properties will override the endpoint properties. If you always want to set the email address
dynamically, you can leave out the address parameter on the SMTP endpoint.

Document generated by Confluence on Oct 27, 2008 21:07 Page 149


SMTPS Transport

This page last changed on Sep 19, 2008 by jackie.wheeler.

SMTPS Transport
TLS/SSL connections are made on behalf of an entity, which can be anonymous or identified by a
certificate. The key store provides the certificates and associated private keys necessary for identifying
the entity making the connection. Additionally, connections are made to trusted systems. The public
certificates of trusted systems are stored in a trust store, which is used to verify that the connection
made to a remote system matches the expected identity.

The SMTPS connector enables SMTP over SSL using the javax.mail APIs. It supports all the elements
and attributes of the SMTP connector plus some required properties for setting up the client key store and
the trust store for the SSL connection.

Property Description

tls-client Configures the client key store with the following


attributes:

• path: The location (which will be resolved


relative to the current classpath and file
system, if possible) of the keystore that
contains public certificates and private keys
for identification
• storePassword: The password used to
protect the keystore
• class: The type of keystore used (a Java
class name)

tls-trust-store Configures the trust store. The attributes are:

• path: The location (which will be resolved


relative to the current classpath and file
system, if possible) of the trust store that
contains public certificates of trusted servers
• storePassword: The password used to
protect the trust store

For example:

<smtps:connector name="smtpsConnector">
<smtps:tls-client path="clientKeystore" storePassword="mulepassword" />
<smtps:tls-trust-store path="greenmail-truststore" storePassword="password" />
</smtps:connector>
<model name="test">
<service name="relay">
<inbound>
<vm:inbound-endpoint path="send" />
</inbound>
<outbound>
<outbound-pass-through-router>
<smtps:outbound-endpoint host="localhost" port="65439" to="bob@example.com" />
</outbound-pass-through-router>
</outbound>
...

For information on configuring endpoints using the SMTPS connector, see SMTP Transport.

The SMTPS transport supports the same filters and transformers as the Email transport.

Document generated by Confluence on Oct 27, 2008 21:07 Page 150


SOAP Transport

This page last changed on Oct 17, 2008 by jackie.wheeler.

SOAP Transport
The SOAP transport is currently deprecated. We recommend that you either use the CXF
Transport or the Axis Transport to build web services from now on.

The SOAP transport enables your components to be exposed as web services and to act as SOAP clients.
The SOAP transport provides support for the CFX and Axis transports.

The Javadoc for the SOAP transport can be found here .

You configure a SOAP endpoint as follows:

soap:http://localhost:1234/MyService

The actual SOAP stack used to execute this service will be discovered based on the first SOAP stack
available on the class path. Alternatively, an implementation can be specified directly.

The SOAP transport provides a single transformer, http-to-soap-request-transformer, which converts


an HTTP GET request into a SOAP request. It does so according to the following template:

<?xml version=\"1.0\" encoding=\"{0}\"?>


<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"
xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"
xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">
<soap:Body>
<NAMESPACE:METHOD>
<NAMESPACE:PROPERTY1>VALUE1</NAMESPACE:PROPERTY1>
<NAMESPACE:PROPERTY2>VALUE1</NAMESPACE:PROPERTY2>
...
</NAMESPACE:METHOD>
</soap:Body>
</soap:Envelope>

...where namespace is a property on the endpoint, the method is the "method" property set on the
message, and the properties are from the HTTP GET request.

For example, given the following transformer configuration:

<custom-transformer class="org.mule.transport.soap.transformers.HttpRequestToSoapRequest">
<spring:property name="namespace" value="http://acme.com/hello">
</custom-transformer>

...and a GET request of "http://foo.com/hello?method=sayHello&name=Dan&salutation=Bonjour", the


following SOAP message would be generated:

<?xml version=\"1.0\" encoding=\"{0}\"?>


<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"
xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"
xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">
<soap:Body>
<sayHello xmlns="http://acme.com/hello">
<name>Dan</name>
<salutation>Bonjour</salutation>
</sayHello>
</soap:Body>
</soap:Envelope>

Document generated by Confluence on Oct 27, 2008 21:07 Page 151


SSL Transport

This page last changed on Oct 15, 2008 by dan.diephouse@mulesource.com.

SSL Transport
The SSL transport can be used for secure socket communication using SSL or TLS.

The Javadoc for this transport can be found here .

Connector
Connects Mule to an SSL socket to send or receive data via the network.

Child Elements of <connector...>

Name Cardinality Description

client 0..1 The client key store. SSL and


TLS connections are made on
behalf of an entity, which can
be anonymous or identified
by a certificate. This interface
specifies how a keystore can be
used to provide the certificates
(and associated private keys)
necessary for identification.

key-store 0..1 The key store information,


including location, key store
type, and algorithm.

server 0..1 The server trust store. TLS


connections are made to trusted
systems - the public certificates
of trusted systems are stored in
a keystore (called a trust store)
and used to verify that the
connection made to a remote
system really is the expected
identity.

protocol-handler 0..1 Configures the global Java


protocol handler by setting
the java.protocol.handler.pkgs
system property.

Endpoint

Attributes of <endpoint...>

Name Type Required Default Description

host string no

Document generated by Confluence on Oct 27, 2008 21:07 Page 152


port port number no

Inbound Endpoint

Attributes of <inbound-endpoint...>

Name Type Required Default Description

host string no

port port number no

Outbound Endpoint

Attributes of <outbound-endpoint...>

Name Type Required Default Description

host string no

port port number no

To configure the SSL connector:

<?xml version="1.0" encoding="UTF-8" ?>


<mule xmlns="http://www.mulesource.org/schema/mule/core/2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ssl="http://www.mulesource.org/schema/mule/ssl/2.0"
xsi:schemaLocation="http://www.mulesource.org/schema/mule/core/2.0
http://www.mulesource.org/schema/mule/core/2.0/mule.xsd
http://www.mulesource.org/schema/mule/ssl/2.0
http://www.mulesource.org/schema/mule/ssl/2.0/mule-ssl.xsd">
<ssl:connector name="SslConnector" keepSendSocketOpen="true">
<ssl:client path="clientKeyStore" storePassword="mulepassword" />
<ssl:key-store path="serverKeystore" storePassword="mulepassword" keyPassword="mulepassword" />
<ssl:server path="trustStore" storePassword="mulepassword" />
</ssl:connector>
<endpoint name="sendEndpoint" address="ssl://localhost:60198" synchronous="true" />
...

To configure the TLS connector instead of the SSL connector, specify the tls namespace and schema,
configure the connector, and then use the tls prefix for endpoints:

<?xml version="1.0" encoding="UTF-8" ?>


<mule xmlns="http://www.mulesource.org/schema/mule/core/2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tls="http://www.mulesource.org/schema/mule/tls/2.0"
xsi:schemaLocation="http://www.mulesource.org/schema/mule/core/2.0
http://www.mulesource.org/schema/mule/core/2.0/mule.xsd
http://www.mulesource.org/schema/mule/tls/2.0
http://www.mulesource.org/schema/mule/tls/2.0/mule-tls.xsd">
<tls:connector name="tlsConnector" keepSendSocketOpen="true">
<tls:client path="clientKeyStore" storePassword="mulepassword" />
<tls:key-store path="serverKeystore" storePassword="mulepassword" keyPassword="mulepassword" />
<tls:server path="trustStore" storePassword="mulepassword" />
</tls:connector>
<tls:endpoint name="sendEndpoint" connector-ref="tlsConnector" address="tls://localhost:60198"
synchronous="true" />

Document generated by Confluence on Oct 27, 2008 21:07 Page 153


...

Document generated by Confluence on Oct 27, 2008 21:07 Page 154


STDIO Transport

This page last changed on Oct 21, 2008 by jackie.wheeler.

STDIO Transport
The STDIO Transport allows the reading and writing of streaming data to Java's System.out and
System.in objects for debugging.

Connector

Attributes of <connector...>

Name Type Required Default Description

messageDelayTime long no Delay in


milliseconds
before printing the
prompt to stdout.

outputMessage string no Text printed to


stdout when a
message is sent.

promptMessage string no Text printed to


stdout when
waiting for input.

promptMessageCode string no Code used to


retrieve prompt
message from
resource bundle.

outputMessageCode string no Code used to


retrieve output
message from
resource bundle.

resourceBundle string no Resource bundle


to provide
prompt with
promptMessageCode.

To configure the STDIO connector:

<?xml version="1.0" encoding="UTF-8" ?>


<mule xmlns="http://www.mulesource.org/schema/mule/core/2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:stdio="http://www.mulesource.org/schema/mule/stdio/2.0"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.mulesource.org/schema/mule/core/2.0
http://www.mulesource.org/schema/mule/core/2.0/mule.xsd
http://www.mulesource.org/schema/mule/stdio/2.0
http://www.mulesource.org/schema/mule/stdio/2.0/mule-stdio.xsd">
<stdio:connector name="stdioConnector" messageDelayTime="1234" outputMessage="abc"
promptMessage="bcd" promptMessageCode="456" resourceBundle="dummy-messages" />
<model name="model">
<service name="service">

Document generated by Confluence on Oct 27, 2008 21:07 Page 155


<inbound>
<stdio:inbound-endpoint name="in" system="IN" connector-ref="stdioConnector" />
</inbound>
<outbound>
<multicasting-router>
<stdio:outbound-endpoint name="out" system="OUT" connector-ref="stdioConnector" />
<stdio:outbound-endpoint name="err" system="ERR" connector-ref="stdioConnector" />
</multicasting-router>
</outbound>
</service>
</model>
</mule>

Transformers

There are no built-in transformers for the STDIO transport.

Internationalizing Messages

If you are internationalizing your application, you can also internationalize the promptMessages and
outputMessages for the STDIO connector. (This assumes that you have already created a resource bundle
that contains your messages as described on that page.)

To internationalize, you must specify both the resourceBundle parameter and the promptMessageCode
and/or outputMessageCode parameters. The resourceBundle parameter will contain the key to the
resource bundle itself. The promptMessageCode provides the key to the message in the bundle for
the prompt message. In the snippet above, the "dummy-messages" resource bundle means that the
prompt message "456" will be expected in the bundle META-INF/services/org/mule/i18n/dummy-
messages<langCode>.properties.

Document generated by Confluence on Oct 27, 2008 21:07 Page 156


TCP Transport

This page last changed on Sep 19, 2008 by jackie.wheeler.

Table of Contents

Click here to expand...

• TCP Transport
• ° Connector
° - Child Elements of <connector...>
° Inbound endpoint
° - Attributes of <inbound-endpoint...>
° Outbound endpoint
° - Attributes of <outbound-endpoint...>
° Endpoint
° - Attributes of <endpoint...>
° Streaming protocol
° Xml protocol
° Xml eof protocol
° Eof protocol
° - Attributes of <eof-protocol...>
° Direct protocol
° - Attributes of <direct-protocol...>
° Safe protocol
° - Attributes of <safe-protocol...>
° Length protocol
° - Attributes of <length-protocol...>
° Custom protocol
° - Attributes of <custom-protocol...>
° Transformers

TCP Transport
The TCP transport enables events to be sent and received over TCP sockets.

Connector
Connects Mule to a TCP socket to send or receive data via the network.

Child Elements of <connector...>

Name Cardinality Description

abstract-protocol 0..1 The class name for the protocol


handler. This controls how the
raw data stream is converted
into messages. By default,
messages are constructed
as dara is received, with no
correction for multiple packets
or fragmentation. Typically,
change this value, or use
a transport that includes a
protocol like HTTP.

Document generated by Confluence on Oct 27, 2008 21:07 Page 157


Inbound Endpoint

Attributes of <inbound-endpoint...>

Name Type Required Default Description

host string no

port port number no

Outbound Endpoint

Attributes of <outbound-endpoint...>

Name Type Required Default Description

host string no

port port number no

Endpoint

Attributes of <endpoint...>

Name Type Required Default Description

host string no

port port number no

Streaming Protocol
TCP does not guarantee that data written to a socket is transmitted in a single packet, so if you want to
transmit entire Mule messages reliably, you must specify an additional protocol. However, this is not an
issue with streaming, so this is an alias for the "direct" (null) protocol.

Xml Protocol
TCP does not guarantee that data written to a socket is transmitted in a single packet, so if you want to
transmit entire Mule messages reliably, you must specify an additional protocol. This protocol uses XML
syntax to isolate messages from the stream of bytes received, so it will only work with well-formed XML.

Xml Eof Protocol


Similar to "xml-protocol", but it will also use socket closure to terminate a message (even if the XML is
not well-formed).

Document generated by Confluence on Oct 27, 2008 21:07 Page 158


Eof Protocol
TCP does not guarantee that data written to a socket is transmitted in a single packet, so if you want
to transmit entire Mule messages reliably, you must specify an additional protocol. This protocol simply
accumulates all data until the socket closes and places it in a single message.

Attributes of <eof-protocol...>

Name Type Required Default Description

payloadOnly boolean no Sends only the


payload, not
the entire Mule
message object or
its properties. This
defaults to true
when the protocol
is not specified
explicitly (when
the safe protocol
is used).

Direct Protocol
TCP does not guarantee that data written to a socket is transmitted in a single packet. Using this "null"
protocol does not change the normal TCP behavior, so message fragmentation may occur. For example, a
single sent message may be received in several pieces, each as a separate received message. Typically,
it is not a good choice for messaging within Mule, but it may be necessary to interface with external TCP-
based protocols.

Attributes of <direct-protocol...>

Name Type Required Default Description

payloadOnly boolean no Sends only the


payload, not
the entire Mule
message object or
its properties. This
defaults to true
when the protocol
is not specified
explicitly (when
the safe protocol
is used).

Safe Protocol
Similar to "length-protocol", but it also includes a prefix. Verification of the prefix allows mis-matched
protocols to be detected and avoids interpreting "random" data as a message length (which may give
out-of-memory errors). This is the default protocol in Mule 2.x.

Document generated by Confluence on Oct 27, 2008 21:07 Page 159


Attributes of <safe-protocol...>

Name Type Required Default Description

payloadOnly boolean no Sends only the


payload, not
the entire Mule
message object or
its properties. This
defaults to true
when the protocol
is not specified
explicitly (when
the safe protocol
is used).

maxMessageLength integer no An optional


maximum length
for the number
of bytes in a
single message.
Messages larger
than this will
trigger an error in
the receiver, but it
give an assurance
that no out-of-
memory error will
occur.

Length Protocol
This protocol precedes each message with the number of bytes sent so that an entire message can be
constructed on the received.

Attributes of <length-protocol...>

Name Type Required Default Description

payloadOnly boolean no Sends only the


payload, not
the entire Mule
message object or
its properties. This
defaults to true
when the protocol
is not specified
explicitly (when
the safe protocol
is used).

maxMessageLength integer no An optional


maximum length
for the number
of bytes in a
single message.
Messages larger
than this will

Document generated by Confluence on Oct 27, 2008 21:07 Page 160


trigger an error in
the receiver, but it
give an assurance
that no out-of-
memory error will
occur.

Custom Protocol
The user may supply their own protocol implementation via this element.

Attributes of <custom-protocol...>

Name Type Required Default Description

class class name no A class that


implements
the TcpProtocol
interface.

Transformers
The following transformers are used by default for the TCP transport unless a transformer is explicitly set
on the connector or service.

Transformer Description

ByteArrayToString Converts a byte array to a String

StringToByteArray Converts a String to a byte array

Document generated by Confluence on Oct 27, 2008 21:07 Page 161


UDP Transport

This page last changed on Oct 14, 2008 by dan.diephouse@mulesource.com.

UDP Transport
The UDP transport enables events to be sent and received as Datagram packets.

The Javadoc for this transport can be found here .

Connector

Attributes of <connector...>

Name Type Required Default Description

receiveBufferSize integer no The size of the


receiving buffer
for the socket.

receiveTimeout long no The amount of


time after which
a Receive call will
time out.

sendBufferSize integer no The size of the


sending buffer for
the socket.

sendTimeout long no The amount of


time after which a
Send call will time
out.

socketLinger long no The amount of


time the socket
will remain open
after a closesocket
call.

broadcast boolean no Whether to enable


the socket to send
broadcast data.

keepSendSocketOpenboolean no Whether to keep


the Sending
socket open.

Endpoints
You configure UDP endpoints just as you would with any other transport, with the following additional
attributes:

• host: the IP address of the server, such as www.mulesource.com, localhost, or 127.0.0.1


• port: the port number of the server.

For example:

Document generated by Confluence on Oct 27, 2008 21:07 Page 162


<udp:inbound-endpoint host="${hostname}" port="61000" />

Message Payload
The default message payload of the UDP transport for incoming messages is a byte[] array.

Document generated by Confluence on Oct 27, 2008 21:07 Page 163


VM Transport

This page last changed on Oct 15, 2008 by jackie.wheeler.

VM Transport
The VM transport is used for intra-VM communication between components managed by Mule. The
connector provides options for configuring VM transient or persistent queues.

The Javadoc for this transport can be found here .

Connector

Attributes of <connector...>

Name Type Required Default Description

queueEvents boolean no Determines


whether queues
should be set up
for listeners on
the connector. If
set to false, the
connector simply
forwards events
to components via
the Mule server.
If it is set to
true, the queues
are configured
using the queuing
profile.

queueTimeout positiveInteger no

Child Elements of <connector...>

Name Cardinality Description

queueProfile 0..1 DEPRECATED. USE "<queue-


profile>" instead.

queue-profile 0..1

Using VM Queues
When using a synchronous VM endpoint, events are delivered in memory from one component to another
(asynchronous endpoints introduce an event queue that threads can consume from). However, when the
queueEvents property is set, events can be stored in arbitrary memory queues and consumed later by
clients or components. Furthermore, these queues can be persistent and XA transactional (see below).

To use VM queues, the queueEvents property must be set on the connector, and all VM endpoints that
should queue events must use a VM connector that has queueEvents enabled. You cannot set the
queueEvents property on the endpoint. For example:

<?xml version="1.0" encoding="UTF-8"?>

Document generated by Confluence on Oct 27, 2008 21:07 Page 164


<mule xmlns="http://www.mulesource.org/schema/mule/core/2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.0"
xmlns:test="http://www.mulesource.org/schema/mule/test/2.0"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-2.5.xsd
http://www.mulesource.org/schema/mule/core/2.0 http://www.mulesource.org/schema/mule/core/2.0/
mule.xsd
http://www.mulesource.org/schema/mule/test/2.0 http://www.mulesource.org/schema/mule/test/2.0/mule-
test.xsd
http://www.mulesource.org/schema/mule/vm/2.0 http://www.mulesource.org/schema/mule/vm/2.0/mule-
vm.xsd">

<vm:connector name="asynchVm" queueEvents="true"/>


<model>
<service name="myAsynchService">
<inbound>
<vm:inbound-endpoint path="in" connector-ref="asynchVm"/>
</inbound>

<test:component>
<test:return-data>Polo</test:return-data>
</test:component>

<outbound>
<outbound-pass-through-router>
<vm:outbound-endpoint path="out" connector-ref="asynchVm"/>
</outbound-pass-through-router>
</outbound>
</service>
</model>
</mule>

Notice that the inbound endpoint explicitly tells Mule to use the asynchVm connector. Otherwise, Mule will
look for the first connector that matches the protocol for the endpoint.

Using Persistent Queues

A VM queue can be made persistent so that its state can be maintained between server shutdowns. To
make VM queues persistent, you enable the persistent property in the queue profile on the model or
service. For more information, see Tuning Performance.

Using Transactions

VM queues can take part in distributed XA transactions. To make a VM endpoint transactional, use the
following configuration:

<inbound>
<vm:inbound-endpoint address="vm://dispatchInQueue" connector-ref="vmQueue">
<vm:transaction action="BEGIN_OR_JOIN"/>
</vm:inbound-endpoint>
</inbound>

You must add a transaction manager to your configuration. For more information, see Transaction
Management.

Transformers
There are no specific transformers for the VM transport.

Document generated by Confluence on Oct 27, 2008 21:07 Page 165


WSDL Transport

This page last changed on Oct 07, 2008 by jackie.wheeler.

WSDL Transport
[ Generic WSDL Endpoints ] [ Transformers ] [ Specifying an Alternate WSDL Location ] [ Example of the
CXF WSDL Endpoint ]

The WSDL transport can be used to for invoking remote web services by obtaining the service WSDL.
Mule will create a dynamic proxy for the service and then invoke it.

The Javadoc for this transport can be found here for the Axis version and here for the CXF version.

Generic WSDL Endpoints


A WSDL endpoint enables you to easily invoke web services without generating a client. At startup, it
reads the WSDL to determine how to invoke the remote web service during runtime. When a message is
sent through the WSDL endpoint, it is able to construct a SOAP message using the message payload and
its knowledge of the expected payload format from the WSDL.

You must provide the full URL to the WSDL of the service to invoke, and you must supply a 'method'
parameter that tells Mule which operation to invoke on the service:

wsdl:http://www.webservicex.net/stockquote.asmx?WSDL&method=GetQuote

The WSDL URL is prepended with the wsdl: prefix. Mule checks your class path to see if there is a WSDL
provider that it can use to create a client proxy from the WSDL. Mule supports both Axis and CXF as
WSDL providers. If you want to use a specific one, you can specify it on the URL as follows:

wsdl-cxf:http://www.webservicex.net/stockquote.asmx?WSDL&method=GetQuote

or

wsdl-axis:http://www.webservicex.net/stockquote.asmx?WSDL&method=GetQuote

In general, you should use the CXF WSDL endpoint. The one limitation of the CXF WSDL provider is
that it does not allow you to use non-Java primitives (objects that are not a String, int, double, and so
on). Sometimes the Axis WSDL generation will not work (incorrect namespaces are used), so you can
experiment with each one to see which works best.

Transformers
There are no specific transformers to set on WSDL endpoints.

Specifying an Alternate WSDL Location


By default, the WSDL provider will look for your WSDL by taking the endpoint address and appending
?wsdl to it. With the CXF transport, you have the option of specifying a location for the WSDL that is
different from that specified with the ?wsdl parameter. This may be useful in cases where the WSDL isn't
available the normal way, either because the SOAP engine doesn't provide it or the provider does not
want to expose the WSDL publicly.

In these cases, you can specify the wsdlLocation property of the CXF endpoint as follows:

<endpoint
address="wsdl-cxf:http://localhost:8080/book/services/BookService?method=getBooks">
<properties>
<property name="wsdlLocation" value="file:///c:/BookService.wsdl"/>
</properties>
</endpoint>

Document generated by Confluence on Oct 27, 2008 21:07 Page 166


In this case, the WSDL CXF endpoint works as it normally does, except that it reads the WSDL from the
local drive.

Example of the CXF WSDL Endpoint


This example demonstrates how to take multiple arguments from the console, invoke a web service, and
print the output to the screen. It uses the Currency Convertor web service on www.webservicex.net.

This service requires two arguments: the "from" currency code and the "to" currency code. When the CXF
dispatcher prepares arguments for the invocation of the service, it expects to find a message payload of
Object[] - that is, an Object array. In the case of the Currency Convertor, this should be an array of two
Objects - the "from" currency and the "to" currency.

There are several ways to construct this object array, but the easiest way is to use the custom
transformer StringToObjectArrayTransformer , which translates a delimited String into an Object array. In
the example below, you simply type in a String in the format of <fromCurrency>,<toCurrency>.

<?xml version="1.0" encoding="UTF-8"?>


<mule xmlns="http://www.mulesource.org/schema/mule/core/2.1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:spring="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-
context-2.5.xsd
http://www.mulesource.org/schema/mule/core/2.1 http://www.mulesource.org/schema/mule/core/2.1/
mule.xsd">

<model name="sample">

<service name="inputService">
<inbound>
<inbound-endpoint address="stdio://System.in?promptMessage=Enter from and to currency symbols,
separated by a comma:"
synchronous="true">
<transformers>
<!-- Convert the input to an object array -->
<custom-transformer class="org.mule.transformer.simple.StringToObjectArray">
<spring:property name="delimiter" value=","/>
</custom-transformer>
</transformers>
</inbound-endpoint>
</inbound>
<outbound>
<chaining-router>
<outbound-endpoint address="wsdl-cxf:http://www.webservicex.net/CurrenyConvertor.asmx?
WSDL&amp;method=ConversionRate"
synchronous="true"/>
<outbound-endpoint address="stdio://System.out"/>
</chaining-router>
</outbound>
</service>
</model>
</mule>

For example, type "EUR,USD" to get the conversion rate for Euros to US Dollars, and you'll get something
like this:

Enter from and to currency symbols, separated by a comma:


EUR,USD
1.3606

Document generated by Confluence on Oct 27, 2008 21:07 Page 167


XMPP Transport

This page last changed on Oct 21, 2008 by jackie.wheeler.

XMPP Transport
The XMPP transport enables the XMPP (Jabber) instant messaging protocol. The XMPPS connector
provides a secure implementation.

The Javadoc for the XMPP transport can be found here .

Inbound Endpoint

Attributes of <inbound-endpoint...>

Name Type Required Default Description

user string no

password string no

host string no

port port number no

recipient string no

groupChat boolean no

nickname string no

resource string no

thread string no

to string no

from string no

Outbound Endpoint

Attributes of <outbound-endpoint...>

Name Type Required Default Description

user string no

password string no

host string no

port port number no

recipient string no

Document generated by Confluence on Oct 27, 2008 21:07 Page 168


groupChat boolean no

nickname string no

resource string no

thread string no

to string no

from string no

Endpoint

Attributes of <endpoint...>

Name Type Required Default Description

user string no

password string no

host string no

port port number no

recipient string no

groupChat boolean no

nickname string no

resource string no

thread string no

to string no

from string no

You configure the XMPP connector as follows:

<?xml version="1.0" encoding="UTF-8"?>


<mule xmlns="http://www.mulesource.org/schema/mule/core/2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:xmpp="http://www.mulesource.org/schema/mule/xmpp/2.0"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-2.5.xsd
http://www.mulesource.org/schema/mule/core/2.0 http://www.mulesource.org/schema/mule/core/2.0/
mule.xsd
http://www.mulesource.org/schema/mule/xmpp/2.0 http://www.mulesource.org/schema/mule/xmpp/2.0/mule-
xmpp.xsd">

<xmpp:endpoint name="noNicknameEndpoint" host="localhost" port="1234" user="mule" password="secret"


recipient="recipient" groupChat="true"/>

</mule>

Document generated by Confluence on Oct 27, 2008 21:07 Page 169


If you want to use secure XMPP, specify the xmpps namespace instead, specifying the schema as follows,
and then use the xmpps prefix on the endpoints:

http://www.mulesource.org/schema/mule/xmpps/2.0 http://www.mulesource.org/schema/mule/xmpps/2.0/
mule-xmpps.xsd

Transformers
There are two transformers provided with the XMPP transport:

Transformer Description

org.mule.transport.xmpp.transformers.XmppPacketToString
Converts an XMPP Packet to a String, returning a
java.lang.String object.

org.mule.transport.xmpp.transformers.ObjectToXmppPacket
Accepts a String or an XMPP Packet and returns
an XMPP Packet. This transformer doesn't accept
all objects, only Strings and XMPP Packets.

Document generated by Confluence on Oct 27, 2008 21:07 Page 170


Choosing the Right Topology

This page last changed on Jul 01, 2008 by jackie.wheeler.

Choosing the Right Topology


This page is under construction

As you build your Mule application, it is important to think critically about how best to architect your
application to achieve the desired availability, fault tolerance, and performance characteristics. This page
outlines some of the solutions for achieving the right blend of these characteristics through clustering
and other techniques. There is no one correct approach for everyone, and designing your system is both
an art and a science. If you need more assistance, MuleSource Professional Services can help you by
reviewing your architecture plan or designing it for you. For more information, contact us.

About Clustering
Clustering an application is useful for achieving the following:

• High availability (HA): Making your system continually available in the event that one or more
servers or a data center fails.
• Fault tolerance (FT): The ability to recover from failure of an underlying component. Typically, the
recovery is achieved through transaction rollback or compensating actions.

This page describes several possible clustering solutions. Please note that as of the current release,
MuleSource does not support any specific clustering solution, although many users have successfully set
up Mule in a clustered environment.

JMS Queues
JMS can be used to achieve HA & FT by routing messages through JMS queues. In this case, each
message is routed through a JMS queue whenever it moves from component to component.

Pros:

• Easy to do
• Well understood by developers

Cons:

• Requires lots of transactions, and transactions can be complicated


• Performance hit if you're using XA

Load Balancers
Load balancers simply route requests to different servers based on the the current load of each server
and which servers are currently up. Load balancers can be software or hardware based. This approach is
commonly used with clustered databases (see below).

Document generated by Confluence on Oct 27, 2008 21:07 Page 171


Pros:

• Straightforward to do
• Well understood by developers

Cons:

• Not a complete solution on its own, doesn't provide fault tolerance.

Maintaining State in a Database


If you have a clustered database, one option for your application is to simply store all state in the
database and rely on it to replicate the data consistently across servers.

Pros:

• Straightforward to do
• Well understood by developers

Cons:

• Not all state is amenable to being stored in the database

Handling Stateful Components


While most applications can be supported by the above techniques, some require sharing state between
JVMs more deeply.

One common example of this is an aggregator component. For example, assume you have an aggregator
that is aggregating messages from two different producers. Producer #1 sends a message to the
aggregator, which receives it and holds it in memory until Producer #2 sends a message.

Producer #1 ---> |----------|


|Aggregator| --> Some other component
Producer #2 ---> |----------|

If the server with the aggregator goes down between Producer #1 sending a message and Producer #2
sending a message, Producer #2 can't just send its message to a different server because that server will
not have the message from Producer #1.

The solution to this is to share the state of the aggregator component across different machines through
clustering software such as Terracotta, Tangosol Coherence, JGroups, etc. By using one of these tools,
Producer #2 can simply fail over to a different server. Note that MuleSource has not tested Mule with
these tools and does not officially support them.

Pros:

• Works for all clustering cases


• Can work as a cache as well

Cons:

• Not officially supported by MuleSource


• Requires performance tuning to get things working efficiently

Example Architectures

HTTP + JMS Queues

In this example architecture, HTTP requests come in through a load balancer and are immediately put on
a JMS queue. The JMS queue is clustered between the different servers. A server will start processing a
message off the JMS queue and wrap everything in a transaction.

Document generated by Confluence on Oct 27, 2008 21:07 Page 172


If the server goes down, the transaction will roll back and another server will pick up the message and
start processing it.

Note: If the HTTP connection is open for the duration of this process, this approach will not work, as the
load balancer will not transparently switch connections between servers. In this case, the HTTP client will
need to retry the request.

Terracotta

Terracotta is an open source JVM clustering technology. It is able to replicate the state of your
components across JVMs. In this example architecture, there is a load balancer that is proxying requests
between multiple servers.

If one of the servers goes down, the load balancer automatically routes requests to a server that is up.
Because all the state of your components is shared between the different servers, your internal process
can continue on another server.

Note: If the HTTP connection is open for the duration of this process, this approach will not work, as the
load balancer will not transparently switch connections between servers. In this case, the HTTP client will
need to retry the request.

Related topics
There are many other topics that are important to discuss around clustering:

• Maintaining geo-distributed clusters

Document generated by Confluence on Oct 27, 2008 21:07 Page 173


• Data partitioning
• ACID vs. BASE transactions
• Compensation and transactions

Document generated by Confluence on Oct 27, 2008 21:07 Page 174


Configuration Overview

This page last changed on Oct 16, 2008 by jackie.wheeler.

Configuration Overview
[ Configuration Files ] [ Configuration Builders ] [ Accessing the Configuration Programmatically ]

By default, Mule starts up with a simple configuration in which only some system-level services are
configured. You must configure services, transports, and the rest of the elements required for your
application. Following is an overview of configuration in Mule.

Configuration Files
In most cases, you will configure Mule using XML files. These files are based on Spring and make it very
easy to set up your Mule instance in a short time. For complete information on setting the options in the
configuration file, see XML Configuration.

When you start Mule from the command line, you simply specify the configuration file(s) with the -
config parameter:

mule -config foo-config.xml

mule -config foo-config.xml,bar-config.xml

If you want to start Mule by calling it from your code, you specify the configuration file as a parameter to
the ConfigurationBuilder:

MuleContext context = new DefaultMuleContextFactory().createMuleContext(new


SpringXmlConfigurationBuilder("foo-config.xml"));
context.start();

If you have multiple configuration files, you can also import them into one configuration file so that you
only have to specify one configuration file at the command line or from your code. For example:

<?xml version="1.0" encoding="UTF-8"?>


<mule xmlns=http://www.mulesource.org/schema/mule/core/2.0 ....>
<spring:beans>
<spring:import resource="mule-sub-config1.xml" />
<spring:import resource="mule-sub-config2.xml" />
</spring:beans>
...

Configuration Builders
The configuration builder is responsible for creating the configuration that's used at run time from the
configuration files you provide. Mule provides two standard configuration builders, or you can create your
own.

SpringXmlConfigurationBuilder

The default configuration builder used to configure Mule is the SpringXmlConfigurationBuilder. This
configuration builder uses Spring 2.0 to configure Mule based on one or more XML files leveraging custom
Mule namespaces. For more information, see XML Configuration.

ScriptConfigurationBuilder

This configuration builder allows a JSR-223 compliant script engine (e.g., Groovy, Jython) to configure
Mule. For more information, see Scripting Module.

Document generated by Confluence on Oct 27, 2008 21:07 Page 175


Custom Configuration Builders

You can easily create your own custom configuration builder by implementing the ConfigurationBuilder
interface, which has a method configure. Typically, you call configure(MuleContext
muleContext.getRegistry()) to get access to Mule's internal registry, which contains the configuration
information, and to register services and other elements.

In most cases, you will want to inherit from the class AbstractResourceConfigurationBuilder , which
will make any configuration files specified on the command line available in an instance variable called
configResources.

Specifying the Configuration Builder

SpringXmlConfigurationBuilder is the default configuration builder. If you want to use another


configuration builder, you can specify it on the command line at startup with the -builder parameter:

mule -builder org.mule.module.scripting.builders.ScriptConfigurationBuilder -config mule-


config.groovy

You can also specify the configuration builder as a parameter to the MuleContextFactory when starting
Mule programatically:

MuleContext context = new DefaultMuleContextFactory().createMuleContext(new


ScriptConfigurationBuilder("mule-config.groovy"));
context.start();

Accessing the Configuration Programmatically


All Mule configuration is accessible from a single object: org.mule.api.config.MuleConfiguration .
Configurations in a MuleConfiguration are set when a MuleContext is created. The object becomes
immutable after it is started and can be accessed using the following:

MuleContext context = MuleServer.getMuleContext();


MuleConfiguration configuration = context.getConfiguration();

Document generated by Confluence on Oct 27, 2008 21:07 Page 176


Configuration Reference

This page last changed on Oct 10, 2008 by jackie.wheeler.

Configuration Reference
• Global Settings Configuration Reference
• Model Configuration Reference
• Service Configuration Reference
• Endpoint Configuration Reference
• Routers
° Inbound Router Configuration Reference
° Outbound Router Configuration Reference
° Asynchronous Reply Router Configuration Reference
° Catch All Strategy Configuration Reference

• Filters Configuration Reference


• Transformers Configuration Reference
• Component Configuration Reference
• Entry Point Resolver Configuration Reference
• Exception Strategy Configuration Reference
• Properties Configuration Reference
• Notifications Configuration Reference
• Transactions Configuration Reference

For configuration reference on transports, see Available Transports. For modules, see Using Mule Modules.

For transports and modules contributed by the community, see MuleForge Active Projects.

Document generated by Confluence on Oct 27, 2008 21:07 Page 177


Asynchronous Reply Router Configuration Reference

This page last changed on Oct 22, 2008 by jackie.wheeler.

Asynchronous Reply Router Configuration


Reference
This page provides details on the elements you configure for asynchronous reply routers. This information
is pulled directly from mule.xsd and is cached. If the information appears to be out of date, refresh the
page. For more information on routers, see Using Message Routers.

<single-async-reply-router ...>
Configures a Single Response Router. This will return the first message it receives on a reply endpoint and
will discard the rest.

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

abstract-inbound- 0..* A placeholder for


endpoint inbound endpoint
elements. Inbound
endpoints receive
messages from
the underlying
transport. The
message payload
is then delivered
to the component
for processing.

abstract-message- 0..1 Maps the


info-mapping attributes of the
current message
to known message
elements in Mule;
namely, Message
ID, CorrrelationID.

<collection-async-reply-router ...>
Configures a Collection Response Router. This will return a MuleMessageCollection message type that will
contain all messages received for the current correlation.

Document generated by Confluence on Oct 27, 2008 21:07 Page 178


Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

abstract-inbound- 0..* A placeholder for


endpoint inbound endpoint
elements. Inbound
endpoints receive
messages from
the underlying
transport. The
message payload
is then delivered
to the component
for processing.

abstract-message- 0..1 Maps the


info-mapping attributes of the
current message
to known message
elements in Mule;
namely, Message
ID, CorrrelationID.

<custom-async-reply-router ...>

Attributes

Name Type Required Default Description

class class name no

Child Elements

Name Cardinality Description

abstract-inbound-endpoint 0..* A placeholder for inbound


endpoint elements. Inbound
endpoints receive messages
from the underlying transport.
The message payload is then
delivered to the component for
processing.

abstract-message-info-mapping 0..1 Maps the attributes of


the current message to
known message elements in
Mule; namely, Message ID,
CorrrelationID.

spring:property 0..*

Document generated by Confluence on Oct 27, 2008 21:07 Page 179


Catch All Strategy Configuration Reference

This page last changed on Oct 22, 2008 by jackie.wheeler.

Catch All Strategy Configuration Reference


This page provides details on the elements you configure for catch-all strategies. This information is
pulled directly from mule.xsd and is cached. If the information appears to be out of date, refresh the
page.

<logging-catch-all-strategy ...>
Does nothing with the message but simply logs (using the WARN log level) the fact that the message was
not dispatched because no routing path was defined.

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

<custom-catch-all-strategy ...>

Attributes

Name Type Required Default Description

class class name no

Child Elements

Name Cardinality Description

spring:property 0..*

<forwarding-catch-all-strategy ...>
Forwards the message to the specified endpoint if no outbound routers match.

Document generated by Confluence on Oct 27, 2008 21:07 Page 180


Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

abstract- 0..* A placeholder for


outbound- outbound endpoint
endpoint elements.
Outbound
endpoints dispatch
messages to
the underlying
transport.

<custom-forwarding-catch-all-strategy ...>

Attributes

Name Type Required Default Description

class class name no

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 0..* A placeholder for outbound


endpoint elements. Outbound
endpoints dispatch messages to
the underlying transport.

spring:property 0..*

Document generated by Confluence on Oct 27, 2008 21:07 Page 181


Component Configuration Reference

This page last changed on Oct 22, 2008 by jackie.wheeler.

Component Configuration Reference


This page provides details on the elements you configure for components. This information is pulled
directly from mule.xsd and is cached. If the information appears to be out of date, refresh the page. For
more information on components, see Configuring Components.

<component ...>
A simple POJO (Plain Old Java Object) component that will be invoked by Mule when a message is
received. The instance can be specified via a factory, or via a class.

Attributes

Name Type Required Default Description

class class name no Specify a


component class.
This is a shortcut
that is equivalent
to providing a
prototype-object
element.

Child Elements

Name Cardinality Description

abstract-interceptor 1..1 A placeholder for an interceptor


element.

interceptor-stack 1..1

abstract-object-factory 0..1

abstract-lifecycle-adapter- 0..1
factory

binding 0..* A binding associates a Mule


endpoint with an injected Java
interface. This is like using
Spring to inject a bean, but
instead of calling a method on
the bean a message is sent to
an endpoint.

abstract-entry-point-resolver-set 0..1 A placeholder for entry point


resolver set elements. These
combine a group of entry point
resolvers, trying them in turn
until one succeeds.

Document generated by Confluence on Oct 27, 2008 21:07 Page 182


abstract-entry-point-resolver 0..1 A placeholder for an entry point
resolver element. Entry point
resolvers define how payloads
are delivered to Java code by
choosing the method to call.

<pooled-component ...>
A pooled POJO (Plain Old Java Object) component that will be invoked by Mule when a message is
received. The instance can be specified via a factory, or via a class.

Attributes

Name Type Required Default Description

class class name no Specify a


component class.
This is a shortcut
that is equivalent
to providing a
prototype-object
element.

Child Elements

Name Cardinality Description

abstract-interceptor 1..1 A placeholder for an interceptor


element.

interceptor-stack 1..1

abstract-object-factory 0..1

abstract-lifecycle-adapter- 0..1
factory

binding 0..* A binding associates a Mule


endpoint with an injected Java
interface. This is like using
Spring to inject a bean, but
instead of calling a method on
the bean a message is sent to
an endpoint.

abstract-entry-point-resolver-set 0..1 A placeholder for entry point


resolver set elements. These
combine a group of entry point
resolvers, trying them in turn
until one succeeds.

abstract-entry-point-resolver 0..1 A placeholder for an entry point


resolver element. Entry point
resolvers define how payloads
are delivered to Java code by
choosing the method to call.

Document generated by Confluence on Oct 27, 2008 21:07 Page 183


abstract-pooling-profile 0..1 Characteristics of the object pool

<pooling-profile ...>
A pooling profile is used to configure the pooling behaviour of Mule components. Each service sets its own
pooling profile. The org.mule.config.PoolingProfile class contains all the necessary values to create a pool
of component proxies.

Attributes

Name Type Required Default Description

maxActive string no Controls the


maximum
number of Mule
components that
can be borrowed
from a session
at one time.
When set to a
negative value,
there is no limit
to the number of
components that
may be active at
one time. When
maxActive is
exceeded, the
pool is said to be
exhausted.

maxIdle string no Controls the


maximum
number of Mule
components that
can sit idle in the
pool at any time.
When set to a
negative value,
there is no limit
to the number of
Mule components
that may be idle
at one time.

initialisationPolicy INITIALISE_NONE no INITIALISE_ONE Determines how


/ components in
INITIALISE_ONE a pool should
/ be initialized.
INITIALISE_ALL The possible
values are:
INITIALISE_NONE
(will not load
any components
into the pool
on startup),
INITIALISE_ONE
(will load one
initial component
into the pool

Document generated by Confluence on Oct 27, 2008 21:07 Page 184


on startup), or
INITIALISE_ALL
(will load all
components in the
pool on startup)

exhaustedActionWHEN_EXHAUSTED_GROW no WHEN_EXHAUSTED_GROW
Specifies the
/ behavior of the
WHEN_EXHAUSTED_WAIT Mule component
/ pool when the
WHEN_EXHAUSTED_FAIL pool is exhausted.
Possible
values are:
"WHEN_EXHAUSTED_FAIL",
which will throw a
NoSuchElementException,
"WHEN_EXHAUSTED_WAIT",
which will
block (invoke
Object.wait(long))
until a new or
idle object is
available, or
WHEN_EXHAUSTED_GROW,
which will create
a new Mule
and return
it, essentially
making maxActive
meaningless. If a
positive maxWait
value is supplied,
it will block for at
most that many
milliseconds,
after which a
NoSuchElementException
will be thrown. If
maxThreadWait
is a negative
value, it will block
indefinitely.

maxWait string no Specifies the


number of
milliseconds to
wait for a pooled
component to
become available
when the pool is
exhausted and the
exhaustedAction
is set to
WHEN_EXHAUSTED_BLOCK.

Document generated by Confluence on Oct 27, 2008 21:07 Page 185


Child Elements

Name Cardinality Description

<bridge-component ...>
This transfers a message from inbound to outbound endpoints. This name is provided for backwards
compatability - it is equivalent to not specifying any component.

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

abstract- 1..1 A placeholder for


interceptor an interceptor
element.

interceptor-stack 1..1

<echo-component ...>
This logs the message and returns the payload back as the result.

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

abstract- 1..1 A placeholder for


interceptor an interceptor
element.

interceptor-stack 1..1

<log-component ...>
This logs the message content (or content length if it is a large message).

Document generated by Confluence on Oct 27, 2008 21:07 Page 186


Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

abstract- 1..1 A placeholder for


interceptor an interceptor
element.

interceptor-stack 1..1

<null-component ...>
This will throw an exception if it receives a message.

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

abstract- 1..1 A placeholder for


interceptor an interceptor
element.

interceptor-stack 1..1

<spring-object ...>

Attributes

Name Type Required Default Description

bean name (no spaces) no Name of Spring


bean to look up.

Child Elements

Name Cardinality Description

property 0..* Sets a Mule property. This is a


name/value pair that can be set
on components, services, etc.,
and which provide a generic way
of configuring the system. In
Mule 2.x, you shouldn't need to

Document generated by Confluence on Oct 27, 2008 21:07 Page 187


use a generic property like this,
since almost all functionality
is exposed via dedicated
elements. However, it can be
useful in configuring obscure
or overlooked options and in
configuring transports from the
generic endpoint elements.

properties 0..1 Sets Mule properties. These


are name/value pairs that
can be set on components,
services, etc., and which provide
a generic way of configuring
the system. In Mule 2.x, you
shouldn't need to use generic
properties like this, since almost
all functionality is exposed via
dedicated elements. However,
they can be useful in configuring
obscure or overlooked options
and in configuring transports
from the generic endpoint
elements.

<singleton-object ...>

Attributes

Name Type Required Default Description

class class name no Class name

Child Elements

Name Cardinality Description

property 0..* Sets a Mule property. This is a


name/value pair that can be set
on components, services, etc.,
and which provide a generic way
of configuring the system. In
Mule 2.x, you shouldn't need to
use a generic property like this,
since almost all functionality
is exposed via dedicated
elements. However, it can be
useful in configuring obscure
or overlooked options and in
configuring transports from the
generic endpoint elements.

properties 0..1 Sets Mule properties. These


are name/value pairs that
can be set on components,
services, etc., and which provide
a generic way of configuring
the system. In Mule 2.x, you

Document generated by Confluence on Oct 27, 2008 21:07 Page 188


shouldn't need to use generic
properties like this, since almost
all functionality is exposed via
dedicated elements. However,
they can be useful in configuring
obscure or overlooked options
and in configuring transports
from the generic endpoint
elements.

<prototype-object ...>

Attributes

Name Type Required Default Description

class class name no Class name

Child Elements

Name Cardinality Description

property 0..* Sets a Mule property. This is a


name/value pair that can be set
on components, services, etc.,
and which provide a generic way
of configuring the system. In
Mule 2.x, you shouldn't need to
use a generic property like this,
since almost all functionality
is exposed via dedicated
elements. However, it can be
useful in configuring obscure
or overlooked options and in
configuring transports from the
generic endpoint elements.

properties 0..1 Sets Mule properties. These


are name/value pairs that
can be set on components,
services, etc., and which provide
a generic way of configuring
the system. In Mule 2.x, you
shouldn't need to use generic
properties like this, since almost
all functionality is exposed via
dedicated elements. However,
they can be useful in configuring
obscure or overlooked options
and in configuring transports
from the generic endpoint
elements.

Document generated by Confluence on Oct 27, 2008 21:07 Page 189


<interceptor-stack ...>

Attributes

Name Type Required Default Description

name name no The name used


to identify this
interceptor stack.

Child Elements

Name Cardinality Description

abstract-interceptor 1..1 A placeholder for an interceptor


element.

<interceptor-stack ...>

Attributes

Name Type Required Default Description

ref name (no spaces) no The name of the


interceptor stack
to use.

Child Elements

Name Cardinality Description

<timer-interceptor ...>
The timer interceptor (ported from 1.x).

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

<logging-interceptor ...>
The logging interceptor (ported from 1.x).

Document generated by Confluence on Oct 27, 2008 21:07 Page 190


Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

<custom-interceptor ...>
A user-implemented interceptor.

Attributes

Name Type Required Default Description

class class name no An


implementation
of the Interceptor
interface.

Child Elements

Name Cardinality Description

spring:property 0..*

<custom-lifecycle-adapter-factory ...>

Attributes

Name Type Required Default Description

class class name no An


implementation
of the
LifecycleAdapter
interface.

Child Elements

Name Cardinality Description

<binding ...>
A binding associates a Mule endpoint with an injected Java interface. This is like using Spring to inject a
bean, but instead of calling a method on the bean a message is sent to an endpoint.

Document generated by Confluence on Oct 27, 2008 21:07 Page 191


Attributes

Name Type Required Default Description

interface class name no The interface


to be injected.
A proxy will be
created that
implements this
interface by
calling out to the
endpoint.

method no The method on


the interface
that should be
used. This can
be omitted if the
interface has a
single method.

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 1..* A placeholder for outbound


endpoint elements. Outbound
endpoints dispatch messages to
the underlying transport.

Entry Point Resolvers


See Entry Point Resolver Configuration Reference.

Document generated by Confluence on Oct 27, 2008 21:07 Page 192


Endpoint Configuration Reference

This page last changed on Oct 22, 2008 by jackie.wheeler.

Endpoint Configuration Reference


This page provides details on the elements you configure for endpoints. This information is pulled directly
from mule.xsd and is cached. If the information appears to be out of date, refresh the page. For more
information on endpoints, see Configuring Endpoints.

<inbound-endpoint ...>
An inbound endpoint receives messages from the associated transport. Each transport implements its
own inbound endpoint element, with a more friendly syntax, but this generic element can be used with
any transport by supplying the correct address URI. For example, "vm://foo" describes a VM transport
endpoint.

Attributes

Name Type Required Default Description

name name (no spaces) no Identifies the


inbound endpoint
in the registry,
but is of relatively
little use -
it cannot be
referred to from
MuleClient, for
example. For
more useful
aliases, use global
endpoints.

ref name (no spaces) no A reference to a


global endpoint.
If this attribute
is used then the
endpoint is used
as a template
to construct
this endpoint. A
template fixes the
address (protocol,
path, host, etc.),
and may specify
initial values for
various properties,
but further
properties can be
defined locally (as
long as they do
not change the
address in any
way).

address string no The generic


address for this
endpoint. If this

Document generated by Confluence on Oct 27, 2008 21:07 Page 193


attribute is used,
the protocol must
be specified as
part of the URI.
Alternatively,
most transports
provide their own
attributes for
specifying the
address (path,
host, etc.). Note
that the address
attribute cannot
be combined with
"ref" or with the
transport-provided
alternative
attributes.

synchronous boolean no If true, the


result from the
component
processing the
incoming message
will be returned as
a response.

remoteSync boolean no If true, the


component
will wait for a
response to the
outgoing message
before replying
to the incoming
message.

remoteSyncTimeout integer no The timeout for


the remoteSync
wait (ms).

encoding string no String encoding


used for
messages.

connector-ref name (no spaces) no The name of


the connector
associated with
this endpoint. This
must be specified
if more than
one connector is
defined for this
transport.

transformer-refs list of names no A list of the


transformers that
will be applied to
the message in
order before it is
delivered to the
component.

responseTransformer- list of names no A list of the


refs transformers that

Document generated by Confluence on Oct 27, 2008 21:07 Page 194


will be applied to
the synchronous
response in
order before it is
returned via the
transport.

Child Elements

Name Cardinality Description

abstract-transaction 0..1 A placeholder for transaction


elements. Transactions allow
a series of operations to be
grouped together.

abstract-filter 0..1 A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

abstract-security-filter 0..1 A placeholder for security filter


elements. Security filters can
control access to the system,
etc.

abstract-retry-policy 0..1 A placeholder for a retry policy


element. Retry policies define
how Mule should retry a failed
message send/dispatch/request.

abstract-transformer 0..* A placeholder for transformer


elements. Transformers convert
message payloads.

transformers 0..1 A list of transformer elements


that will be applied to the
message before it is delivered
to the component. Note that
a list of transformers can
also be specified directly
(without the "transformers"
element), but then it is
not possible to also specify
response transformers (using
the "response-transformers"
element).

response-transformers 0..1 A list of transformer elements


that will be applied to the
response message returned
from the component.

property 0..* Sets a Mule property. This is a


name/value pair that can be set
on components, services, etc.,
and which provide a generic way
of configuring the system. In
Mule 2.x, you shouldn't need to
use a generic property like this,
since almost all functionality
is exposed via dedicated

Document generated by Confluence on Oct 27, 2008 21:07 Page 195


elements. However, it can be
useful in configuring obscure
or overlooked options and in
configuring transports from the
generic endpoint elements.

properties 0..1 Sets Mule properties. These


are name/value pairs that
can be set on components,
services, etc., and which provide
a generic way of configuring
the system. In Mule 2.x, you
shouldn't need to use generic
properties like this, since almost
all functionality is exposed via
dedicated elements. However,
they can be useful in configuring
obscure or overlooked options
and in configuring transports
from the generic endpoint
elements.

<outbound-endpoint ...>
An outbound endpoint sends messages to the associated transport. Each transport implements its own
outbound endpoint element, with a more friendly syntax, but this generic element can be used with
any transport by supplying the correct address URI. For example, "vm://foo" describes a VM transport
endpoint.

Attributes

Name Type Required Default Description

name name (no spaces) no Identifies the


outbound endpoint
in the registry,
but is of relatively
little use -
it cannot be
referred to from
MuleClient, for
example. For
more useful
aliases, use global
endpoints.

ref name (no spaces) no A reference to a


global endpoint.
If this attribute
is used then the
endpoint is used
as a template
to construct
this endpoint. A
template fixes the
address (protocol,
path, host, etc.),
and may specify
initial values for
various properties,
but further

Document generated by Confluence on Oct 27, 2008 21:07 Page 196


properties can be
defined locally (as
long as they do
not change the
address in any
way).

address string no The generic


address for this
endpoint. If this
attribute is used,
the protocol must
be specified as
part of the URI.
Alternatively,
most transports
provide their own
attributes for
specifying the
address (path,
host, etc.). Note
that the address
attribute cannot
be combined with
"ref" or with the
transport-provided
alternative
attributes.

synchronous boolean no If true, the


result from the
component
processing the
incoming message
will be returned as
a response.

remoteSync boolean no If true, the


component
will wait for a
response to the
outgoing message
before replying
to the incoming
message.

remoteSyncTimeout integer no The timeout for


the remoteSync
wait (ms).

encoding string no String encoding


used for
messages.

connector-ref name (no spaces) no The name of


the connector
associated with
this endpoint. This
must be specified
if more than
one connector is
defined for this
transport.

Document generated by Confluence on Oct 27, 2008 21:07 Page 197


transformer-refs list of names no A list of the
transformers that
will be applied to
the message in
order before it is
delivered to the
component.

responseTransformer- list of names no A list of the


refs transformers that
will be applied to
the synchronous
response in
order before it is
returned via the
transport.

Child Elements

Name Cardinality Description

abstract-transaction 0..1 A placeholder for transaction


elements. Transactions allow
a series of operations to be
grouped together.

abstract-filter 0..1 A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

abstract-security-filter 0..1 A placeholder for security filter


elements. Security filters can
control access to the system,
etc.

abstract-retry-policy 0..1 A placeholder for a retry policy


element. Retry policies define
how Mule should retry a failed
message send/dispatch/request.

abstract-transformer 0..* A placeholder for transformer


elements. Transformers convert
message payloads.

transformers 0..1 A list of transformer elements


that will be applied to the
message before it is delivered
to the component. Note that
a list of transformers can
also be specified directly
(without the "transformers"
element), but then it is
not possible to also specify
response transformers (using
the "response-transformers"
element).

response-transformers 0..1 A list of transformer elements


that will be applied to the

Document generated by Confluence on Oct 27, 2008 21:07 Page 198


response message returned
from the component.

property 0..* Sets a Mule property. This is a


name/value pair that can be set
on components, services, etc.,
and which provide a generic way
of configuring the system. In
Mule 2.x, you shouldn't need to
use a generic property like this,
since almost all functionality
is exposed via dedicated
elements. However, it can be
useful in configuring obscure
or overlooked options and in
configuring transports from the
generic endpoint elements.

properties 0..1 Sets Mule properties. These


are name/value pairs that
can be set on components,
services, etc., and which provide
a generic way of configuring
the system. In Mule 2.x, you
shouldn't need to use generic
properties like this, since almost
all functionality is exposed via
dedicated elements. However,
they can be useful in configuring
obscure or overlooked options
and in configuring transports
from the generic endpoint
elements.

<endpoint ...>
An endpoint "template" that can be used to construct an inbound or outbound endpoint elsewhere in the
configuration by referencing the endpoint name. Each transport implements its own endpoint element,
with a more friendly syntax, but this generic element can be used with any transport by supplying the
correct address URI. For example, "vm://foo" describes a VM transport endpoint.

Attributes

Name Type Required Default Description

name name (no spaces) no Identifies the


endpoint so that
other elements
can reference it.
This name can
also be referenced
in MuleClient.

ref name (no spaces) no A reference to a


global endpoint.
If this attribute
is used then the
endpoint is used
as a template
to construct
this endpoint. A

Document generated by Confluence on Oct 27, 2008 21:07 Page 199


template fixes the
address (protocol,
path, host, etc.),
and may specify
initial values for
various properties,
but further
properties can be
defined locally (as
long as they do
not change the
address in any
way).

address string no The generic


address for this
endpoint. If this
attribute is used,
the protocol must
be specified as
part of the URI.
Alternatively,
most transports
provide their own
attributes for
specifying the
address (path,
host, etc.). Note
that the address
attribute cannot
be combined with
"ref" or with the
transport-provided
alternative
attributes.

synchronous boolean no If true, the


result from the
component
processing the
incoming message
will be returned as
a response.

remoteSync boolean no If true, the


component
will wait for a
response to the
outgoing message
before replying
to the incoming
message.

remoteSyncTimeout integer no The timeout for


the remoteSync
wait (ms).

encoding string no String encoding


used for
messages.

connector-ref name (no spaces) no The name of


the connector
associated with

Document generated by Confluence on Oct 27, 2008 21:07 Page 200


this endpoint. This
must be specified
if more than
one connector is
defined for this
transport.

transformer-refs list of names no A list of the


transformers that
will be applied to
the message in
order before it is
delivered to the
component.

responseTransformer- list of names no A list of the


refs transformers that
will be applied to
the synchronous
response in
order before it is
returned via the
transport.

Child Elements

Name Cardinality Description

abstract-transaction 0..1 A placeholder for transaction


elements. Transactions allow
a series of operations to be
grouped together.

abstract-filter 0..1 A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

abstract-security-filter 0..1 A placeholder for security filter


elements. Security filters can
control access to the system,
etc.

abstract-retry-policy 0..1 A placeholder for a retry policy


element. Retry policies define
how Mule should retry a failed
message send/dispatch/request.

abstract-transformer 0..* A placeholder for transformer


elements. Transformers convert
message payloads.

transformers 0..1 A list of transformer elements


that will be applied to the
message before it is delivered
to the component. Note that
a list of transformers can
also be specified directly
(without the "transformers"
element), but then it is
not possible to also specify
response transformers (using

Document generated by Confluence on Oct 27, 2008 21:07 Page 201


the "response-transformers"
element).

response-transformers 0..1 A list of transformer elements


that will be applied to the
response message returned
from the component.

property 0..* Sets a Mule property. This is a


name/value pair that can be set
on components, services, etc.,
and which provide a generic way
of configuring the system. In
Mule 2.x, you shouldn't need to
use a generic property like this,
since almost all functionality
is exposed via dedicated
elements. However, it can be
useful in configuring obscure
or overlooked options and in
configuring transports from the
generic endpoint elements.

properties 0..1 Sets Mule properties. These


are name/value pairs that
can be set on components,
services, etc., and which provide
a generic way of configuring
the system. In Mule 2.x, you
shouldn't need to use generic
properties like this, since almost
all functionality is exposed via
dedicated elements. However,
they can be useful in configuring
obscure or overlooked options
and in configuring transports
from the generic endpoint
elements.

Document generated by Confluence on Oct 27, 2008 21:07 Page 202


Exception Strategy Configuration Reference

This page last changed on Oct 22, 2008 by jackie.wheeler.

Exception Strategy Configuration Reference


This page provides details on the elements you configure for exception strategies. This information is
pulled directly from mule.xsd and is cached. If the information appears to be out of date, refresh the
page. For more information on exception strategies, see Error Handling.

<default-service-exception-strategy ...>
Provide default exception handling via an endpoint.

Attributes

Name Type Required Default Description

enableNotifications boolean no Determines


whether
ExceptionNotifications
wil be fired from
this strategy when
an exception
occurs.

Child Elements

Name Cardinality Description

commit-transaction 0..1 Defines when a current


transaction gets rolled-back
depending on the name of
the exception caught. Users
can set a comma delimited
list of wildcard patterns that
wil be matched angainst the
fully qualified classname of the
current exception. Patterns
defined for this element will
leave the current transaction (if
any) untouched and llow it to be
committed.

rollback-transaction 0..1 Defines when a current


transaction gets rolled-back
depending on the name of
the exception caught. Users
can set a comma delimited
list of wildcard patterns that
wil be matched angainst the
fully qualified classname of the
current exception. Patterns
defined for this element will
rollback the current transaction
(if any).

Document generated by Confluence on Oct 27, 2008 21:07 Page 203


abstract-outbound-endpoint 0..* A placeholder for outbound
endpoint elements. Outbound
endpoints dispatch messages to
the underlying transport.

<default-connector-exception-strategy ...>
Provide default exception handling via an endpoint.

Attributes

Name Type Required Default Description

enableNotifications boolean no Determines


whether
ExceptionNotifications
wil be fired from
this strategy when
an exception
occurs.

Child Elements

Name Cardinality Description

commit-transaction 0..1 Defines when a current


transaction gets rolled-back
depending on the name of
the exception caught. Users
can set a comma delimited
list of wildcard patterns that
wil be matched angainst the
fully qualified classname of the
current exception. Patterns
defined for this element will
leave the current transaction (if
any) untouched and llow it to be
committed.

rollback-transaction 0..1 Defines when a current


transaction gets rolled-back
depending on the name of
the exception caught. Users
can set a comma delimited
list of wildcard patterns that
wil be matched angainst the
fully qualified classname of the
current exception. Patterns
defined for this element will
rollback the current transaction
(if any).

abstract-outbound-endpoint 0..* A placeholder for outbound


endpoint elements. Outbound
endpoints dispatch messages to
the underlying transport.

Document generated by Confluence on Oct 27, 2008 21:07 Page 204


<custom-exception-strategy ...>
A user-defined exception stratgey.

Attributes

Name Type Required Default Description

enableNotifications boolean no Determines


whether
ExceptionNotifications
wil be fired from
this strategy when
an exception
occurs.

class class name no A class that


implements the
ExceptionListener
interface. In
addition, if
an outbound-
endpoint element
is specified,
it is set as an
"endpoint" bean
property.

Child Elements

Name Cardinality Description

commit-transaction 0..1 Defines when a current


transaction gets rolled-back
depending on the name of
the exception caught. Users
can set a comma delimited
list of wildcard patterns that
wil be matched angainst the
fully qualified classname of the
current exception. Patterns
defined for this element will
leave the current transaction (if
any) untouched and llow it to be
committed.

rollback-transaction 0..1 Defines when a current


transaction gets rolled-back
depending on the name of
the exception caught. Users
can set a comma delimited
list of wildcard patterns that
wil be matched angainst the
fully qualified classname of the
current exception. Patterns
defined for this element will
rollback the current transaction
(if any).

Document generated by Confluence on Oct 27, 2008 21:07 Page 205


abstract-outbound-endpoint 0..* A placeholder for outbound
endpoint elements. Outbound
endpoints dispatch messages to
the underlying transport.

spring:property 0..*

Document generated by Confluence on Oct 27, 2008 21:07 Page 206


Filters Configuration Reference

This page last changed on Oct 22, 2008 by jackie.wheeler.

Filters Configuration Reference


For more information on filters, see Using Filters.

[ Filter ] [ Not Filter ] [ And Filter ] [ Or Filter ] [ Wildcard Filter ] [ Expression Filter ] [ Regex Filter ] [
Message Property Filter ] [ Exception Type Filter ] [ Payload Type Filter ] [ Custom Filter ] [ Encryption
Security Filter ]

Filter
A filter that is defined elsewhere (at the global level, or as a Spring bean).

Attributes of <filter...>

Name Type Required Default Description

name name (no spaces) no Identifies the


filter so that
other elements
can reference it.
Required if the
filter is defined at
the global level.

not boolean no Inverts the filter


condition.

ref name (no spaces) no The name of the


filter to use.

Not Filter
Invert the enclosed filter (so if it returns true for some message, this will return false, and vice-versa).

Child Elements of <not-filter...>

Name Cardinality Description

abstract-filter 0..1 A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

And Filter
Return true only if all the enclosed filters return true.

Document generated by Confluence on Oct 27, 2008 21:07 Page 207


Child Elements of <and-filter...>

Name Cardinality Description

abstract-filter 2..* A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

Or Filter
Return true if any of the enclosed filters returns true.

Child Elements of <or-filter...>

Name Cardinality Description

abstract-filter 2..* A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

Wildcard Filter
A filter that matches string messages against wildcards. It performs matches with "", for example,
"jms.events." would catch "jms.events.customer" and "jms.events.receipts". This filter accepts a
comma-separated list of patterns, so more than one filter pattern can be matched for a given argument:
"jms.events., jms.actions." will match "jms.events.system" and "jms.actions" but not "jms.queue".

Expression Filter
A filter that can evaluate a range of expressions. It supports some base expression types such as header,
payload (payload type), regex, and wildcard.

Attributes of <expression-filter...>

Name Type Required Default Description

name name (no spaces) no Identifies the


filter so that
other elements
can reference it.
Required if the
filter is defined at
the global level.

not boolean no Inverts the filter


condition.

evaluator header/payload- no The expression


type/exception- evaluator
type/wildcard/ to use. The
regex/ognl/xpath/ expression filter
supports some

Document generated by Confluence on Oct 27, 2008 21:07 Page 208


jxpath/groovy/ types such as
bean/custom header, payload,
exception,
wildcard and
regex, that are
in-built filters
not registered
with the
ExpressionEvaluatorManager.
All others are
registered
with the
ExpressionEvaluatorManager.
Where XPath,
bean, and ONGL
are used, the
expression should
be a boolean
expression.

expression string no The expression


that will be
evaluated. This
should always
be a boolean
expression. The
syntax of the
expression will
be determined by
the expression
language being
used.

customEvaluator name (no spaces) no Must be set if


the evaluator is
set to custom.
The custom
evaluator must
be registered
with the
ExpressionEvaluatorManager
if it is to be used
here.

nullReturnsTrue boolean no Whether the filter


should return true
if the specified
expression returns
null.

Regex Filter
A filter that matches string messages against a regular expression. The Java regular expression engine
(java.util.regex.Pattern) is used.

Attributes of <regex-filter...>

Name Type Required Default Description

Document generated by Confluence on Oct 27, 2008 21:07 Page 209


name name (no spaces) no Identifies the
filter so that
other elements
can reference it.
Required if the
filter is defined at
the global level.

not boolean no Inverts the filter


condition.

pattern string no The property


name and possibly
value to use when
matching. If the
expression is just
a property name,
the filter will check
that the property
exists. Users can
also uses '=' and
'!=' to determine
a specific value for
a property.

Message Property Filter


A filter that matches properties on a message. This can be very useful as the message properties
represent all the meta information about the message from the underlying transport, so for a message
received over HTTP, you can check for HTTP headers and so forth. The pattern should be expressed as a
key/value pair, such as "propertyName=value". If you want to compare more than one property, you can
use the logic filters for And, Or, and Not expressions. By default the comparison is case sensitive, which
you can override with the caseSensitive property.

Attributes of <message-property-filter...>

Name Type Required Default Description

name name (no spaces) no Identifies the


filter so that
other elements
can reference it.
Required if the
filter is defined at
the global level.

not boolean no Inverts the filter


condition.

pattern string no The property


name and possibly
value to use when
matching. If the
expression is just
a property name,
the filter will check
that the property
exists. Users can
also uses '=' and
'!=' to determine

Document generated by Confluence on Oct 27, 2008 21:07 Page 210


a specific value for
a property.

caseSensitive boolean no true If false, the


comparison
ignores case.

Exception Type Filter


A filter that matches the type of an exception.

Attributes of <exception-type-filter...>

Name Type Required Default Description

name name (no spaces) no Identifies the


filter so that
other elements
can reference it.
Required if the
filter is defined at
the global level.

not boolean no Inverts the filter


condition.

expectedType class name no The expected


class used in the
comparison.

Payload Type Filter


A filter that matches the type of the payload.

Attributes of <payload-type-filter...>

Name Type Required Default Description

name name (no spaces) no Identifies the


filter so that
other elements
can reference it.
Required if the
filter is defined at
the global level.

not boolean no Inverts the filter


condition.

expectedType class name no The expected


class used in the
comparison.

Custom Filter
A user-implemented filter.

Document generated by Confluence on Oct 27, 2008 21:07 Page 211


Attributes of <custom-filter...>

Name Type Required Default Description

name name (no spaces) no Identifies the


filter so that
other elements
can reference it.
Required if the
filter is defined at
the global level.

not boolean no Inverts the filter


condition.

class class name no An


implementation
of the Filter
interface.

Child Elements of <custom-filter...>

Name Cardinality Description

spring:property 0..*

Encryption Security Filter


A filter that provides password-based encyption.

Attributes of <encryption-security-filter...>

Name Type Required Default Description

strategy-ref name (no spaces) no The name of


the encryption
strategy to use.
This should be
configured using
the password-
encryption-
strategy element,
inside a security-
manager element
at the top level.

Document generated by Confluence on Oct 27, 2008 21:07 Page 212


Global Settings Configuration Reference

This page last changed on Oct 22, 2008 by jackie.wheeler.

Global Settings Configuration Reference


This page provides details on the global settings you configure at the root level of a Mule configuration.
Some of this information is pulled directly from mule.xsd and is cached. If the information appears to
be out of date, refresh the page. For more information on configuration, see XML Configuration. For
reference on global properties, see Properties Configuration Reference. For reference on notifications, see
Notifications Configuration Reference. For information on threading profiles, see Tuning Performance.

<configuration ...>
Defaults and general settings for the entire Mule system.

Attributes

Name Type Required Default Description

defaultSynchronousEndpoints
boolean no false If true then
connections to
endpoints will wait
for a response.

defaultRemoteSync boolean no false If true then


connections to
endpoints will wait
for a response
from the remote
service.

defaultSynchronousEventTimeout
string no 3000 The default period
(ms) to wait for
a synchronous
response.

defaultTransactionTimeout string no 5000 The default


timeout for
transactions, used
if no more specific
configuration is
given.

Child Elements

Name Cardinality Description

default-threading-profile 0..1 The default threading profile,


used by components and by
endpoints for dispatching and
receiving if no more specific
configuration is given.

default-dispatcher-threading- 0..1 The default dispatching


profile threading profile, modifies the

Document generated by Confluence on Oct 27, 2008 21:07 Page 213


default-threading-profile values
and is used by endpoints for
dispatching if no more specific
configuration is given.

default-receiver-threading- 0..1 The default receiving threading


profile profile, modifies the default-
threading-profile values and is
used by endpoints for receiving
if no more specific configuration
is given.

default-service-threading-profile 0..1 The default service threading


profile, modifies the default-
threading-profile values and
is used if no more specific
configuration is given.

abstract-retry-policy 0..1 The default retry policy, used


by connectors and endpoints
if no more specific policy is
configured for them.

A placeholder for a retry policy


element. Retry policies define
how Mule should retry a failed
message send/dispatch/request.

Document generated by Confluence on Oct 27, 2008 21:07 Page 214


Inbound Router Configuration Reference

This page last changed on Oct 22, 2008 by jackie.wheeler.

Inbound Router Configuration Reference


This page provides details on the elements you configure for inbound routers. This information is pulled
directly from mule.xsd and is cached. If the information appears to be out of date, refresh the page. For
more information on routers, see Using Message Routers.

<idempotent-receiver-router ...>
Ensures that only unique messages are received by a service by checking the unique ID of the
incoming message. Note that the ID used can be generated from the message using an expression
defined in the {{idExpression}} attribute. By default, the expression used is #\[message:id\], which
means the underlying endpoint must support unique message IDs for this to work. Otherwise, a
{{UniqueIdNotSupportedException}} is thrown.

Attributes

Name Type Required Default Description

idExpression string no Defines one or


more expressions
to use when
extrating the ID
from the message.
For example, it
would be possible
to combine to
headers as the ID
of the message
to provide
idempotency: "#
\[headers:foo,bar
\]". Or, you could
combine the
message ID with
a header: "#
\[message:id\]-
#[header:foo]".
If this property
is not set, "#
\[message:id\]"
will be used by
default.

Child Elements

Name Cardinality Description

abstract-filter 0..1 A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

Document generated by Confluence on Oct 27, 2008 21:07 Page 215


abstract-object-store 0..1 A placeholder for an object store
that can be used by routers to
maintain state.

<idempotent-secure-hash-receiver-router ...>
Ensures that only unique messages are received by a service by calculating the hash of the message
itself using a message digest algorithm. This provides a value with an infinitesimally small chance of a
collision. This can be used to filter message duplicates. Keep in mind that the hash is calculated over
the entire byte array representing the message, so any leading or trailing spaces or extraneous bytes
(like padding) can produce different hash values for the same semantic message content. Care should be
taken to ensure that messages do not contain extraneous bytes. This class is useful when the message
does not support unique identifiers.

Attributes

Name Type Required Default Description

messageDigestAlgorithm string no The secure


hashing algorithm
to use. If not set,
the default is
SHA-256.

Child Elements

Name Cardinality Description

abstract-filter 0..1 A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

abstract-object-store 0..1 A placeholder for an object store


that can be used by routers to
maintain state.

<wire-tap-router ...>
The WireTap inbound router allows you to route certain messages to a different endpoint as well as to the
component.

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

abstract-filter 0..1 A placeholder for


filter elements.
Filters are used
to make decisions

Document generated by Confluence on Oct 27, 2008 21:07 Page 216


within the Mule
framework.

abstract- 1..1 A placeholder for


outbound- outbound endpoint
endpoint elements.
Outbound
endpoints dispatch
messages to
the underlying
transport.

<forwarding-router ...>
Allows messages to be forwarded to the outbound routers without first being processed by a component.

Attributes

Name Type Required Default Description

transformer-refs list of names no

transformFirst boolean no

Child Elements

Name Cardinality Description

abstract-filter 0..1 A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

abstract-transformer 0..* A placeholder for transformer


elements. Transformers convert
message payloads.

<selective-consumer-router ...>
Applies one or more filters to the incoming message. If the filters match, the message is forwarded to the
component. Otherwise, the message is forwarded to the catch-all strategy on the router. If no catch-all
strategy is configured, the message is ignored and a warning is logged.

Attributes

Name Type Required Default Description

transformer-refs list of names no

transformFirst boolean no

Document generated by Confluence on Oct 27, 2008 21:07 Page 217


Child Elements

Name Cardinality Description

abstract-filter 0..1 A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

abstract-transformer 0..* A placeholder for transformer


elements. Transformers convert
message payloads.

<correlation-resequencer-router ...>
Holds back a group of messages and resequences them using each message's correlation sequence
property.

Attributes

Name Type Required Default Description

timeout integer no

Child Elements

Name Cardinality Description

abstract-filter 0..1 A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

<message-chunking-aggregator-router ...>
Combines two or more messages into a single message by matching messages with a given Correlation
ID. Correlation IDs are set on messages when they are dispatched by certain outbound routers, such as
the Recipient List and Message Splitter routers. These messages can be aggregated back together again
using this router.

Attributes

Name Type Required Default Description

timeout integer no

Document generated by Confluence on Oct 27, 2008 21:07 Page 218


Child Elements

Name Cardinality Description

abstract-filter 0..1 A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

abstract-message-info-mapping 0..1 Maps the attributes of


the current message to
known message elements in
Mule; namely, Message ID,
CorrrelationID.

<custom-correlation-aggregator-router ...>
Configures a custom message aggregator. Mule provides an abstract implementation that has a template
method that performs the message aggregation. A common use of the aggregator router is to combine
the results of multiple requests such as "ask this set of vendors for the best price of X".

Attributes

Name Type Required Default Description

timeout integer no

class class name no

Child Elements

Name Cardinality Description

abstract-filter 0..1 A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

abstract-message-info-mapping 0..1 Maps the attributes of


the current message to
known message elements in
Mule; namely, Message ID,
CorrrelationID.

<collection-aggregator-router ...>
Configures a Collection Response Router. This will return a MuleMessageCollection message type that will
contain all events received for a each correlation group.

Document generated by Confluence on Oct 27, 2008 21:07 Page 219


Attributes

Name Type Required Default Description

timeout integer no

Child Elements

Name Cardinality Description

abstract-filter 0..1 A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

<custom-inbound-router ...>
Allows for custom inbound routers to be configured.

Attributes

Name Type Required Default Description

class class name no An


implementation
of InboundRouter
(fully qualified
Java class name)

Child Elements

Name Cardinality Description

abstract-filter 0..1 A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

spring:property 0..*

abstract-outbound-endpoint 0..* A placeholder for outbound


endpoint elements. Outbound
endpoints dispatch messages to
the underlying transport.

Document generated by Confluence on Oct 27, 2008 21:07 Page 220


Model Configuration Reference

This page last changed on Oct 22, 2008 by jackie.wheeler.

Model Configuration Reference


This page provides details on the elements you configure for models. Some of this information is pulled
directly from mule.xsd and is cached. If the information appears to be out of date, refresh the page. For
more information on models, see Models.

<model ...>
The default model is a SEDA model.

Attributes

Name Type Required Default Description

name name no The name used


to identify this
model.

inherit boolean no If true then this


model element is
an extension of
a previous model
element with the
same name.

Child Elements

Name Cardinality Description

abstract-exception-strategy 0..1 A placeholder for an exception


strategy element. Exception
strategies define how Mule
should react to errors.

abstract-service 0..* A placeholder for a service


element. Services combine
message routing with a Java
(typically) component.

abstract-entry-point-resolver-set 0..1 A placeholder for entry point


resolver set elements. These
combine a group of entry point
resolvers, trying them in turn
until one succeeds.

abstract-entry-point-resolver 0..1 A placeholder for an entry point


resolver element. Entry point
resolvers define how payloads
are delivered to Java code by
choosing the method to call.

Document generated by Confluence on Oct 27, 2008 21:07 Page 221


abstract-queue-profile 0..1 A placeholder for queue profile
elements. A queue profile
controls how messages are
queued before being processed.

Queue Profile
Specifies the properties of an internal Mule queue. Internal queues are used to queue messages for each
component managed by Mule.

Attributes of <queue-profile...>

Name Type Required Default Description

maxOutstandingMessages
integer no Defines the
maximum number
of messages that
can be queued.

persistent boolean no false Whether Mule


messages are
persisted to a
store. Primarily,
this is used for
persisting queued
messages to
disk so that the
internal state
of the server is
mirrored on disk
in case the server
fails and needs
to be restarted.
Default is false.

Exception Strategy
See Exception Strategy Configuration Reference.

Service
See Service Configuration Reference.

Entry Point Resolver


See Entry Point Resolver Configuration Reference.

Document generated by Confluence on Oct 27, 2008 21:07 Page 222


Notifications Configuration Reference

This page last changed on Oct 22, 2008 by jackie.wheeler.

Notifications Configuration Reference


This page provides details on the elements you configure for notifications. Some of this information is
pulled directly from mule.xsd and is cached. If the information appears to be out of date, refresh the
page. For more information on notifications, see Mule Server Notifications.

Notifications
Register listeners for notifications and associate interfaces with particular events.

Attributes of <notifications...>

Name Type Required Default Description

dynamic boolean no If the notification


manager is
dynamic then
programatic
updates to the
manager (ie
via Java code)
will affect all
messages.
Otherwise, some
parts of the
system may
cache state for
efficiency and
so not generate
newly enabled
notifications. The
default value is
false.

Child Elements of <notifications...>

Name Cardinality Description

notification 0..* Associate an event with an


interface. Listeners which
implement the interface will
receive instances of the event.

disable-notification 0..* Block the association of


an event with a particular
interface. This filters events
after the association with a
particular interface (and so
takes precedence).

notification-listener 0..* Register a bean as a listener


with the notification system.
Events are dispatched by

Document generated by Confluence on Oct 27, 2008 21:07 Page 223


reflection - the listener will
receive all events associated
with any interfaces it
implements. The relationship
between interfaces and events
is configured by the notification
and disable-notification
elements.

Notification Types
You can specify the following types of notifications using the event attribute of the <notification>
element:
"CONTEXT"
"MODEL"
"SERVICE"
"SECURITY"
"ENDPOINT-MESSAGE"
"COMPONENT-MESSAGE"
"MANAGEMENT"
"CONNECTION"
"REGISTRY"
"CUSTOM"
"EXCEPTION"
"TRANSACTION"
"ROUTING"

Document generated by Confluence on Oct 27, 2008 21:07 Page 224


Outbound Router Configuration Reference

This page last changed on Oct 22, 2008 by jackie.wheeler.

Outbound Router Configuration Reference


This page provides details on the elements you configure for outbound routers. This information is pulled
directly from mule.xsd and is cached. If the information appears to be out of date, refresh the page. For
more information on routers, see Using Message Routers.

<pass-through-router ...>
This router always matches and simply sends or dispatches message via the endpoint that is configured.

Attributes

Name Type Required Default Description

enableCorrelation ALWAYS no IF_NOT_SET


/ NEVER /
IF_NOT_SET

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 1..1 A placeholder for outbound


endpoint elements. Outbound
endpoints dispatch messages to
the underlying transport.

reply-to 0..1 Defines where the message


should be routed after the
recipient of the message this
service dispatches to has
finished with it.

abstract-transaction 0..1 A placeholder for transaction


elements. Transactions allow
a series of operations to be
grouped together.

abstract-message-info-mapping 0..1 Maps the attributes of


the current message to
known message elements in
Mule; namely, Message ID,
CorrrelationID.

<filtering-router ...>
Uses filters to determine whether the message matches a particular criteria and if so will route the
message to the endpoint configured on the router.

Document generated by Confluence on Oct 27, 2008 21:07 Page 225


Attributes

Name Type Required Default Description

transformer-refs list of names no

enableCorrelation ALWAYS no IF_NOT_SET


/ NEVER /
IF_NOT_SET

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 1..* A placeholder for outbound


endpoint elements. Outbound
endpoints dispatch messages to
the underlying transport.

abstract-filter 0..1 Filters the messages to be


processed by this router.

A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

abstract-transformer 0..* Filters are applied before


message transformations. A
transformer can be configured
here to transform messages
before they are filtered.

A placeholder for transformer


elements. Transformers convert
message payloads.

reply-to 0..1 Defines where the message


should be routed after the
recipient of the message this
service dispatches to has
finished with it.

abstract-transaction 0..1 A placeholder for transaction


elements. Transactions allow
a series of operations to be
grouped together.

abstract-message-info-mapping 0..1 Maps the attributes of


the current message to
known message elements in
Mule; namely, Message ID,
CorrrelationID.

<template-endpoint-router ...>
Allows endpoints to be altered at runtime based on properties set on the current message or fallback
values set on the endpoint properties. Templated values are expressed using square braces around a
property name.

Document generated by Confluence on Oct 27, 2008 21:07 Page 226


Attributes

Name Type Required Default Description

transformer-refs list of names no

enableCorrelation ALWAYS no IF_NOT_SET


/ NEVER /
IF_NOT_SET

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 1..1 A placeholder for outbound


endpoint elements. Outbound
endpoints dispatch messages to
the underlying transport.

abstract-filter 0..1 Filters the messages to be


processed by this router.

A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

abstract-transformer 0..* Filters are applied before


message transformations. A
transformer can be configured
here to transform messages
before they are filtered.

A placeholder for transformer


elements. Transformers convert
message payloads.

reply-to 0..1 Defines where the message


should be routed after the
recipient of the message this
service dispatches to has
finished with it.

abstract-transaction 0..1 A placeholder for transaction


elements. Transactions allow
a series of operations to be
grouped together.

abstract-message-info-mapping 0..1 Maps the attributes of


the current message to
known message elements in
Mule; namely, Message ID,
CorrrelationID.

<chaining-router ...>
Sends the message through multiple endpoints using the result of the first invocation as the input for the
next.

Document generated by Confluence on Oct 27, 2008 21:07 Page 227


Attributes

Name Type Required Default Description

transformer-refs list of names no

enableCorrelation ALWAYS no IF_NOT_SET


/ NEVER /
IF_NOT_SET

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 1..* A placeholder for outbound


endpoint elements. Outbound
endpoints dispatch messages to
the underlying transport.

abstract-filter 0..1 Filters the messages to be


processed by this router.

A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

abstract-transformer 0..* Filters are applied before


message transformations. A
transformer can be configured
here to transform messages
before they are filtered.

A placeholder for transformer


elements. Transformers convert
message payloads.

reply-to 0..1 Defines where the message


should be routed after the
recipient of the message this
service dispatches to has
finished with it.

abstract-transaction 0..1 A placeholder for transaction


elements. Transactions allow
a series of operations to be
grouped together.

abstract-message-info-mapping 0..1 Maps the attributes of


the current message to
known message elements in
Mule; namely, Message ID,
CorrrelationID.

<exception-based-router ...>
Sends a message over an endpoint by selecting the first endpoint that can connect to the transport.

Document generated by Confluence on Oct 27, 2008 21:07 Page 228


Attributes

Name Type Required Default Description

transformer-refs list of names no

enableCorrelation ALWAYS no IF_NOT_SET


/ NEVER /
IF_NOT_SET

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 1..* A placeholder for outbound


endpoint elements. Outbound
endpoints dispatch messages to
the underlying transport.

abstract-filter 0..1 Filters the messages to be


processed by this router.

A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

abstract-transformer 0..* Filters are applied before


message transformations. A
transformer can be configured
here to transform messages
before they are filtered.

A placeholder for transformer


elements. Transformers convert
message payloads.

reply-to 0..1 Defines where the message


should be routed after the
recipient of the message this
service dispatches to has
finished with it.

abstract-transaction 0..1 A placeholder for transaction


elements. Transactions allow
a series of operations to be
grouped together.

abstract-message-info-mapping 0..1 Maps the attributes of


the current message to
known message elements in
Mule; namely, Message ID,
CorrrelationID.

<multicasting-router ...>
Sends the same message over multiple endpoints.

Document generated by Confluence on Oct 27, 2008 21:07 Page 229


Attributes

Name Type Required Default Description

transformer-refs list of names no

enableCorrelation ALWAYS no IF_NOT_SET


/ NEVER /
IF_NOT_SET

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 1..* A placeholder for outbound


endpoint elements. Outbound
endpoints dispatch messages to
the underlying transport.

abstract-filter 0..1 Filters the messages to be


processed by this router.

A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

abstract-transformer 0..* Filters are applied before


message transformations. A
transformer can be configured
here to transform messages
before they are filtered.

A placeholder for transformer


elements. Transformers convert
message payloads.

reply-to 0..1 Defines where the message


should be routed after the
recipient of the message this
service dispatches to has
finished with it.

abstract-transaction 0..1 A placeholder for transaction


elements. Transactions allow
a series of operations to be
grouped together.

abstract-message-info-mapping 0..1 Maps the attributes of


the current message to
known message elements in
Mule; namely, Message ID,
CorrrelationID.

<endpoint-selector-router ...>
// TODO

Document generated by Confluence on Oct 27, 2008 21:07 Page 230


Attributes

Name Type Required Default Description

transformer-refs list of names no

enableCorrelation ALWAYS no IF_NOT_SET


/ NEVER /
IF_NOT_SET

evaluator groovy / header no The expression


/ headers / evaluator to
headers-list / use. Expression
attachment / Evaluators must
attachments / be registered
attachments- with the
list / message / ExpressionEvaluatrManager
map-payload / before thay can
payload / xpath be used. Using
/ jxpath / bean the custom
/ ognl / function evaluator allows
/ custom the developer
to define their
own in the
'custom-evaluator'
attribute. Note
that some
evaluators such as
xpath, groovy, and
bean are loaded
from other Mule
modules (XML
and Scripting,
respectively).
These modules
must be on your
classpath before
the evaluator can
be used.

expression string no The expression


to evaluate. The
syntax of this
attribute will
change depending
on the evaluator
being used.

custom-evaluator name (no spaces) no The name of


the custom
evaluator to use.
This attribute is
only used when
the evaluator
attribute is set
to custom. You
can plug in your
own expression
evaluators by
registering

Document generated by Confluence on Oct 27, 2008 21:07 Page 231


them with the
ExpressionEvaluatorManager.

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 1..* A placeholder for outbound


endpoint elements. Outbound
endpoints dispatch messages to
the underlying transport.

abstract-filter 0..1 Filters the messages to be


processed by this router.

A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

abstract-transformer 0..* Filters are applied before


message transformations. A
transformer can be configured
here to transform messages
before they are filtered.

A placeholder for transformer


elements. Transformers convert
message payloads.

reply-to 0..1 Defines where the message


should be routed after the
recipient of the message this
service dispatches to has
finished with it.

abstract-transaction 0..1 A placeholder for transaction


elements. Transactions allow
a series of operations to be
grouped together.

abstract-message-info-mapping 0..1 Maps the attributes of


the current message to
known message elements in
Mule; namely, Message ID,
CorrrelationID.

<list-message-splitter-router ...>
Accepts a list of objects that will be routed to different endpoints. The actual endpoint used for each
object in the list is determined by a filter configured on the endpoint itself.

Attributes

Name Type Required Default Description

transformer-refs list of names no

Document generated by Confluence on Oct 27, 2008 21:07 Page 232


enableCorrelation ALWAYS no IF_NOT_SET
/ NEVER /
IF_NOT_SET

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 1..* A placeholder for outbound


endpoint elements. Outbound
endpoints dispatch messages to
the underlying transport.

abstract-filter 0..1 Filters the messages to be


processed by this router.

A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

abstract-transformer 0..* Filters are applied before


message transformations. A
transformer can be configured
here to transform messages
before they are filtered.

A placeholder for transformer


elements. Transformers convert
message payloads.

reply-to 0..1 Defines where the message


should be routed after the
recipient of the message this
service dispatches to has
finished with it.

abstract-transaction 0..1 A placeholder for transaction


elements. Transactions allow
a series of operations to be
grouped together.

abstract-message-info-mapping 0..1 Maps the attributes of


the current message to
known message elements in
Mule; namely, Message ID,
CorrrelationID.

<expression-splitter-router ...>
Splits the message based on an expression. The expression must return one or more message parts in
order to be effective.

Attributes

Name Type Required Default Description

transformer-refs list of names no

Document generated by Confluence on Oct 27, 2008 21:07 Page 233


enableCorrelation ALWAYS no IF_NOT_SET
/ NEVER /
IF_NOT_SET

evaluator groovy / header no The expression


/ headers / evaluator to
headers-list / use. Expression
attachment / Evaluators must
attachments / be registered
attachments- with the
list / message / ExpressionEvaluatrManager
map-payload / before thay can
payload / xpath be used. Using
/ jxpath / bean the custom
/ ognl / function evaluator allows
/ custom the developer
to define their
own in the
'custom-evaluator'
attribute. Note
that some
evaluators such as
xpath, groovy, and
bean are loaded
from other Mule
modules (XML
and Scripting,
respectively).
These modules
must be on your
classpath before
the evaluator can
be used.

expression string no The expression


to evaluate. The
syntax of this
attribute will
change depending
on the evaluator
being used.

custom-evaluator name (no spaces) no The name of


the custom
evaluator to use.
This attribute is
only used when
the evaluator
attribute is set
to custom. You
can plug in your
own expression
evaluators by
registering
them with the
ExpressionEvaluatorManager.

Document generated by Confluence on Oct 27, 2008 21:07 Page 234


Child Elements

Name Cardinality Description

abstract-outbound-endpoint 1..* A placeholder for outbound


endpoint elements. Outbound
endpoints dispatch messages to
the underlying transport.

abstract-filter 0..1 Filters the messages to be


processed by this router.

A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

abstract-transformer 0..* Filters are applied before


message transformations. A
transformer can be configured
here to transform messages
before they are filtered.

A placeholder for transformer


elements. Transformers convert
message payloads.

reply-to 0..1 Defines where the message


should be routed after the
recipient of the message this
service dispatches to has
finished with it.

abstract-transaction 0..1 A placeholder for transaction


elements. Transactions allow
a series of operations to be
grouped together.

abstract-message-info-mapping 0..1 Maps the attributes of


the current message to
known message elements in
Mule; namely, Message ID,
CorrrelationID.

<message-chunking-router ...>
Allows you to split a single message into a number of fixed-length messages that will all be routed to the
same endpoint.

Attributes

Name Type Required Default Description

transformer-refs list of names no

enableCorrelation ALWAYS no IF_NOT_SET


/ NEVER /
IF_NOT_SET

Document generated by Confluence on Oct 27, 2008 21:07 Page 235


messageSize integer no

numberOfMessages integer no

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 1..* A placeholder for outbound


endpoint elements. Outbound
endpoints dispatch messages to
the underlying transport.

abstract-filter 0..1 Filters the messages to be


processed by this router.

A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

abstract-transformer 0..* Filters are applied before


message transformations. A
transformer can be configured
here to transform messages
before they are filtered.

A placeholder for transformer


elements. Transformers convert
message payloads.

reply-to 0..1 Defines where the message


should be routed after the
recipient of the message this
service dispatches to has
finished with it.

abstract-transaction 0..1 A placeholder for transaction


elements. Transactions allow
a series of operations to be
grouped together.

abstract-message-info-mapping 0..1 Maps the attributes of


the current message to
known message elements in
Mule; namely, Message ID,
CorrrelationID.

<static-recipient-list-router ...>
Sends the same message to multiple endpoints over the same endpoint or to implement routing-slip
behaviour where the next destination for the message is determined from message properties or the
payload. It uses a static list of recipient endpoints, which are specified via the attribute recipientsProperty
and delimited by the attribute recipientsDelimieter.

Document generated by Confluence on Oct 27, 2008 21:07 Page 236


Attributes

Name Type Required Default Description

recipientsProperty string no

recipientsDelimiter string no

synchronous boolean no

transformer-refs list of names no

enableCorrelation ALWAYS no IF_NOT_SET


/ NEVER /
IF_NOT_SET

Child Elements

Name Cardinality Description

recipients 0..1

abstract-filter 0..1 Filters the messages to be


processed by this router.

A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

abstract-transformer 0..* Filters are applied before


message transformations. A
transformer can be configured
here to transform messages
before they are filtered.

A placeholder for transformer


elements. Transformers convert
message payloads.

reply-to 0..1 Defines where the message


should be routed after the
recipient of the message this
service dispatches to has
finished with it.

abstract-transaction 0..1 A placeholder for transaction


elements. Transactions allow
a series of operations to be
grouped together.

abstract-message-info-mapping 0..1 Maps the attributes of


the current message to
known message elements in
Mule; namely, Message ID,
CorrrelationID.

Document generated by Confluence on Oct 27, 2008 21:07 Page 237


<expression-recipient-list-router ...>
Sends the same message to multiple endpoints over the same endpoint or implements routing-slip
behaviour where the next destination for the message is determined from message properties or the
payload. It uses a list of recipients endpoints, which are extracted from the message using an expression.
(As of 2.1)

Attributes

Name Type Required Default Description

synchronous boolean no

transformer-refs list of names no

enableCorrelation ALWAYS no IF_NOT_SET


/ NEVER /
IF_NOT_SET

evaluator groovy / header no The expression


/ headers / evaluator to
headers-list / use. Expression
attachment / Evaluators must
attachments / be registered
attachments- with the
list / message / ExpressionEvaluatrManager
map-payload / before thay can
payload / xpath be used. Using
/ jxpath / bean the custom
/ ognl / function evaluator allows
/ custom the developer
to define their
own in the
'custom-evaluator'
attribute. Note
that some
evaluators such as
xpath, groovy, and
bean are loaded
from other Mule
modules (XML
and Scripting,
respectively).
These modules
must be on your
classpath before
the evaluator can
be used.

expression string no The expression


to evaluate. The
syntax of this
attribute will
change depending
on the evaluator
being used.

custom-evaluator name (no spaces) no The name of


the custom
evaluator to use.
This attribute is

Document generated by Confluence on Oct 27, 2008 21:07 Page 238


only used when
the evaluator
attribute is set
to custom. You
can plug in your
own expression
evaluators by
registering
them with the
ExpressionEvaluatorManager.

Child Elements

Name Cardinality Description

recipients 0..1

abstract-filter 0..1 Filters the messages to be


processed by this router.

A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

abstract-transformer 0..* Filters are applied before


message transformations. A
transformer can be configured
here to transform messages
before they are filtered.

A placeholder for transformer


elements. Transformers convert
message payloads.

reply-to 0..1 Defines where the message


should be routed after the
recipient of the message this
service dispatches to has
finished with it.

abstract-transaction 0..1 A placeholder for transaction


elements. Transactions allow
a series of operations to be
grouped together.

abstract-message-info-mapping 0..1 Maps the attributes of


the current message to
known message elements in
Mule; namely, Message ID,
CorrrelationID.

<custom-outbound-router ...>
Allows you to configure a custom outbound router by specifying the custom router class and by using
Spring properties.

Document generated by Confluence on Oct 27, 2008 21:07 Page 239


Attributes

Name Type Required Default Description

class class name no An


implementation of
OutboundRouter
(fully qualified
Java class name)

transformer-refs list of names no

enableCorrelation ALWAYS no IF_NOT_SET


/ NEVER /
IF_NOT_SET

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 0..* A placeholder for outbound


endpoint elements. Outbound
endpoints dispatch messages to
the underlying transport.

spring:property 0..*

abstract-filter 0..1 Filters the messages to be


processed by this router.

A placeholder for filter elements.


Filters are used to make
decisions within the Mule
framework.

abstract-transformer 0..* Filters are applied before


message transformations. A
transformer can be configured
here to transform messages
before they are filtered.

A placeholder for transformer


elements. Transformers convert
message payloads.

reply-to 0..1 Defines where the message


should be routed after the
recipient of the message this
service dispatches to has
finished with it.

abstract-transaction 0..1 A placeholder for transaction


elements. Transactions allow
a series of operations to be
grouped together.

abstract-message-info-mapping 0..1 Maps the attributes of


the current message to
known message elements in

Document generated by Confluence on Oct 27, 2008 21:07 Page 240


Mule; namely, Message ID,
CorrrelationID.

Document generated by Confluence on Oct 27, 2008 21:07 Page 241


Properties Configuration Reference

This page last changed on Oct 22, 2008 by jackie.wheeler.

Properties Configuration Reference


This page provides detailed reference information for property elements in Mule. The information below is
pulled directly from the source code, so it reflects the latest data since you loaded the page. If something
appears to be out of date, you can refresh the page to reload the information.

Global Property
A global property is a named string. It can be inserted in most attribute values using the #[...] syntax. So
the attribute value "#[foo]" would be replaced by the value associated with the property named "foo".

Attributes of <global-property...>

Name Type Required Default Description

name name (no spaces) no The name of the


property. This is
used inside #[...].

value string no The value of the


property. This
replaces each
occurence of
#[...].

Property
Sets a Mule property. This is a name/value pair that can be set on components, services, etc., and
which provide a generic way of configuring the system. In Mule 2.x, you shouldn't need to use a generic
property like this, since almost all functionality is exposed via dedicated elements. However, it can
be useful in configuring obscure or overlooked options and in configuring transports from the generic
endpoint elements.

Attributes of <property...>

Name Type Required Default Description

key string no

value string no

value-ref name (no spaces) no

Properties
Sets Mule properties. These are name/value pairs that can be set on components, services, etc., and
which provide a generic way of configuring the system. In Mule 2.x, you shouldn't need to use generic
properties like this, since almost all functionality is exposed via dedicated elements. However, they can
be useful in configuring obscure or overlooked options and in configuring transports from the generic
endpoint elements.

Document generated by Confluence on Oct 27, 2008 21:07 Page 242


Jndi Provider Property
Direct setting of a JNDI property.

Attributes of <jndi-provider-property...>

Name Type Required Default Description

key string no

value string no

value-ref name (no spaces) no

Jndi Provider Properties


Direct setting of JNDI properties (allows access to the full Spring map entry).

Document generated by Confluence on Oct 27, 2008 21:07 Page 243


Service Configuration Reference

This page last changed on Oct 22, 2008 by jackie.wheeler.

Service Configuration Reference


This page provides details on the elements you configure for services. This information is pulled directly
from mule.xsd and is cached. If the information appears to be out of date, refresh the page. For more
information on services, see Configuring the Service.

<service ...>
The standard SEDA service. A service describes how to receive messages, deliver them to a component,
and handle the results (if any).

Attributes

Name Type Required Default Description

name name no The name used


to identify this
service.

initialState started / no started The initial


stopped state of the
/ paused service. Usually a
service is started
automatically,
but this attribute
can block any
initial startup
("stopped") or
stop the service
immediately after
initial startup
("paused").

queueTimeout integer no The timeout used


when taking
messages from
the SEDA queue.

Child Elements

Name Cardinality Description

description 0..1 This can hold any kind of


documentation consistent
with the overall XML format).
It is intended to be "human
readable" only and is not used
by the system.

inbound 0..1 The elements within "inbound"


describe how a service receives
messages.

Document generated by Confluence on Oct 27, 2008 21:07 Page 244


abstract-component 0..1 A placeholder for component
element. A component
processes data. Typically it is a
Java object.

outbound 0..1 The elements within "outbound"


describe how a services sends or
dispatches messages.

async-reply 0..1 The elements within


"async-reply" describe how
asynchronous replies are
handled.

abstract-exception-strategy 0..1 A placeholder for an exception


strategy element. Exception
strategies define how Mule
should react to errors.

abstract-service-threading- 0..1 A placeholder for service


profile threading profile element.
Threading profiles define how
thread pools interact with the
component.

abstract-queue-profile 0..1 A placeholder for queue profile


elements. A queue profile
controls how messages are
queued before being processed.

<custom-service ...>
A user-implemeted service (typically used only in testing).

Attributes

Name Type Required Default Description

name name no The name used


to identify this
service.

initialState started / no started The initial


stopped state of the
/ paused service. Usually a
service is started
automatically,
but this attribute
can block any
initial startup
("stopped") or
stop the service
immediately after
initial startup
("paused").

class class name no The class to use


for the service.

Document generated by Confluence on Oct 27, 2008 21:07 Page 245


Child Elements

Name Cardinality Description

description 0..1 This can hold any kind of


documentation consistent
with the overall XML format).
It is intended to be "human
readable" only and is not used
by the system.

inbound 0..1 The elements within "inbound"


describe how a service receives
messages.

abstract-component 0..1 A placeholder for component


element. A component
processes data. Typically it is a
Java object.

outbound 0..1 The elements within "outbound"


describe how a services sends or
dispatches messages.

async-reply 0..1 The elements within


"async-reply" describe how
asynchronous replies are
handled.

abstract-exception-strategy 0..1 A placeholder for an exception


strategy element. Exception
strategies define how Mule
should react to errors.

<description ...>
This can hold any kind of documentation consistent with the overall XML format). It is intended to be
"human readable" only and is not used by the system.

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

<description ...>
This can hold any kind of documentation consistent with the overall XML format). It is intended to be
"human readable" only and is not used by the system.

Document generated by Confluence on Oct 27, 2008 21:07 Page 246


Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

<inbound ...>
The elements within "inbound" describe how a service receives messages.

Attributes

Name Type Required Default Description

matchAll boolean no true If true, the input


message will be
passed through
inbound routers,
otherwise only
the first matching
router is used.

Child Elements

Name Cardinality Description

abstract-inbound-endpoint 0..* A placeholder for inbound


endpoint elements. Inbound
endpoints receive messages
from the underlying transport.
The message payload is then
delivered to the component for
processing.

abstract-inbound-router 0..* A placeholder for inbound router


elements. Inbound routers
control how incoming messages
are handled.

abstract-catch-all-strategy 0..1 A placeholder for catch-all


strategy elements.

<outbound ...>
The elements within "outbound" describe how a services sends or dispatches messages.

Document generated by Confluence on Oct 27, 2008 21:07 Page 247


Attributes

Name Type Required Default Description

matchAll boolean no false If true, the output


message will be
sent to all routers,
otherwise only
the first matching
router is used.

Child Elements

Name Cardinality Description

abstract-outbound-router 1..* A placeholder for outbound


router elements. Outbound
routers control how outgoing
messages are delivered to the
outbound endpoints.

abstract-catch-all-strategy 0..1 A placeholder for catch-all


strategy elements.

<async-reply ...>
The elements within "async-reply" describe how asynchronous replies are handled.

Attributes

Name Type Required Default Description

timeout integer no The timeout (ms)


to wait for a reply.

failOnTimeout boolean no If the router


times out before
all expected
events have been
received should
an exception be
thrown or should
the current events
be returned for
processing. The
default is false.

Child Elements

Name Cardinality Description

abstract-inbound-endpoint 1..* A placeholder for inbound


endpoint elements. Inbound
endpoints receive messages

Document generated by Confluence on Oct 27, 2008 21:07 Page 248


from the underlying transport.
The message payload is then
delivered to the component for
processing.

abstract-async-reply-router 0..1 A placeholder for an async reply


router element. Asynchronous
replies are handled via this
router.

<queue-profile ...>
Specifies the properties of an internal Mule queue. Internal queues are used to queue messages for each
component managed by Mule.

Attributes

Name Type Required Default Description

maxOutstandingMessages integer no Defines the


maximum number
of messages that
can be queued.

persistent boolean no false Whether Mule


messages are
persisted to a
store. Primarily,
this is used for
persisting queued
messages to
disk so that the
internal state
of the server is
mirrored on disk
in case the server
fails and needs
to be restarted.
Default is false.

Child Elements

Name Cardinality Description

Exception Strategy
See Exception Strategy Configuration Reference.

Catch All Strategy


See Catch All Strategy Configuration Reference.

Component
See Component Configuration Reference.

Document generated by Confluence on Oct 27, 2008 21:07 Page 249


Transactions Configuration Reference

This page last changed on Oct 22, 2008 by jackie.wheeler.

Transactions Configuration Reference


Abstract Transaction
A placeholder for transaction elements. Transactions allow a series of operations to be grouped together.

Attributes of <abstract-transaction...>

Name Type Required Default Description

action NONE/ no NONE - Never


ALWAYS_BEGIN/ participate in
BEGIN_OR_JOIN/ a transaction;
ALWAYS_JOIN/ ALWAYS_BEGIN
JOIN_IF_POSSIBLE - Always start a
new transaction
when receiving
an event. An
exception will
be thrown if
a transaction
already exists;
BEGIN_OR_JOIN
- If a transaction
is already in
progress when
an event is
received, join
the transaction,
otherwise start a
new transaction;
ALWAYS_JOIN -
Always expects
a transaction to
be in progress
when an event is
received, if there
is no transaction
an exception
is thrown;
JOIN_IF_POSSIBLE
- Will join
the current
transaction if
one is available
otherwise no
transaction is
created.

timeout integer no Timeout for


transaction (ms).

Document generated by Confluence on Oct 27, 2008 21:07 Page 250


Custom Transaction
Allow access to user-defined or otherwise unsupported third-party transactions.

Attributes of <custom-transaction...>

Name Type Required Default Description

action NONE/ no NONE - Never


ALWAYS_BEGIN/ participate in
BEGIN_OR_JOIN/ a transaction;
ALWAYS_JOIN/ ALWAYS_BEGIN
JOIN_IF_POSSIBLE - Always start a
new transaction
when receiving
an event. An
exception will
be thrown if
a transaction
already exists;
BEGIN_OR_JOIN
- If a transaction
is already in
progress when
an event is
received, join
the transaction,
otherwise start a
new transaction;
ALWAYS_JOIN -
Always expects
a transaction to
be in progress
when an event is
received, if there
is no transaction
an exception
is thrown;
JOIN_IF_POSSIBLE
- Will join
the current
transaction if
one is available
otherwise no
transaction is
created.

timeout integer no Timeout for


transaction (ms).

factory-class class name no A class that


implements the
TransactionFactory
interface that will
be instantiated
and used to
generate a
transaction. This
attribute and
the "factory-
ref" attribute

Document generated by Confluence on Oct 27, 2008 21:07 Page 251


are mutually
exclusive; one
of the two is
required.

factory-ref name (no spaces) no A bean that


implements the
TransactionFactory
interface that
will be used
to generate a
transaction. This
attribute and
the "factory-
class" attribute
are mutually
exclusive; one
of the two is
required.

Xa Transaction
Allow access to XA transactions.

Websphere Transaction Manager


The WebSphere transaction manager.

Attributes of <websphere-transaction-manager...>

Name Type Required Default Description

name name (no spaces) no transactionManager An optional name


for the transaction
manager. The
default value is
"transactionManager".

Jboss Transaction Manager


The JBoss transaction manager.

Attributes of <jboss-transaction-manager...>

Name Type Required Default Description

name name (no spaces) no transactionManager An optional name


for the transaction
manager. The
default value is
"transactionManager".

Weblogic Transaction Manager


The WebLogic transaction manager.

Document generated by Confluence on Oct 27, 2008 21:07 Page 252


Child Elements of <weblogic-transaction-manager...>

Name Cardinality Description

environment 0..1 The JNDI environment.

Jrun Transaction Manager


The JRun transaction manager.

Attributes of <jrun-transaction-manager...>

Name Type Required Default Description

name name (no spaces) no transactionManager An optional name


for the transaction
manager. The
default value is
"transactionManager".

Resin Transaction Manager


The Resin transaction manager.

Attributes of <resin-transaction-manager...>

Name Type Required Default Description

name name (no spaces) no transactionManager An optional name


for the transaction
manager. The
default value is
"transactionManager".

Jndi Transaction Manager


Retrieve a named transaction manager factory from JNDI.

Attributes of <jndi-transaction-manager...>

Name Type Required Default Description

jndiName string no The name of


the manager
factory to retrieve
(eg java:/
TransactionManager).

Custom Transaction Manager


A user-implemented transaction manager.

Document generated by Confluence on Oct 27, 2008 21:07 Page 253


Attributes of <custom-transaction-manager...>

Name Type Required Default Description

class class name no The class to


instantiate
to create a
transaction
manager.

Child Elements of <custom-transaction-manager...>

Name Cardinality Description

environment 0..1 The JNDI environment.

spring:property 0..*

Document generated by Confluence on Oct 27, 2008 21:07 Page 254


Configuring a Mule Instance

This page last changed on Oct 10, 2008 by jackie.wheeler.

Configuring a Mule Instance


A Mule configuration file can become an elaborate tree of elements, however, the basic things to
configure at the top level are:

• Connectors - Non-default configuration of any transports used


• Endpoints - Global definition of endpoints is encouraged to clearly describe where your integration
channels are
• Transformers - Transformers may be defined globally and later referenced from your services
• Filters - Filters may be defined globally and later referenced from your services
• Models - One or more models that logically group together your services
• Services - One or more services that wrap your components and configure routers, endpoints,
transformers, and filters specifically for that service

Following is an example of a simple Mule configuration file:

Simple Mule Configuration

<mule xmlns="http://www.mulesource.org/schema/mule/core/2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.0"
xsi:schemaLocation="
http://www.mulesource.org/schema/mule/core/2.0 http://www.mulesource.org/schema/mule/core/2.0/
mule.xsd
http://www.mulesource.org/schema/mule/vm/2.0 http://www.mulesource.org/schema/mule/vm/2.0/mule-
vm.xsd">

<vm:connector name="vmConnector" queueEvents="true" queueTimeout="5000"/>

<vm:endpoint name="CustomerRequests" path="customer.requests"/>


<vm:endpoint name="CustomerResponses" path="customer.responses"/>

<custom-transformer name="ThisToThat" class="com.acme.transformer.ThisToThat"/>

<model name="main">
<service name="myBasicService">
<inbound>
<inbound-endpoint ref="CustomerRequests"/>
</inbound>
<component class="com.acme.service.BasicService"/>
<outbound>
<outbound-pass-through-router>
<outbound-endpoint ref="CustomerResponses" transformer-refs="ThisToThat"/>
</outbound-pass-through-router>
</outbound>
</service>

Document generated by Confluence on Oct 27, 2008 21:07 Page 255


</model>
</mule>

Advanced Configuration
Other, more advanced things you may configure at this level:

• Agents - Agents are typically used for cross-cutting concerns such as logging or management
• Notifications - Be notified upon certain lifecycle events
• Security Manager - Authenticates requests based on one or more security providers
• Transaction Management - Mule transactions are configured on inbound endpoints, where an
endpoint can be configured to start a new transaction or join an existing one.
• Global Configuration Options - Miscellaneous global settings
• Global Properties - Placeholder values

Document generated by Confluence on Oct 27, 2008 21:07 Page 256


Configuring Endpoints

This page last changed on Oct 15, 2008 by jackie.wheeler.

Configuring Endpoints
[ Basic Configuration ] [ Endpoint Usage ] [ Global Endpoints ]

Endpoints are used to connect services. An endpoint is a specific channel on which a service can send
messages and from which another service can receive messages. For example, a purchasing component
may receive an order request over HTTP. Once the order has been processed by the component, a JMS
message may be sent over a topic to notify an auditing system, and a response can be sent back over
HTTP.

This page describes how to configure an endpoint. For details on the various attributes and elements you
can configure on an endpoint, see Endpoint Configuration Reference.

Basic Configuration
In its most basic form, an endpoint consists of a transport and a transport-specific channel/destination/
resource used to identify the channel and location where two services can exchange information. For
example:

URI-style Endpoints

<inbound-endpoint address="udp://localhost:65432"/>
<jetty:inbound-endpoint address="http://localhost:60211/mycomponent1" synchronous="true" />
<outbound-endpoint address="smtp://user:secret@smtp.host"/>
<inbound-endpoint address="jms://test.queue"/>

Traditionally, endpoints in Mule have been specified as a URI such as the examples above. This form is
still supported, and indeed may prove to be more practical depending on your application. However, as of
Mule 2.0, the recommended way to specify endpoints is via transport-specific namespaces, as shown in
the following examples.

Transport-specific Endpoints

<file:inbound-endpoint path="./.mule/in"
comparator="org.mule.transport.file.comparator.OlderFirstComparator" reverseOrder="true"/>
<ssl:endpoint name="clientEndpoint" host="localhost" port="60198" synchronous="true"/>
<jetty:endpoint name="serverEndpoint" host="localhost" port="60203" path="services/Foo"
synchronous="false" />
<imaps:endpoint name="global1s" host="localhost" password="secret" port="123" user="bob"/>
<rmi:endpoint name="BadType" host="localhost" port="1099" object="MatchingUMO"
method="reverseString"/>
<quartz:endpoint name="qEP6" repeatCount="10" repeatInterval="1000" jobName="job"/>
<jms:inbound-endpoint queue="test.queue"/>

Properties

Properties on endpoints can be used to customize behavior. Any properties set on the endpoint can
be used to overload default properties on the associated transport's connector. For example, an SMTP
outbound endpoint might set the fromAddress property to workflow1 to override a default connector
value of sysadmin. Any standard properties for an endpoint will be available as attributes in the XML
schema if transport-specific endpoints are used. It is also possible to specify a non-standard property. For
example:

Setting properties

<!-- Standard properties -->


<quartz:endpoint name="qEP6" repeatCount="10" repeatInterval="1000" jobName="job"/>

<!-- Non-standard properties -->

Document generated by Confluence on Oct 27, 2008 21:07 Page 257


<quartz:endpoint name="qEP7" jobName="job2">
<property key="actionOnTimeout" value="self-destruct"/>
<property key="precision" value="2.5"/>
</quartz:endpoint>

Connector

In many cases, the connector associated with an endpoint can simply be assumed based on the transport
and created implicitly. However, if more than one connector of the same transport exists, or if non-
default settings are used for the connector, you must refer to the connector from the endpoint using the
connector-ref attribute.

Specifying a connector

<inbound-endpoint address="tcp://localhost:65432" connector-ref="tcpConnector1"/>


<tcp:inbound-endpoint host="localhost" port="65433" connector-ref="tcpConnector2"/>

Filter

An endpoint can contain a filter to selectively ignore certain messages. The filter can be transport-specific
such as a JMS selector or file filter or can be a general-purpose filter such as JXPath. Filtering is not
supported by all transports, and setting a filter on an endpoint using some transports will result in an
UnsupportedOperationException. For more information, see Using Filters.

Filter example

<jms:endpoint queue="in.queue">
<jms:selector expression="JMSPriority > 5"/>
</jms:endpoint>

<vm:endpoint name="fruitBowlEndpoint" path="fruitBowlPublishQ">


<message-property-filter pattern="foo=bar"/>
</vm:endpoint>

Transaction

A transaction can begin or commit when an event is received or sent via an endpoint. The endpoint must
be synchronous, and transaction support depends largely on the particular transport being used. For
more information see Transaction Management.

Transaction example

<jms:inbound-endpoint queue="in">
<jms:transaction action="BEGIN_OR_JOIN"/>
</jms:inbound-endpoint>

Endpoint Usage
Endpoints can be used in the following places:

• Inbound Routers
• Outbound Routers
• Services
• Catch-all Strategies
• Exception Strategies

Inbound Routers

See Using Message Routers.

Inbound router

<service name="Receiver">
<inbound>

Document generated by Confluence on Oct 27, 2008 21:07 Page 258


<vm:inbound-endpoint path="inbound.channel"/>
<wire-tap-router>
<vm:outbound-endpoint path="tapped.channel"/>
</wire-tap-router>
</inbound>
<component class="com.acme.SomeService"/>
</service>

Outbound Routers

See Using Message Routers.

Outbound routers

<service name="MessageChunker">
<inbound>
<jms:inbound-endpoint queue="big.messages"/>
</inbound>
<outbound>
<message-chunking-router messageSize="10">
<jms:outbound-endpoint queue="small.chunks"/>
</message-chunking-router>
</outbound>
</service>

<service name="LenderGatewayService">
<inbound>
<inbound-endpoint ref="LenderGateway" />
</inbound>
<outbound>
<chaining-router>
<outbound-endpoint remoteSync="true" ref="LenderService" />
<outbound-endpoint ref="BankingGateway" transformer-refs="SetLendersAsRecipients
ObjectToJMSMessage" />
</chaining-router>
</outbound>
</service>

Services

As a shortcut, endpoints can be configured directly on the service without a router in some cases.

Implicit router

<service name="Echo">
<inbound>
<!-- Inbound router is implicit -->
<stdio:inbound-endpoint system="IN"/>
</inbound>
<echo-component/>
<outbound>
<!-- Outbound router is explicit -->
<outbound-pass-through-router>
<stdio:outbound-endpoint system="OUT"/>
</outbound-pass-through-router>
</outbound>
</service>

Catch-all Strategies

A single "catch-all" endpoint can be configured for certain types of routers. See Using Message Routers.

Catch-all strategy

<service name="dataService">

Document generated by Confluence on Oct 27, 2008 21:07 Page 259


<inbound>
<inbound-endpoint ref="dataIn">
<payload-type-filter expectedType="java.lang.String"/>
</inbound-endpoint>
<forwarding-catch-all-strategy>
<jms:outbound-endpoint queue="error.queue"/>
</forwarding-catch-all-strategy>
</inbound>
...cut...
</service>

Exception Strategies

A single error endpoint can be configured on an exception strategy. See Error Handling.

Exception strategy

<service name="dataService">
<inbound>
...cut...
</inbound>
<component class="com.acme.DataProcessor"/>
<outbound>
...cut...
</outbound>
<default-service-exception-strategy>
<jms:outbound-endpoint queue="error.queue"/>
</default-service-exception-strategy>
</service>

Global Endpoints
Global endpoints, while not required, are a recommended best practice for having a nicely organized
configuration file. A global endpoint can be thought of as a template for shared endpoint configuration.
Global endpoints can be used as they are defined globally, or they can be extended by adding more
configuration attributes or elements.

To reference a global endpoint, use the usual <inbound-endpoint> and <outbound-endpoint> elements,
and specify the global endpoint name using the ref attribute.

Global endpoint example

<file:endpoint name="fileReader" reverseOrder="true"


comparator="org.mule.transport.file.comparator.OlderFirstComparator"/>
...cut...

<model>
<service name="Priority1">
<file:inbound-endpoint ref="fileReader" path="/var/prio1"/>
...cut...
</service>

<service name="Priority2">
<file:inbound-endpoint ref="fileReader" path="/var/prio2"/>
...cut...
</service>
</model>

In the above example, the "fileReader" endpoint is used as a template for the inbound endpoints. The
properties reverseOrder and comparator only need to be declared once, and the property path changes
for each inbound endpoint.

Document generated by Confluence on Oct 27, 2008 21:07 Page 260


Mule Endpoint URIs

This page last changed on Oct 09, 2008 by jackie.wheeler.

Mule Endpoint URIs


Although URI-based endpoints are still supported in Mule 2.0, transport-specific endpoints
are generally recommended instead.

Mule Endpoint URIs are any valid URI and describe how to connect to the underlying transport. Most
connectors in Mule can be created from an endpoint URI except where not enough connection information
can be expressed clearly in a URI, such as JMS connection properties. Endpoint URIs are set on Mule
Endpoints, which manage other connection instance information such as filters and transactions.

Mule Endpoint URIs usually appear in one of the following forms, although other provider
implementations can introduce their own schemes.

scheme://host[:port]//[address][?params]

The scheme must always be set. The host and port are set for endpoints that use unwrapped socket
based communications such as the TCP, UDP, HTTP, or multicast.

udp://localhost:65432

scheme://[username][:password]@host[:port][?params]

The user name and password are used to log in to the remote server specified by the host and port
parameters. The POP3 and SMTP connectors use this format or URI.

pop3://ross:secret@pop3.mycompany.com

smtp://ross:secret@smtp.mycompany.com

scheme://address[?params]

Here we only define a protocol and an address. This tells Mule to get a connector that handles the
specified scheme, or create one if needed, and to create a new endpoint using the specified address.

vm://my.queue

URI Parameters
There are two types of parameters you can set on the URI:

1. Known Mule parameters that control the way the endpoint is configured, such as transformers for
the endpoint.
2. Properties to be set on the connector or to be associated with the transport. This allows you to
set properties on a connector used by this endpoint. Additionally, all properties will be associated
with the transport, so you can mix connector and transport properties. For more information, see
Configuring Endpoints.

Known Parameters

Property Description

connector The name of an existing connector to use for this


endpoint URI

Document generated by Confluence on Oct 27, 2008 21:07 Page 261


transformers Defines a comma-separated list of transformers to
configure on the endpoint

address Explicitly sets the endpoint address to the


specified value and ignores all other info in the
URI.

For example:

file:///C:/temp?transformers=FileToString,XmlToDom

jms://jmsEndpoint/topic:my.topic?connector=WMQConnector

Other Parameters

Any other parameters set on the URI will be set on the connector if a connector is created and also set on
the endpoint itself as properties.

Endpoint Encoding
When using XML configuration, certain character entities defined in the W3C SGML specification need
to be escaped to their SGML code. The most relevant are listed here. Don't forget to remove the space
before the ';'.

For characters such as > < " % #, the notation will be resolved and cause the constructor for the URI to
throw an exception. To use one of these characters, you can specify %HEXNUMBER

Text code Numerical code What it looks like Description, extras

%22 #34 " quotation mark =


APL quote, U+0022
ISONEW

&amp ; #38 & ampersand, U+0026


ISOnum

%3C #60 < less-than sign, U+003C


ISOnum

%3E #62 > greater-than sign, U


+003E ISOnum

%25 #37 % percentage sign, U


+0023 ISOnum

%23 #35 # hash sign, U+0025


ISOnum

Additionally, for connectors such as Axis, FTP, and the Email connectors, if your login credentials include
@, you must escape it using %40. For example, instead of these URIs:

axis:http://wsuser@username:password@localhost/services/services/Version?method=getVersion
ftp://username:password@ftpserver
smtp://'sender@mydomain.com':'123456'@mailserver?address=QA

You must use these:

axis:http://wsuser%40username:password%40localhost/services/services/Version?method=getVersion
ftp://username:password%40ftpserver
smtp://'sender%40mydomain.com':'123456'%40mailserver?address=QA

Document generated by Confluence on Oct 27, 2008 21:07 Page 262


Using Filters

This page last changed on Oct 24, 2008 by jackie.wheeler.

Using Filters
[ Standard Filters ] [ Transport and Module Filters ] [ Creating Custom Filters ]

Filters specify conditions that must be met for a message to be routed to a service. There are several
standard filters that come with Mule that you can use, or you can create your own filters.

You can create a global filter and then reference it from your services. Global filters require the "name"
attribute, whereas filters configured on endpoints or routers do not.

<!-- Globally defined filter with name attribute -->


<payload-type-filter name="payloadFilter" expectedType="java.lang.String">

<model>
<service>
<inbound>
<tcp:inbound-endpoint host="locahost" port="1234">
<!-- Here we reference the filter defined globally using it for this endpoint -->
<filter ref="payloadFilter"/>
</tcp:inbound-endpoint>
</inbound>
<echo-component/>
<service>
</model>

For reference to the configuration of each filter, see Filters Configuration Reference.

Standard Filters
Mule includes the following standard filters that you can apply to your routers:

• Payload Type Filter


• Expression Filter
• ° Using JXPath Expressions
° Using OGNL Expressions

• RegEx Filter
• Wildcard Filter
• Exception Type Filter
• Message Property Filter
• Logic Filters
• ° And Filter
° Or Filter
° Not Filter

Payload Type Filter

Checks the class type of the payload object inside a message.

<payload-type-filter expectedType="java.lang.String">

Expression Filter

Evaluates a range of expressions. Use the evaluator attribute to specify the expression evaluator to
use, one of the following: header, payload-type, exception-type, wildcard, regex, ognl, xpath, jxpath,
bean, groovy, or custom. Use the expression attribute to set the actual expression. If the expression
type is xpath, bean, or ongl, the expression should be a boolean. If the expression type is custom, set
the customEvaluator attribute to the name of the custom evaluator, which must be registered with the

Document generated by Confluence on Oct 27, 2008 21:07 Page 263


ExpressionEvaluatorManager (see Creating Custom Filters). For more information on using expression
evaluators, see Using Expression Evaluators.

Optionally, set the nullReturnsTrue attribute to true if you want to return true whenever the
expression is null.

Using JXPath Expressions

JXPath is an XPath interpreter that can apply XPath expressions to XML DOM objects or any other object
graph. For more information about JXPath, see the JXpath user guide, JXPath tutorial, or XPath tutorial.

<expression-filter evaluator="jxpath" expression="(msg/header/resultcode)='success'">

You can also use the JXPath filter from the XML module, which supports some additional properties.

Using OGNL Expressions

OGNL is a simple yet very powerful expression language for plain Java objects. Similar to JXPath, it
works on object graphs, and thus the corresponding filter enables simple and efficient content routing for
payloads. For example:

<expression-filter evaluator="ognl" expression="[MULE:0].equals(42)"/>

or more simply:

<ognl-filter expression="[MULE:0].equals(42)"/>

This filter would block any messages whose payloads are not arrays or lists and do not contain the value
42 as the first element.

RegEx Filter

Applies a regular expression pattern to the message payload. The filter applies toString() to the
payload, so you might also want to apply a PayloadTypeFilter to the message using an AndFilter to make
sure the payload is a String.

<regex-filter pattern="the quick brown (.*)"/>

Wildcard Filter

Applies a wildcard pattern to the message payload. The filter applies toString() to the payload, so you
might also want to apply a PayloadTypeFilter to the message using an AndFilter to make sure the payload
is a String.

For the string "the quick brown fox jumped over the lazy dog", the following patterns would match:

• *x jumped over the lazy dog


• the quick*
• *fox*

<wildcard-filter pattern="the quick brown *"/>

Exception Type Filter

A filter that matches an exception type.

<exception-type-filter expectedType="java.lang.RuntimeException"/>

Message Property Filter

This filter allows you add logic to your routers based on the value of one or more properties of a
message. This filter can be very powerful because the message properties are exposed, allowing you to

Document generated by Confluence on Oct 27, 2008 21:07 Page 264


reference any transport-specific or user-defined property. For example, you can match one or more HTTP
headers for an HTTP event, match properties in JMS and email messages, and more.

By default, the comparison is case sensitive. You can set the caseSensitive attribute to override this
behavior.

<message-property-filter pattern="Content-Type=text/xml" caseSensitive="false"/>

The expression is always a key value pair. If you want to use more complex expressions, you can use the
logic filters. The following example shows two filters :

<and-filter>
<message-property-filter pattern="JMSCorrelationID=1234567890"/>
<message-property-filter pattern="JMSReplyTo=null"/>
</and-filter>

Logic Filters

There are three logic filters that can be used with other filters: And, Or, and Not. Logic filters can be
nested so that more complex logic can be expressed.

And Filter

An And filter combines two filters and only accepts the message if it matches the criteria of both filters.

<and-filter>
<payload-type-filter expectedType="java.lang.String"/>
<regex-filter pattern="the quick brown (.*)"/>
</and-filter>

Or Filter

The Or filter considers two filters and accepts the message if it matches the criteria of either one of the
filters.

<or-filter>
<payload-type-filter expectedType="java.lang.String"/>
<payload-type-filter expectedType="java.lang.StringBuffer"/>
</or-filter>

Not Filter

A Not filter accepts the message if it does not match the criteria in the filter.

<not-filter>
<payload-type-filter expectedType="java.lang.String"/>
</not-filter>

Transport and Module Filters


Several Mule transports and modules provide their own filters. For example, the XML module includes a
filter to determine if a message is XML. For more information, see Available Transports and Using Mule
Modules. Also, there are filters on MuleForge that have been contributed by the community.

Creating Custom Filters


The standard filters handle most filtering requirements, but you can also create your own filter. To create
a filter, implement the Filter interface , which has a single method:

public boolean accept(MuleMessage message);

Document generated by Confluence on Oct 27, 2008 21:07 Page 265


This method returns true if the message matches the criteria that the filter imposes. Otherwise, it returns
false.

Document generated by Confluence on Oct 27, 2008 21:07 Page 266


Configuring a Transport

This page last changed on Oct 22, 2008 by jackie.wheeler.

Configuring a Transport
You can configure a transport in the following ways:

• Define a connector configuration using the <connector> element in the Mule XML configuration file.
• Set transport properties on endpoints to customize the transport behavior for a single endpoint
instance.
• Use an endpoint URI that defines the scheme and connection information for the transport, such
as tcp://localhost:12345. See Mule Endpoint URIs for more information. The URI consists of the
protocol followed by transport-specific information, and then zero or more parameters to set as
properties on the connector.

This page describes the common properties for all transports. The actual configuration parameters for
each transport type are described separately for each transport. To see the details of a specific transport,
see Available Transports.

Common Connector Attributes and Properties

Attribute Description Required

name The identifying name of the Yes


connector

createMultipleTransactedReceivers Whether to create multiple No


concurrent receivers for this
connector. This property is
used by transports that support
transactions, specifically
receivers that extend the
TransactedPollingMessageReceiver,
and provides better throughput.

numberOfConcurrentTransactedReceivers
If No
createMultipleTransactedReceivers
is set to true, the number of
concurrent receivers that will be
launched.

dynamicNotification Whether to enable dynamic No


notification.

Property Description Default Required

abstract-exception- The exception strategy The default exception No


strategy to use when errors strategy set on the
occur in the connector. Mule Configuration.

receiver-threading- The threading The default receiver Yes


profile properties and threading profile set on
WorkManager to use the Mule Configuration
when receiving events
from the connector.

Document generated by Confluence on Oct 27, 2008 21:07 Page 267


dispatcher-threading- The threading The default dispatcher Yes
profile properties and threading profile set on
WorkManager to use the Mule Configuration.
when dispatching
events from the
connector.

connection-strategy The object responsible org.mule.transport. Yes


for controlling how SingleAttemptConnectionStrategy
connection failures and
retries are handled.
The connection strategy
can attempt to make
a connection based
on frequency, retry
attempts, Jmx, or some
other trigger. NOTE:
this feature is not yet
available for 2.0.

service-overrides A map of service No


configuration values
that can be used to
override the default
configuration for this
transport.

Retry Policies
Retry policies are used to configure how a connector behaves when its connection fails. For complete
information, see Configuring Retry Policies.

Creating Your Own Transport


For information on creating a custom transport for Mule, see Creating Transports.

Detailed Configuration Information


• Threading profiles
° Receiver threading profile
° Dispatcher threading profile

• Service overrides

Receiver Threading Profile

Attributes of <receiver-threading-profile...>

Name Type Required Default Description

maxThreadsActive integer no The maximum


number of threads
that will be used.

maxThreadsIdle integer no The maximum


number of idle or
inactive threads

Document generated by Confluence on Oct 27, 2008 21:07 Page 268


that can be in the
pool before they
are destroyed.

threadTTL integer no Detemines how


long an inactive
thread is kept in
the pool before
being discarded.

poolExhaustedAction WAIT/DISCARD/ no When the


DISCARD_OLDEST/ maximum pool
ABORT/RUN size or queue size
is bounded, this
value determines
how to handle
incoming tasks.
Possible values
are: WAIT
(wait until a
thread becomes
available. This
policy should,
in general, not
be used if the
minimum number
of threads is zero,
in which case
a thread may
never become
available.),
DISCARD
(throw away the
current request
and return),
DISCARD_OLDEST
(throw away the
oldest request
and return),
ABORT (throw a
RuntimeException),
and RUN (the
thread making
the execute
request runs the
task itself. This
policy helps guard
against lockup.)

threadWaitTimeout integer no How long to wait


in milliseconds
when the pool
exhausted
action is WAIT.
If the value is
negative, it will
wait indefinitely.

doThreading boolean no true Whether threading


should be used
(default is true).

maxBufferSize integer no Determines how


many requests

Document generated by Confluence on Oct 27, 2008 21:07 Page 269


are queued when
the pool is at
maximum usage
capacity and the
pool exhausted
action is WAIT.
The buffer is used
as an overflow.

Dispatcher Threading Profile

Attributes of <dispatcher-threading-profile...>

Name Type Required Default Description

maxThreadsActive integer no The maximum


number of threads
that will be used.

maxThreadsIdle integer no The maximum


number of idle or
inactive threads
that can be in the
pool before they
are destroyed.

threadTTL integer no Detemines how


long an inactive
thread is kept in
the pool before
being discarded.

poolExhaustedAction WAIT/DISCARD/ no When the


DISCARD_OLDEST/ maximum pool
ABORT/RUN size or queue size
is bounded, this
value determines
how to handle
incoming tasks.
Possible values
are: WAIT
(wait until a
thread becomes
available. This
policy should,
in general, not
be used if the
minimum number
of threads is zero,
in which case
a thread may
never become
available.),
DISCARD
(throw away the
current request
and return),
DISCARD_OLDEST
(throw away the
oldest request
and return),

Document generated by Confluence on Oct 27, 2008 21:07 Page 270


ABORT (throw a
RuntimeException),
and RUN (the
thread making
the execute
request runs the
task itself. This
policy helps guard
against lockup.)

threadWaitTimeout integer no How long to wait


in milliseconds
when the pool
exhausted
action is WAIT.
If the value is
negative, it will
wait indefinitely.

doThreading boolean no true Whether threading


should be used
(default is true).

maxBufferSize integer no Determines how


many requests
are queued when
the pool is at
maximum usage
capacity and the
pool exhausted
action is WAIT.
The buffer is used
as an overflow.

Service Overrides

Attributes of <service-overrides...>

Name Type Required Default Description

messageReceiver name (no spaces) no

transactedMessageReceiver
name (no spaces) no

xaTransactedMessageReceiver
name (no spaces) no

dispatcherFactory name (no spaces) no

inboundTransformer name (no spaces) no

outboundTransformername (no spaces) no

responseTransformer name (no spaces) no

endpointBuilder name (no spaces) no

messageAdapter name (no spaces) no

streamMessageAdapter
name (no spaces) no

serviceFinder name (no spaces) no

Document generated by Confluence on Oct 27, 2008 21:07 Page 271


sessionHandler name (no spaces) no

Document generated by Confluence on Oct 27, 2008 21:07 Page 272


Configuring Retry Policies

This page last changed on Oct 24, 2008 by jackie.wheeler.

Configuring Retry Policies


Retry policies configure how a connector behaves when its connection fails. Different policies can be used
to control how a reconnection is made based on type of exception, number and/or frequency of retry
attempts, notifications, and more. Retry policies are available as of Mule 2.1.

If you are using the Enterprise Edition of Mule, there are several standard retry policies available that you
can configure using the Retry schema. If you are using the Community Edition of Mule, you must create
your own policies and configure them using standard Spring syntax rather than the Retry schema.

Configuring Retry Policies with the Retry Schema

This section describes the retry policies you can configure directly in your XML by including the mule-
retry-ee.xsd schema. You import the schema as follows:

<mule xmlns="http://www.mulesource.org/schema/mule/core/2.1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:retry="http://www.mulesource.com/schema/mule/retry/2.1"
xsi:schemaLocation="
http://www.mulesource.org/schema/mule/core/2.1 http://www.mulesource.org/schema/mule/core/2.1/
mule.xsd
http://www.mulesource.com/schema/mule/retry/2.1 http://www.mulesource.com/schema/mule/retry/2.1/
mule-retry-ee.xsd">

Simple Policy
This policy allows the user to configure how many times a retry should
be attempted and how long to wait between retries.

Attributes of <simple-policy...>

Name Type Required Default Description

frequency long no 2000 How often (in ms)


to retry

count integer no 2 How many retry


attempts to make

For example:

<tcp:connector name="tcpConnector">
<retry:simple-policy count="5" frequency="1000"/>
</tcp:connector>

Forever Policy
Retry an infinite amount of times at the specified frequency.

Document generated by Confluence on Oct 27, 2008 21:07 Page 273


Attributes of <forever-policy...>

Name Type Required Default Description

frequency long no 2000 How often (in ms)


to retry

For example:

<tcp:connector name="tcpConnector">
<retry:forever-policy frequency="5000"/>
</tcp:connector>

Custom Policy
A user-defined retry policy.

Attributes of <custom-policy...>

Name Type Required Default Description

class class name no A class that


implements the
RetryPolicyTemplate
interface.

Child Elements of <custom-policy...>

Name Cardinality Description

spring:property 0..*

For example:

<tcp:connector name="tcpConnector">
<retry:custom-policy class="org.mule.retry.test.TestRetryPolicyTemplate">
<spring:property name="fooBar" value="true"/>
<spring:property name="revolutions" value="500"/>
</retry:custom-policy>
</tcp:connector>

Retry Notifiers

A retry notifier is called upon each retry attempt and is also configurable.

Connect Notifier
Fires a ConnectionNotification upon each retry attempt.

For example:

<tcp:connector name="tcpConnector">
<retry:simple-policy>
<retry:connect-notifier/>
</retry:simple-policy>
</tcp:connector>

Document generated by Confluence on Oct 27, 2008 21:07 Page 274


Custom Notifier
A user-defined retry notifier.

Attributes of <custom-notifier...>

Name Type Required Default Description

class class name no A class that


implements the
RetryNotifier
interface.

Child Elements of <custom-notifier...>

Name Cardinality Description

spring:property 0..*

For example:

<tcp:connector name="tcpConnector">
<retry:simple-policy>
<retry:custom-notifier class="org.mule.retry.test.TestRetryNotifier">
<spring:property name="color" value="red"/>
</retry:custom-notifier>
</retry:simple-policy>
</tcp:connector>

Configuring Separate Connectors for Inbound and Outbound

The retry policy for a connector is used for both inbound and outbound connections. If you require
a different behavior for inbound and outbound connections, you can achieve this by configuring two
connectors with the different policies and reference them from the inbound and outbound endpoints,
respectively.

Default Retry Policy

The default retry policy is used for any connector that does not have retry explicitly configured. You can
set the default policy using the <configuration> element:

<configuration>
<retry:simple-policy count="3"/>
</configuration>

Creating a Custom Retry Policy


To create a custom retry policy, you implement the interface RetryPolicy , where the method
PolicyStatus applyPolicy(Throwable cause) takes some action based on the type of exception
and returns PolicyStatus to indicate whether the policy has been exhausted or should continue to retry.
You also create a RetryPolicyTemplate , which is what you actually configure on the connector. The
template should generally inherit from AbstractPolicyTemplate and have the method RetryPolicy
createRetryInstance() return an instance of your custom RetryPolicy. At runtime, a new instance
of the RetryPolicy will be created each time the policy goes into effect, thereby resetting any state
information it may contain, such as counters.

Document generated by Confluence on Oct 27, 2008 21:07 Page 275


For example:

package com.acme.retry;

public class AstronomicalRetryPolicyTemplate extends AbstractPolicyTemplate


{
int totalPlanets;

public RetryPolicy createRetryInstance()


{
return new AstronomicalRetryPolicy(totalPlanets);
}

protected static class AstronomicalRetryPolicy implements RetryPolicy


{
int totalPlanets;

public AstronomicalRetryPolicy(int totalPlanets) { this.totalPlanets = totalPlanets; }

public PolicyStatus applyPolicy(Throwable cause)


{
if (AstronomyUtils.getPlanetsAligned() == totalPlanets)
{
return PolicyStatus.policyExhausted(cause);
}
else
{
Thread.sleep(5000);
return PolicyStatus.policyOk();
}
}
}

public int getTotalPlanets() { return totalPlanets; }


public void setTotalPlanets(int totalPlanets) { this.totalPlanets = totalPlanets; }
}

Configuring Retry Policies with the Spring Schema


Because the retry schema is available in Mule Enterprise Edition only, Mule Community users must use
standard Spring syntax for configuring a custom retry policy. For example:

<tcp:connector name="tcpConnector">
<spring:property name="retryPolicyTemplate">
<spring:bean class="com.acme.retry.AstronomicalRetryPolicyTemplate">
<spring:property name="totalPlanets" value="8"/>
</spring:bean>
</spring:property>
</tcp:connector>

Document generated by Confluence on Oct 27, 2008 21:07 Page 276


Configuring Security

This page last changed on Sep 08, 2008 by jackie.wheeler.

Configuring Security
This page is under construction

Mule allows you to authenticate requests via endpoints using transport-specific or generic authentication
methods. It also allows you to control method-level authorization on your service components. The
Security Manager is responsible for authenticating requests based on one or more security providers.
There is a simple Mule security provider wrapper that delegates to Acegi, which means you can use any
of the Acegi security providers such as JAAS, LDAP, CAS (Yale Central Authenication service), and DAO.
All security is provided via the Mule security API , so you can easily plug in custom implementations.

Configuring the Security Manager


The following describes how to configure a single Security provider on Mule, in this case an in-memory
DAO.
##update the rest of this page for 2.0

<mule-configuration>
<security-manager>
<security-provider name="memory-dao"
className="org.mule.extras.acegi.AcegiProviderAdapter">
<properties>
<container-property name="delegate" reference="daoAuthenticationProvider"/>
</properties>
</security-provider>
</security-manager>
....
</mule-configuration>

Note that the 'delegate' property is a container property meaning we need a container to get it from.
Here we configure a Spring Container Context to load our Security Providers from. you can set multiple
security-provider elements.

<container-context
className="org.mule.extras.spring.SpringContainerContext">
<properties>
<property name="configFile" value="securityContext.xml"/>
</properties>
</container-context>

The Spring Acegi configuration is where the real Security Provider configuration occurs.

<beans>
<bean id="daoAuthenticationProvider"
class="org.acegisecurity.providers.dao.DaoAuthenticationProvider">
<property name="userDetailsService">
<ref bean="inMemoryDaoImpl"/>
</property>
</bean>

<bean id="inMemoryDaoImpl" class="org.acegisecurity.userdetails.memory.InMemoryDaoImpl">


<property name="userMap">
<value>
ross=ross,ROLE_ADMIN
anon=anon,ROLE_ANONYMOUS
</value>
</property>

Document generated by Confluence on Oct 27, 2008 21:07 Page 277


</bean>
</beans>

Here we have a static DAO Security Provider that allows user credentials to be set in memory with two
users; ross and anon.

Encryption Strategies
The Security Manager can be configured with one or more Encryption strategies that can then be used
by encryption transformers, Security filters or secure Transport providers such as ssl or https. These
Encryption strategies can greatly simplify configuration for secure messaging as they can be shared
across components.

<security-manager>
<encryption-strategy name="PBE"
className="org.mule.impl.security.PasswordBasedEncryptionStrategy">
<properties>
<property name="password" value="mule"/>
</properties>
</encryption-strategy>
</security-manager>

This strategy can then be referenced by other components in the system such as filters or transformers.

<transformers>
<transformer name="EncryptedToByteArray"
className="org.mule.transformers.encryption.DecryptionTransformer">
<properties>
<property name="strategyName" value="PBE"/>
</properties>
</transformer>
</transformers>

Security Filters
Security filters can be configured on an object to either authenticate inbound requests or attach
credentials to outbound requests.

Endpoint Security Filter

As the name suggests, these types of filters are configured on endpoints. To configure a Http Basic Auth
filter on a http endpoint use the following -

<endpoint address="http://localhost:4567">
<security-filter
className="org.mule.extras.acegi.filters.http.HttpBasicAuthenticationFilter">
<properties>
<property name="realm" value="mule-realm"/>
</properties>
</security-filter>
</endpoint>

When a request is received the Authentication header will be read from the request and authenticated
against all Security Providers on the Security Manager. If you only want to validate on certain ones you
can supply a comma-separated list of Security Provider names.

<endpoint address="http://localhost:4567">
<security-filter useProviders="default,another"
className="org.mule.extras.acegi.filters.http.HttpBasicAuthenticationFilter"/>
</endpoint>

Document generated by Confluence on Oct 27, 2008 21:07 Page 278


Related Topics
The following topics are of interest to users wanting to enable authorization on service components or use
security technologies:

• JAAS Security
• PGP Security
• Component Authorization Using Acegi
• Setting up LDAP Provider for Acegi

Document generated by Confluence on Oct 27, 2008 21:07 Page 279


Controlling the Infrastructure with Mule Galaxy

This page last changed on Aug 04, 2008 by jackie.wheeler.

Controlling the Infrastructure with Mule Galaxy


Mule Galaxy helps you get control over your infrastructure by providing the following features:

• Governance: provides a centralized control point for policy management and compliance, ensuring
that your SOA adheres to your firm's policies.
• Registry: automatically detects and displays dependencies among services and manages service
lifecycles.
• Repository: stores and manages artifacts (including Mule configuration files, web services
frameworks, and any other artifact), providing version management and collaborative comments,
and allows you to publish the artifacts in a web browser using the Atom Publishing Protocol.

Mule Galaxy can be deployed either alongside Mule or as a standalone component in an enterprise's SOA
infrastructure. Mule Galaxy is available with Mule Enterprise Edition.

For complete information on Mule Galaxy, see the Mule Galaxy site.

Document generated by Confluence on Oct 27, 2008 21:07 Page 280


Creating a Custom XML Namespace

This page last changed on Sep 12, 2008 by jackie.wheeler.

Creating a Custom XML Namespace


This page is ready for review

XML schema definitions are used for each module to define the objects and properties that the module
makes available to Mule. These configuration elements are introduced using a namespace for each
module and associating the namespace with the schema. This page describes how configuration is
handled in Mule and what steps are required when writing a new module or transport in Mule.

Advantages of Using Namespaces


The use of namespaces provides the following advantages:

• Class names are removed from XML so that implementation details are hidden.
• All objects introduced by the module are self-contained by a namespace.
• The schema provides a domain-specific language (DSL) for the module where all objects and
properties are described in the schema with type validation.
• The schema can provide additional validation for types, value ranges, and required properties.

Using Module Schemas


Schemas are located in each package's main/resources/META-INF directory. The core schema is in the
mule-core package, the TCP schema is in the tcp package, and so on.

The Mule schema can be used directly or embedded inside Spring. In addition, Spring beans can be
created directly inside the Mule schema (just use <spring:bean .../>) and elements from other
namespaces can be placed in <other>...</other>.

Embedded Inside Spring

When working inside Spring, the top-level element is <beans>, associated with the usual Spring beans
namespace. At the top of the XML file, there are two or more namespace declarations:

<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mule="http://www.mulesource.org/schema/mule/core/2.0"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-2.0.xsd
http://www.mulesource.org/schema/mule/core/2.0 META-INF/mule.xsd">
<bean ....a spring bean here.../>
<mule:mule>
<!-- Mule configuration here -->
</mule:mule>
</beans>

This tells the XML parser (and your IDE XML editor) to bind the default namespace (no namespace prefix)
to the Spring Beans namespace URI and the mule namespace to the Mule core namespace URI. The
schemaLocation attribute provides a list of namespace URIs and the location of where the schema can be
found.

To make another module available to your configuration, you add a new namespace declaration for it. For
example:

<?xml version="1.0" encoding="UTF-8"?>

Document generated by Confluence on Oct 27, 2008 21:07 Page 281


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mule="http://www.mulesource.org/schema/mule/core/2.0"
xmlns:tcp="http://www.mulesource.org/schema/mule/tcp/2.0"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-2.0.xsd
http://www.mulesource.org/schema/mule/core/2.0 META-INF/mule.xsd
http://www.mulesource.org/schema/mule/tcp/2.0 META-INF/mule-tcp.xsd">

Direct Mule Namespace

This approach is similar to the embedded within Spring approach, but the initial namespace is mule:

<?xml version="1.0" encoding="UTF-8"?>


<mule xmlns="http://www.mulesource.org/schema/mule/core/2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-2.0.xsd
http://www.mulesource.org/schema/mule/core/2.0 META-INF/mule.xsd">
<!-- Mule config here -->
<spring:bean ...you can also embed Spring bean definitions directly.../>
<spring:beans>
<!-- and you can have nested spring defintions -->
</spring:beans>
</mule>

More on Mixing Mule and Spring

The Mule schema includes the ability to use Spring elements at certain points by including
<spring:bean> inside <mule>. These elements are handled explicitly by Mule code, which delegates their
processing to Spring.

Be careful when using Spring elements in your own schema, and check that they behave as expected.
The <bean> and <beans> elements are all forwarded to Spring for processing. In addition, the predefined
mule:mapType can be used and, when associated with the ChildMapDefinitionParser, will automatically
construct a map using Spring's <entry> elements (this is the only way that <entry> can be used
directly inside Mule elements). For examples, see the use of mapType in the Mule schema. Similar
behavior with ChildPropertiesDefinitionParser should also be possible (but ChildMapEntry and
ChildListEntryDefinitionParsers are unrelated to Spring).

Other namespaces can be introduced via <spring:beans> or by adding a dedicated element in a module
(see the Scripting module's <lang> element).

Documentation

You add documentation to the schema using the <xsd:annotation> and <xsd:documentation> tags:

<xsd:element name="my-element" type="myType">


<xsd:annotation>
<xsd:documentation>This element does this</xsd:documentation>
</xsd:annotation>
</xsd:element>
<xsd:complexType name="myType">
<xsd:annotation>
<xsd:documentation>This type does that</xsd:documentation>
</xsd:annotation>
</xsd:complexType>

While documentation can be added in various places within the schema, tools that use this information
follow certain conventions (see below). As a consequence, embedded documentation should:

• Be placed in the element, attribute, or associated type

Document generated by Confluence on Oct 27, 2008 21:07 Page 282


• Avoid duplicating information in element and type
• Avoid reference elements (<xsd:element ref="..."/>)
• Make documentation at each level correct and distinct (do not rely on inheritance, but try to avoid
duplication)

IntelliJ Idea

Idea will show documentation defined for an element or attribute, or for the associated type if those
are missing. The information is displayed when the user presses Ctrl-Q. However, it will not display
"inherited" documentation or text associated with references.

Eclipse

The Web Tools Platform (WTP) XML editor shows documentation defined for an element or attribute, or
for the associated type if those are missing. The information is displayed when you press F2 when an
element or attribute is selected or has the cursor on it. The same information is also shown when using
the context-sensitive auto-completion functionality by pressing the "CTRL-." key combination.

The WTP XML editor will display "inherited" documentation but does not show documentation associated
with referenced global elements.

Writing Configuration Handlers


When writing a new Mule transport of module, you will need to write a schema definition and the code
necessary to parse the XML, but most of the work is done for you. The following section will walk through
the process of:

• Defining the XML Schema: Describes all the objects that your module exposes, such as
transformers, components, filters, routers, agents, etc.
• Writing the Namespace Handler: Responsible for configuring the XML parsers for each of the
elements that your schema defines.
• Writing a Definition Parser for each of the elements (objects) defined in the schema
• Testing your Namespace Handler

Defining the Schema

If you are not familiar with XML schema, you may want to take an introductory course here. However,
Mule defines most of what you need out of the box, so it's fairly straightforward to jump in and write your
own. Following are a few key concepts:

• Complex Types are defined for each object in the module. Complex types define the elements and
attributes that make up the type. For example, a connectorType would define shared attributes for
all connectors and define any nested elements such as <service-overrides>.

<xsd:complexType name="connectorType" mixed="true">


<xsd:choice minOccurs="0" maxOccurs="unbounded">
<xsd:element name="receiver-threading-profile" type="threadingProfileType" minOccurs="0"
maxOccurs="1"/>
<xsd:element name="dispatcher-threading-profile" type="threadingProfileType" minOccurs="0"
maxOccurs="1"/>
<xsd:group ref="exceptionStrategies" minOccurs="0" maxOccurs="1"/>
<xsd:element name="service-overrides" type="serviceOverridesType" minOccurs="0" maxOccurs="1"/
>
</xsd:choice>

<xsd:attribute name="name" type="xsd:string" use="required"/>


<xsd:attribute name="createDispatcherPerRequest" type="xsd:boolean"/>
<xsd:attribute name="createMultipleTransactedReceivers" type="xsd:boolean"/>
</xsd:complexType>

Note that complex types can be extended (much like inheritance), so new complex types can
be built upon existing ones. Mule provides a number of base complex types out of the box
for connectors, agents, transformers, and routers. If you write one of these, your schema

Document generated by Confluence on Oct 27, 2008 21:07 Page 283


should extend the corresponding complex type. Using TCP as an example, here we define the
tcpConnectorType:

<xsd:import namespace="http://www.mulesource.org/schema/mule/core/2.0"/>

<xsd:complexType name="tcpConnectorType">
<xsd:complexContent mixed="true">
<xsd:extension base="mule:connectorType">
<xsd:attribute name="sendBufferSize" type="mule:substitutableInt"/>
<xsd:attribute name="receiveBufferSize" type="mule:substitutableInt"/>
<xsd:attribute name="receiveBacklog" type="mule:substitutableInt"/>
<xsd:attribute name="socketLinger" type="mule:substitutableInt"/>
<xsd:attribute name="sendTcpNoDelay" type="mule:substitutableBoolean"/>
<xsd:attribute name="tcpProtocolClassName" type="xsd:NMTOKEN"/>
<xsd:attribute name="sendTimeout" type="mule:substitutableInt"/>
<xsd:attribute name="receiveTimeout" type="mule:substitutableInt"/>
<xsd:attribute name="keepSendSocketOpen" type="mule:substitutableBoolean"/>
<xsd:attribute name="keepAlive" type="mule:substitutableBoolean"/>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>

This complex type extends the mule:connectorType type. Notice that we need to import the Mule
core schema since that is where the connectorType is defined.

Schema Types

Note that the types we use for int, boolean, and all numeric types are custom types
called substitutableInt or substitutableBoolean. These types allow for int values
and boolean values but also allow developers to use property placeholders, such
as ${tcp.keepAlive} as a valid value for the property. These placeholders will be
replaced at run-time by real values defined in property files.

Element definitions describe what elements are available in the schema. An element has a type, which
should be declared as a Complex Type. For example:

<xsd:element name="connector" type="tcpConnectorType"/>

This makes the connector element available within the tcp namespace.

The schema should be called mule-<short module name>.xsd and stored in the META-INF of the module
or transport.

Versioning

In Mule, the version of the schema is maintained in the schema URI. This means that the namespace and
the targetNamespace implicitly contain the schema version. Schema URIs use the following convention:

http://www.mulesource.org/schema/mule/core/2.0

The first part of the URI http://www.mulesource.org/schema/mule/ is the same for each schema. It is
then followed by the module's short name, followed by the version of the schema.

Schema Mapping

To stop the XML parser from loading Mule schemas from the Internet, you add a mapping file that maps
the remote schema location to a local classpath location. This mapping is done in a simple properties file
called spring.schemas located in the META-INF directory for the module/transport.

spring.schemas

http\://www.mulesource.org/schema/mule/tcp/2.0/mule-tcp.xsd=META-INF/mule-tcp.xsd

Document generated by Confluence on Oct 27, 2008 21:07 Page 284


Namespace Handler

The namespace handler is responsible for registering definition parsers, so that when an element in the
configuration is found, it knows which parser to use to create the corresponding object.

A namespace handler is a single class that is directly associated with a namespace URI. To make this
association, there needs to be a file called spring.handlers in the root of the META-INF directory of the
module or transport. The file contains the following:

spring.handlers

http\://www.mulesource.org/schema/mule/tcp/2.0=org.mule.providers.tcp.config.TcpNamespaceHandler

The TcpNamespaceHandler code is very simple because there is a base support class provided:

TcpNamespaceHandler.java

public class TcpNamespaceHandler extends NamespaceHandlerSupport


{
public void init()
{
registerBeanDefinitionParser("connector", new OrphanDefinitionParser(TcpConnector.class, true));
}
}

Here, there should be one or more registrations binding an element name with a definition parser.

Definition Parsers

The definition parser is where the actual object reference is created. It includes some Spring-specific
classes and terminology, so it's worth reading this introduction.

Mule already includes a number of useful definition parsers that can be used for most situations or
extended to suit your needs. You can also create a custom definition parser. The following table describes
the existing parsers. To see how they are used, see
org.mule.config.spring.handlers.MuleNamespaceHandler .

Parser Description

org.mule.config.spring.parsers.generic.OrphanDefinitionParser
Contructs a single, standalone bean from an
element. It is not injected into any other object.
This parser can be configured to automatically
set the class of the object, the init and destroy
methods, and whether this object is a singleton.

org.mule.config.spring.parsers.generic.ChildDefinitionParser
Creates a definition parser that will construct
a single child element and inject it into the
parent object (the enclosing XML element). The
parser will set all attributes defined in the XML
as bean properties and will process any nested
elements as bean properties too, except the
correct definition parser for the element will be
looked up automatically. If the class is read from
an attribute (when class is null), it is checked
against the constraint. It must be a subclass of
the constraint.

org.mule.config.spring.parsers.generic.ParentDefinitionParser
Processes child property elements in XML but
sets the properties on the parent object. This is
useful when an object has lots of properties and
it's more readable to break those properties into
groups that can be represented as a sub-element
in XML.

Document generated by Confluence on Oct 27, 2008 21:07 Page 285


org.mule.config.spring.parsers.collection.ChildMapEntryDefinitionParser
Allows a series of key value pair elements to be
set on an object as a Map. There is no need to
define a surrounding 'map' element to contain
the map entries. This is useful for key value pair
mappings.

org.mule.config.spring.parsers.AbstractChildBeanDefinitionParser
This definition parser introduces the notion
of hierarchical processing to nested XML
elements. Definition parsers that extend
this class are always child beans that get
set on the parent definition parser. A single
method getPropertyName must be overriden
to specify the name of the property to set
on the parent bean with this bean. Note
that the property name can be dynamically
resolved depending on the parent element. This
implementation also supports collections and
Maps. If the bean class for this element is set to
MapEntryDefinitionParser.KeyValuePair, it is
assumed that a Map is being processed and any
child elements will be added to the parent Map.

org.mule.config.spring.parsers.AbstractMuleSingleBeanDefinitionParser
This parser extends the Spring provided
AbstractBeanDefinitionParser to provide
additional features for consistently customizing
bean representations for Mule bean definition
parsers. Most custom bean definition parsers
in Mule will use this base class. The following
enhancements are made:

• Attribute mappings can be registered to


control how an attribute name in Mule XML
maps to the bean name in the object being
created.
• Value mappings can be used to map key
value pairs from selection lists in the XML
schema to property values on the bean being
created. These are a comma-separated list
of key=value pairs.
• Provides an automatic way of setting the
init-method and destroy-method for this
object. This will then automatically wire the
bean into the lifecycle of the application
context.
• The singleton property provides a fixed
way to make sure the bean is always a
singleton or not.

Naming Conventions

The number and variety of definition parsers is growing rapidly. To make them more manageable, please
use the following conventions.

• Group by function. Abstract bases live in org.mule.config.spring.parsers. Under that we have


generic, specific, and collection, which should be self-explanatory. Inside those you may want
to add further grouping (e.g., specific.security).
• Use consistent names for the relationship of the object being created with the surrounding context:
° Child objects are injected into parents (the enclosing DOM element)
° Grandchild are like child, but recurse up the DOM tree more than one generation
° Orphan objects stand alone
° Named objects are injected into a target identified by name rather than DOM location.
° Parent definition parsers are something like facades, providing an alternative interface to the

parent.

Document generated by Confluence on Oct 27, 2008 21:07 Page 286


Testing

Testing the namespace handler is pretty simple. You configure the object in Mule XML, start the server,
and check that the values have been set correctly. For example:

public class TcpNamespaceHandlerTestCase extends FunctionalTestCase


{
protected String getConfigResources()
{
return "tcp-namespace-config.xml";
}

public void testConfig() throws Exception


{
TcpConnector c = (TcpConnector)managementContext.getRegistry().lookupConnector("tcpConnector");
assertNotNull(c);
assertEquals(1024, c.getReceiveBufferSize());
assertEquals(2048, c.getSendBufferSize());
assertEquals(50, c.getReceiveBacklog());
assertEquals(3000, c.getReceiveTimeout());
assertTrue(c.isKeepAlive());
assertTrue(c.isConnected());
assertTrue(c.isStarted());

}
}

Extending Existing Handlers


Instead of creating a new handler, you can extend an existing transport and add new properties and
elements. For example, the SSL transport extends the TCP transport.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>


<xsd:schema xmlns="http://www.mulesource.org/schema/mule/ssl/2.0"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:mule="http://www.mulesource.org/schema/mule/core/2.0"
xmlns:tcp="http://www.mulesource.org/schema/mule/tcp/2.0"
targetNamespace="http://www.mulesource.org/schema/mule/ssl/2.0"
elementFormDefault="qualified"
attributeFormDefault="unqualified">

<xsd:import namespace="http://www.w3.org/XML/1998/namespace"/>
<xsd:import namespace="http://www.mulesource.org/schema/mule/core/2.0"
schemaLocation="http://www.mulesource.org/schema/mule/core/2.0/mule.xsd" />
<xsd:import namespace="http://www.mulesource.org/schema/mule/tcp/2.0"
schemaLocation="http://www.mulesource.org/schema/mule/tcp/2.0/mule-tcp.xsd"/>

<xsd:element name="connector" substitutionGroup="mule:abstract-connector">


<xsd:annotation>
<xsd:documentation>
Connect Mule to an SSL socket, to send or receive data via the network.
</xsd:documentation>
</xsd:annotation>
<xsd:complexType>
<xsd:complexContent>
<xsd:extension base="tcp:tcpConnectorType">
<xsd:sequence>
<xsd:element minOccurs="0" maxOccurs="1" name="client" type="mule:tlsClientKeyStoreType"/>
<xsd:element minOccurs="0" maxOccurs="1" name="key-store" type="mule:tlsKeyStoreType"/>
<xsd:element minOccurs="0" maxOccurs="1" name="server" type="mule:tlsServerTrustStoreType"/>
<xsd:element minOccurs="0" maxOccurs="1" name="protocol-handler" type="mule:tlsProtocolHandler"/>
</xsd:sequence>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>

Document generated by Confluence on Oct 27, 2008 21:07 Page 287


</xsd:element>

Simple Recipe
The following recipe is sufficient for a simple transport (like UDP). The ordering helps guarantee complete
coverage.

1. Write a test case for the connector.


a. Use IDE's auto completion to test each public getter (as a first approximation to the public API
- tidy by hand).
b. Set the test value to something other than the default.
2. Write the XML configuration for the connector (test/resources/foo-connector-test.xml) using
the properties from the test (make sure the import section is correct).
3. Write the schema definition (tweaking until the XML connector config shows no errors) (META-INF/
mule-foo.xsd).
4. Write the namespace handler (and any needed definition parsers) (src/main/java/org/mule/
providers/foo/config/FooNamespaceHandler)
5. Set the Spring handler mapping (META-INF/spring.handlers).
6. Set the local schema mapping (META-INF/spring.schemas).
7. Make sure the test runs.
8. Check properties against the documentation and make consistent (but note that things like
connection strategy parameters are handled by an embedded element that is itself inherited from
the connectorType) and then re-run the test.

Resources
• A useful set of PDF slides that give an overview of the new approach in Spring and (slides
29 on) given an introductory example. The Mule code is more complex, but follows the same
structure: org.mule.config.spring.handlers.MuleNamespaceHandler is the namespace handler;
org.mule.config.spring.parsers.AbstractMuleBeanDefinitionParser and subclasses are the
bean definition parsers.
• A couple of blog posts (1, 2) that give a developer's-eye overview.
• Useful papers on mutable/extensible containers 1, 2

Document generated by Confluence on Oct 27, 2008 21:07 Page 288


Creating Additional Extensions

This page last changed on Jul 02, 2008 by jackie.wheeler.

This page is under construction

Creating Additional Extensions


In addition to transports, you can create other types of modules. ##describe additional extensions you
can create.## For a quick start, you can use the Maven project archetype for Mule as a code template for
your Mule projects. ##more here##

Document generated by Confluence on Oct 27, 2008 21:07 Page 289


Project Archetype

This page last changed on Jul 08, 2008 by jackie.wheeler.

Project Archetype
Mule provides Maven archetypes that you can use as code templates for your Mule projects. These
templates include a set of implementation notes and todo pointers that help you get started quickly. The
Mule project archetype will help you generate a tailored boilerplate project in seconds. If you want to
create a transport, use the Transport Archetype instead.

Follow the instructions below to create template files, including all the necessary Java boilerplate and
detailed implementation instructions in comments, for a new Mule project.

The project archetype is publicly available from the central maven repository.

Configuring Maven
Edit the file settings.xml (usually in $HOME/.m2) so that Maven will allow you to execute Mule plugins.

<settings>
...
<pluginGroups>
<pluginGroup>org.mule.tools</pluginGroup>
</pluginGroups>
...
</settings>

Using the Archetype


First, open a command shell and change to the directory where you want to create your project.

> cd yourDir

Next, you will execute the archetype and generate the code.

> mvn mule-project-archetype:create -DartifactId=xxx -DmuleVersion=2.0.0

You pass in two system parameters:

• artifactId: The short name for the project (such as 'myApp' or 'java6-extensions')
• muleVersion: The version of the Mule project archetype you want to use. This will also be the default
Mule version used for the generated artifact.

The plug-in will ask various questions (described below) and then generate the files. You can also use
this plug-in without user prompts by entering all the arguments at the command line. For a full list of
arguments that can be passed in, see the Command Line Options.

The Questions Explained


The plug-in prompts you to answer several questions about the project you are writing. These may vary
according to the options you select. An example of the output is shown below.

Provide a description of what the project does:

You should provide an accurate description of the project with any high-level details of what you can or
cannot do with it. This text will be used where a description of the project is required.

Document generated by Confluence on Oct 27, 2008 21:07 Page 290


Which version of Mule is this project targeted at?

The version of Mule you want to use for your project. This will default to the archetype version passed in
on the command line.

Will this project be hosted on MuleForge?

If the project is going to be hosted on MuleForge, additional information will be added to your project for
linking to its issue tracker, web site, build server, and deployment information.

Will this project have a custom schema for configuring it in XML?

If your project offers configuration via XML, you should define an XML schema that defines how the
project is configured. If you do not use this option, users will have to use generic configuration to use
your project.

What is the base Java package path for this module?

This should be a Java package path for you project, such as org/mule/modules/foo. Note that you must
use slashes for separators, not periods.

What type of project is this?

Specifies the type of project that will be created. Typically, the project structure will remain the same for
each project type, but the POM configuration may change to inherit from a different parent POM.

Will this project need to make objects available in the Registry as soon as it's loaded?

The registry bootstrap is a properties file that specifies class names of simple objects that can be made
available in the Mule Registry as soon as the module is loaded. This is useful for registering custom
transformers or property extractors.

The custom option allows you to deviate from the existing endpoint styles and parse your own.

Example Console Output


[INFO] description:
********************************************************************************

Provide a description of what the project does:

[default:]
********************************************************************************

[INFO] muleVersion:
********************************************************************************

Which version of Mule is this module targeted at?

[default: 2.0.0]
********************************************************************************

[INFO] packagePath:
********************************************************************************

What is the base Java package path for this module? (i.e. org/mule/modules
or org/mule/examples):

[default: org/mule/applications]
********************************************************************************

Document generated by Confluence on Oct 27, 2008 21:07 Page 291


[INFO] forgeProject:
********************************************************************************

Will This project be hosted on MuleForge? [y] or [n]

[default: y]
********************************************************************************

[INFO] projectType:
********************************************************************************

What type of project is this?


- [s]tand alone project
- [e]xample project that may be hosted on the MuleForge or in the Mule distribution
- [m]ule module to be hosted on the MuleForge on in the Mule distribution

[default: s]
********************************************************************************

[INFO] hasCustomSchema:
********************************************************************************

Will This project have a custom schema for configuring the module in Xml?

[default: n]
********************************************************************************

[INFO] hasBootstrap:
********************************************************************************

Will This project need to make objects available in the Registry as soon as it's loaded?
[default: n]
********************************************************************************

Command Line Options


By default, this plug-in runs in interactive mode, but it's possible to run it in 'silent' mode by using the
following option:

-Dinteractive=false

The following options can be passed in:

Name Example Default Value

artifactId -DartifactId=mule-module-xxx mule-application-<artifactId>

description -Ddescription="some text" none

muleVersion -DmuleVersion2.0.0 none

hasCustomSchema -DhasCustomSchema=true true

hasBootstrap -DhasBootstrap=true false

projectType -DprojectType=e s (stand alone)

Document generated by Confluence on Oct 27, 2008 21:07 Page 292


packagePath -DpackagePath=org/mule/ org/mule/application/
modules/xxx <artifactId>

forgeProject -DforgeProject=true true

version -Dversion=1.0-SNAPSHOT <muleVersion>

groupId - org.mule.application.<artifactId>
DgroupId=org.mule.applicationxxx

basedir -Dbasedir=/projects/mule/tools <current dir>

Document generated by Confluence on Oct 27, 2008 21:07 Page 293


Creating Custom Routers

This page last changed on Sep 12, 2008 by jackie.wheeler.

Creating Custom Routers


Typically, you implement custom routing with filters, but occasionally you may need to implement a
customer router.

Custom Outbound Routers


Outbound routers control how a message gets routed to a list of endpoints. For example, sometimes a
message gets routed based on simple rules or business logic, whereas in other cases you may multicast a
message to every router.

The easiest way to write an outbound router is to extend the


org.mule.routing.outbound.AbstractOutboundRouter class:

import org.mule.routing.outbound.AbstractOutboundRouter;

public class CustomOutboundRouter extends AbstractOutboundRouter {


....
}

There are two methods you must implement that control how messages will be routed through the
system. First, you must implement the isMatch method. This determines if a message should be
processed by the router.

For example, to route only messages that have a payload containing the string "hello":

public boolean isMatch(MuleMessage message) throws RoutingException


{
return "hello".equals(message.getPayloadAsString());
}

The second method you must implement is the route method. Each outbound router has a list of
endpoints that are associated with it. The route method contains the logic to control how the event is
propagated to the endpoints.

For example, if there were two endpoints you want to route to based on a condition, you would use this
method to select the endpoint:

MuleMessage route(MuleMessage message, MuleSession session, boolean synchronous) throws


MessagingException {
OutboundEndpoint ep = null;
if (isConditionMet(message)) {
ep = getEndpoints().get(0);
} else {
ep = getEndpoints().get(1);
}
....

Once you've selected an endpoint, you must then dispatch or send the message to it based on whether or
not the message is synchronous:

try
{
if (synchronous)
{
return send(session, message, ep);
}
else
{
dispatch(session, message, ep);

Document generated by Confluence on Oct 27, 2008 21:07 Page 294


return null;
}
}
catch (MuleException e)
{
throw new CouldNotRouteOutboundMessageException(message, ep, e);
}
return result;
}

If the request is synchronous, you must use the send method to send the inbound messages
synchronously to the endpoint. The result from this is then returned. If the request is asynchronous, it is
sent using the dispatch method, and no response message is returned.

Custom Inbound Routers


Inbound routers control whether a message is consumed by an inbound endpoint. Typically, you do not
have to create custom routers, as the existing ones provide a high degree of customization using existing
or custom filters.

If a new inbound router class is needed, it will typically extend the


org.mule.routing.inbound.SelectiveConsumer
router. This class uses the Mule filter APIs to determine if a message should be consumed and can be
configured using the existing filters.

The other responsibility of inbound routers is to control how a message is processed by a service. It can
choose to:

• Consume the message and start a new message.


• Aggregate several messages.
• Forward an incoming message to an outbound transport and skip the service invocation.
• Pass on the original message.
For more information, examine the source code for the available inbound routers.

Document generated by Confluence on Oct 27, 2008 21:07 Page 295


Creating Custom Transformers

This page last changed on Sep 12, 2008 by jackie.wheeler.

Creating Custom Transformers


Transformers convert inbound data to an object type as required by the service component. They
also convert outbound data to an object type required by the transport, such as a JMS message. You
can configure transformers on inbound endpoints to ensure that the expected object type is always
received by the service component. Transformers configured on an outbound endpoint ensure that the
endpoint receives the the correct object type before dispatching the message. You can also chain multiple
transformers together to allow for finer-grained transformer implementations that are easier to reuse.

Mule provides several transformers, including XML transformers (such as XML to Object, XSLT, and DOM
to XML), encryption transformers that encrypt and decrypt data, compression transformers that compress
and decompress data, encoding transformers (such as Base 64 and SGML entity encoding and decoding),
and object transformers that serialize and deserialize objects and convert between strings and byte
arrays. For a list of the default transformers in Mule, see Using Transformers.

To create your own transformer, you implement the abstract class


org.mule.transformers.AbstractTransformer . This class is an abstract transformer implementation that
defines methods for controlling the object types this transformer supports and validates the expected
return type, leaving the developer to implement a single transform() method. If the transformer needs
access to the incoming message to retrieve properties useful for transformation, you can implement
AbstractMessageAwareTransformer instead, a sub-class of AbstractTransformer that also provides
access to the message.

Document generated by Confluence on Oct 27, 2008 21:07 Page 296


Creating Transports

This page last changed on Aug 21, 2008 by jackie.wheeler.

Creating Transports
This page is under construction

[ Overview ] [ Transport Interfaces ] [ Implementation ] [ Connectors ] [ Message Receivers ] [ Message


Dispatchers ] [ Service Descriptors ] [ Coding Standards ] [ Package Structure ]

Transports are used to provide connectivity to an underlying data source or message source in a
consistent way. Mule provides transports for many different protocols, including File, FTP, HTTP, JMS,
JDBC, Quartz, and many more. For a complete list, see Available Transports. There are also community-
created transports on MuleForge. If you need to send messages on a protocol other than those provided,
you can create a new transport.

Overview
When creating a new transport, you must implement a set of Mule interfaces in the org.mule.transport
package, and then extend the provided abstract classes. For a quick start, you can use the Maven
transport archetype as a code template for your transports.

Mule transports can be one of the following types:

1. inbound-only: Components can only subscribe to events. They cannot dispatch events.
2. outbound-only: Components can only dispatch events. They cannot subscribe to events.
3. inbound-outbound: Components can subscribe and dispatch events

Transport Interfaces
A transport consists of a set of interface implementations that expose the features for the underlying
transport. Cannot resolve external resource into attachment.

Interface Role

Connector Used to manage Receivers and Dispatchers and to


store any configuration information.

Message Receiver Implements the 'server-part' of the transport.


For example, a TcpMessageReceiver creates
a server socket to receive incoming requests.
A MessageReceiver instance is created when
components use this transport for inbound
communication.

Message Dispatcher Implements the 'client-part' of the transport.


For example, a TcpMessageDispatcher creates a
socket to send requests. A MessageDispatcher
instance is created when components use this
transport for outbound communication.

Message Adapter Is contained in the event and wraps the


underlying message type used by this transport.
To use TCP as an example, the message adapter
simply wraps a byte array. For JMS, the JMS
message payload is exposed as the message's
payload and all headers and user properties are

Document generated by Confluence on Oct 27, 2008 21:07 Page 297


accessible using getProperty/setProperty on the
message adapter.

Transformers Transformers are used to marshal data to and


from the transport-specific data format, such as
an HTTP Request or JMS message.

Endpoints The means of configuring communication channels


to and from components. The endpoint defines
which transport protocol to use and includes
settings like the host or queue name, the filter to
use, and transaction info. Defining an endpoint
on a component will cause Mule to create the
necessary transport connector for the protocol
being used.

When writing a transport, you must implement the following interfaces that define the contract between
Mule and the underlying technology.

org.mule.api.transport.Connector

The connector is used by Mule to register listeners and create message dispatchers for the transport.
Configuration parameters that should be shared by all Message Receivers and Dispatchers are stored
on the connector. Usually, only one connector instance is needed for multiple inbound and outbound
endpoints as multiple Message Receivers and Dispatchers can be associated with a connector. However,
where the underlying transport API has the notion of a connection such as the JMS or JDBC API, there
should be a one-to-one mapping between the Mule connector and the underlying connection.

org.mule.api.transport.MessageReceiver

The Message Receiver is used to receive incoming data from the underlying transport and package it
as an event. The Message Receiver is essentially the server implementation of the transport (where the
Message Dispatcher is a client implementation). For example, the HTTP Message Receiver is an HTTP
server implementation that accepts HTTP requests. An implementation of this class is needed if the
transport supports inbound communication.

org.mule.api.transport.MessageDispatcher

The Message Dispatcher is used to send events, which is akin to making client calls with the underlying
technology. For example, the Axis Message Dispatcher will make a web service call. An implementation of
this class is needed if the transport supports outbound communication.

org.mule.api.transport.MessageDispatcherFactory

This is a factory class used to create MessageDispatcher instances. An implementation of this class is
needed if the transport supports outbound communication.

org.mule.api.transport.MessageAdapter

The message adapter is used to provide a consistent way of reading messages in Mule. The message
adapter provides methods for reading the payload of the message and reading message properties. These
properties may be message headers, custom properties, or other meta information about the message.

Implementation
Mule provides abstract implementations for all of the above interfaces. These implementations handle all
the Mule specifics, leaving a few abstract methods where custom transport code should be implemented.
Therefore, writing a custom transport is as easy as writing/embedding client and or server code specific
to the underlying technology. The following sections describes the implementations available to you.

For a quick start, use the Maven Transport Archetype.

Document generated by Confluence on Oct 27, 2008 21:07 Page 298


Connectors
The org.mule.transport.AbstractConnector implements all the default functionality required for Mule
connectors, such as threading configuration and receiver/dispatcher management. For details about the
standard connector properties, see Configuring a Transport.

You can set further properties on the connector that act as defaults. For example, you can set endpoint
properties that are used by default unless you override them when configuring a specific endpoint.

Sometimes the connector is responsible for managing a connection resource of the transport where the
underlying technology has the notion of a connection, such as in JMS or JDBC. These types of connectors
will have a one-to-one mapping between a Mule connector and the underlying connection. Therefore, if
you want to have two or more physical JMS connections in a single Mule instance, a new connector should
be created for each connection.

For other transports, there will be only one connector of a particular protocol in a Mule instance that
manages all endpoint connections. One such example would be socket-based transports such as TCP
where each receiver manages its own ServerSocket and the connector manages multiple receivers.

Methods to Implement

Method Name Description Required

doInitialise() Is called once all bean properties No


have been set on the connector
and can be used to validate and
initialize the connector's state.

doStart() If there is a single server No


instance or connection
associated with the connector
(such as AxisServer or a JMS or
JDBC Connection), this method
should put the resource in a
started state.

doConnect() Makes a connection to the No


underlying resource if this is
not handled at the receiver/
dispatcher level.

doDisconnect() Close any connection made in No


doConnect().

doStop() Should put any associated No


resources into a stopped state.
Mule automatically calls the
stop() method.

doDispose() Should clean up any open No


resources associated with the
connector.

Message Receivers
Message Receivers will behave a bit differently for each transport, but Mule provides some standard
implementations that can be used for polling resources and managing transactions for the resource.
Usually there are two types of Message Receivers: Polling and Listener-based.

• A Polling Receiver polls a resource such as the file system, database, and streams.

Document generated by Confluence on Oct 27, 2008 21:07 Page 299


• A Listener-based receiver registers itself as a listener to a transport. Examples would be JMS
(javax.message.MessageListener) and Pop3 (javax.mail.MessageCountListener). These base types
may be transacted.

The abstract implementations provided by Mule are described below.

Abstract Message Receiver

The AbstractMessageReceiver provides methods for routing events. When extending this class, you should
set up the necessary code to register the object as a listener to the transport. This will usually be a case
of implementing a listener interface and registering itself.

Methods to Implement

Method name Description Required

doConnect() Should make a connection to Yes


the underlying transport, such
as to connect to a socket or
register a SOAP service. When
there is no connection to be
made, this method should be
used to check that resources
are available. For example, the
FileMessageReceiver checks that
the directories it will be using
are available and readable.
The MessageReceiver should
remain in a 'stopped' state
even after the doConnect()
method is called. This means
that a connection has been
made but no events will be
received until the start() method
is called. Calling start() on
the MessageReceiver will call
doConnect() if the receiver
hasn't connected.

doDisconnect() Disconnects and tidies up Yes


any resources allocated using
the doConnect() method.
This method should return
the MessageReceiver in a
disconnected state so that it can
be connected again using the
doConnect() method.

doStart() Should perform any actions No


necessary to enable the receiver
to start receiving events. This is
different from the doConnect()
method, which actually makes a
connection to the transport but
leaves the MessageReceiver in a
stopped state. For polling-based
MessageReceivers, the start()
method simply starts the polling
thread. For the Axis message
receiver, the start method on
the SOAPService is called.
The action performed depends

Document generated by Confluence on Oct 27, 2008 21:07 Page 300


on the transport being used.
Typically, a custom transport
doesn't need to override this
method.

doStop() Should perform any actions No


necessary to stop the receiver
from receiving events.

doDispose() Is called when the connector is No


being disposed and should clean
up any resources. The doStop()
and doDisconnect() methods
will be called implicitly when this
method is called.

Polling Message Receiver

Some transports poll a resource periodically waiting for new data to arrive. The polling message receiver,
which is based on AbstractPollingMessageReceiver , implements the code necessary to set up and destroy
a listening thread and provides a single method poll() that is invoked repeatedly at a given frequency.

Methods to Implement

Method name Description Required

poll() Is executed repeatedly at a Yes


configured frequency. This
method should execute the logic
necessary to read the data and
return it. The data returned
will be the payload of the new
event. Returning null will cause
no event to be fired.

Transacted Polling Message Receiver

The TransactedPollingMessageReceiver can be used by transaction-enabled transports to manage polling


and transactions for incoming requests. This receiver uses a transaction template to execute requests in
transactions, and the transactions themselves are created according to the endpoint configuration for the
receiver. Derived implementations of this class must be thread safe, as several threads can be started at
once for an improved throughput.

Methods to Implement (in addition to those in the standard Message Receiver)

Method name Description Required

getMessages() Returns a list of objects that Yes


represent individual event
payloads. The payload can be
any type of object and will by
sent to Mule services wrapped in
a MuleEvent object.

processMessage(Object) is called for each object Yes


in the list returned from
getMessages(). Each object
processed is managed in its own
transaction.

Document generated by Confluence on Oct 27, 2008 21:07 Page 301


Thread Management

It's common for receivers to spawn a thread per request. All receiver threads are allocated using the
WorkManager on the receiver. The WorkManager is responsible for executing units of work in a thread. It
has a thread pool that allows threads to be reused and ensures that only a prescribed number of threads
will be spawned.

The WorkManager is an implementation of org.mule.api.context.WorkManager which really just a


wrapper of javax.resource.spi.work.WorkManager with some extra lifecycle methods. There is a
getWorkManager() method on the AbstractMessageReceiver that can be used to get reference to the
WorkManager for the receiver. Work items (i.e. the code to execute in a separate thread) must implement
javax.resource.spi.work.Work. This extends java.lang.Runnable and thus has a run() method which will
be invoked by the WorkManager.

When scheduling work with the WorkManager it is recommended that Developers call scheduleWork(...)
on the WorkManager rather than startWork(...).

Message Dispatchers
Messages Receivers are equivalent to a server for the transport in that it will serve up client requests.
Whereas, Message Dispatchers are the client implementation of the transport. They are responsible for
making client requests over the transport, such as writing to a socket or invoking a web service. The
AbstractMessageDispatcher provides a good base implementation leaving 3 methods for the custom
MessageDispatcher to implement.

Methods to Implement

Method name Description Required

doSend(UMOEvent) Should send the event payload Yes


over the transport. If there is
a response from the transport
it should be returned from this
method. The sendEvent method
is called when the endpoint is
running synchronously and any
response returned will ultimately
be passed back to the callee.
This method is executed in the
same thread as the request
thread.

doDispatch(UMOEvent) Is invoked when the endpoint Yes


is asynchronous and should
invoke the transport but
not return any result. If a
result is returned it should be
ignored and if they underlying
transport does have a notion of
asynchronous processing, that
should be invoked. This method
is executed in a different thread
to the request thread.

doReceive(long) Can be used to make arbitrary Yes


requests to a transport resource.
if the timeout is 0 the method
should block until an event on
the endpoint is received.

doConnect() Should make a connection Yes


to the underlying transport

Document generated by Confluence on Oct 27, 2008 21:07 Page 302


i.e. connect to a socket or
register a soap service. When
there is no connection to be
made this method should be
used to check that resources
are available. For example
the FileMessageDispatcher
checks that the directories
it will be using are
available and readable. The
MessageDispatcher should
remain in a 'stopped' state even
after the doConnect() method is
called.

doDisconnect() Disconnects and tidies up any Yes


resources allocated using the
doConnect() method. This
method should return the
MessageDispatcher into a
disconnected state so that it can
be connected again using the
doConnect() method

doDispose() Is called when the Dispatcher is No


being disposed and should clean
up any open resources.

Threads and Dispatcher Caching

Custom transports do not need to worry about dispatcher threading. Unless threading is turned off,
the Dispatcher methods listed above will be executed in their own thread. This is managed by the
AbstractMessageDispatcher.

When a request is made for a dispatcher, it is looked up from a dispatcher cache on the
AbstractConnector. The cache is keyed by the endpoint being dispatched to. If a Dispatcher is not found
one is created using the MessageDispatcherFactory and then stored in the cache for later. If developers
want a new Dispatcher to be created for each request they can set the disposeDispatcherOnCompletion
property on the AbstractConnector to true. This will essentially turn off dispatcher caching.

Message Adapters

MessageAdapters are usually simple objects that provide a uniform way of accessing an event payload
and associated metadata from a format used by the underlying transport. Almost all messaging protocols
have the notion of message payload and header properties, which means that a MessageAdapter just
needs to allow access to the header properties using standard Map notation i.e.

//Jms message id
String id = (String)message.getProperty("JMSMssageID");

or
//Http content length
int contentLength = message.getIntProperty("Content-Length");

Note that the property names use the same name that is used by the underlying transport; 'Content-
Length' is a standard Http header name and JMSMessageID is the equivalent bean property name on the
javax.jms.Message interface.

Message Adapter should extend the org.mule.provider.AbstractMessageAdapter as this abstract class


implements much of the mundane methods needed by the org.mule.providers.UMOMessageAdapter .

Methods to Implement

Document generated by Confluence on Oct 27, 2008 21:07 Page 303


Method name Description Required

getPayload() Returns the message payload 'as Yes


is'.

getPayloadAsString() Returns a java.lang.String Yes


representation of the message
payload.

getPayloadAsBytes() Returns a byte[] representation Yes


of the message payload.

getUniqueId() This ID is used by various No


routers when correlating
messages. The superclass
supplies a unique value by
default, but this method can
be overridden to provide an ID
recognised by the underlying
transport.

Service Descriptors
Each transport has a service descriptor that describes what classes are used to construct the transport.
For complete information, see Transport Service Descriptors.

Coding Standards
Package Structure
All mule providers have a similar package structure. They follow the convention of -

org.mule.transport.<protocol>

Where protocol is the protocol identifier of the transport such as 'tcp' or 'soap'. Any transformers and
filters for the transport are stored either a 'transformers' or 'filters' package under the main package.
Note that where a provider may have more than one implementation for a given protocol i.e. There are
two Soap implementations in Mule, Axis and CXF, the package name to be used should be soap not axis
or cxf.

Internationalisation

Any exceptions messages used in your transport provider implementation should be stored in a resource
bundle so that they can be internationalised . The message bundle is a standard java properties file and
must be located at -

META-INF/services/org/mule/i18n/<protocol>-messages.properties

Document generated by Confluence on Oct 27, 2008 21:07 Page 304


Transport Archetype

This page last changed on Oct 24, 2008 by jackie.wheeler.

Transport Archetype
[ Configuring Maven ] [ Using the Archetype ] [ The Questions Explained ] [ Example Console Output ] [
Command Line Options ]

Mule provides Maven archetypes that you can use as code templates for your Mule projects. These
templates include a set of implementation notes and todo pointers that help you get started quickly. The
Mule transport archetype will help you generate a tailored boilerplate transport project in seconds. If you
want to create a non-transport module, use the Project Archetype instead.

Follow the instructions below to create template files, including all the necessary Java boilerplate and
detailed implementation instructions in comments, for a new transport.

The transport archetype is publicly available from the central maven repository.

Configuring Maven
Edit the file settings.xml (usually in $HOME/.m2) so that Maven will allow you to execute Mule plugins
without having to specify the org.mule.tools prefix.

<settings>
...
<pluginGroups>
<pluginGroup>org.mule.tools</pluginGroup>
</pluginGroups>
...
</settings>

Using the Archetype


First, open a command shell and change to the directory where you want to create your project.

> cd yourDir

Next, you will execute the archetype and generate the code. Substitute the version number with the Mule
release you're using.

> mvn org.mule.tools:mule-transport-archetype:<version>:create -DtransportId=xxx -


DmuleVersion=2.0.0

You pass in two system parameters:

• transportId: The short name of the protocol (such as 'tcp' or 'jms') or the application name (such
as 'sap')
• muleVersion: The version of the Mule transport archetype you want to use. This will also be the
default Mule version used for the generated artifact.

The plug-in will ask various questions (described below) and then generate the files. You can also use
this plug-in without user prompts by entering all the arguments at the command line. For a full list of
arguments that can be passed in, see the Command Line Options.

The Questions Explained


The plug-in prompts you to answer several questions about the transport you are writing. These may
vary according to the options you select. An example of the output is shown below.

Document generated by Confluence on Oct 27, 2008 21:07 Page 305


Provide a description of what the transport does:

You should provide an accurate description of the transport with any high level details of what you can or
cannot do with it. This text will be used where a description of the project is required.

Which version of Mule is this transport targeted at?

The version of Mule you want to use for your transport. By default this will default to the version passed
in on the command line.

Will this project be hosted on MuleForge?

If the transport is going to be hosted on MuleForge, then additional information will be added to your
project for linking to its issue tracker, web site, build server and deployment information.

Will this transport have a custom schema for configuring the transport in Xml?

It's recommended that all new transports targeted for Mule 2.0 should define an Xml schema that defines
how the transport is configured. If you do not use this option, users will have to use generic configuration
to use your transport.

Can the transport receive inbound requests?

Can this transport receive inbound events? For example, the File transport allows you to listen for files
written to a directory. Jms allows you to listen for events being written to a topic or queue.

Does the Message Receiver need to poll the underlying resource?

In order to receive a message some transports need to do polling. E.g. the the file transport needs
to poll a directory to know something has been written there, whereas JMS provides a callback
(MessageListener) to deliver the message. This is only asked if the transport can receive inbound
requests.

If this transport will have a default inbound transformer, enter the name of the transformer?

If the protocol of the application being connected to has its own message type, you can define a
default inbound transformer, that will be invoked by default when defining endpoints that use this
transport. You need to enter the name of the transformer class (without package name) to generate i.e.
JmsMessageToObject.

Can the transport dispatch outbound requests?

Can events be written to this transport. In the case of the file transport, you can write file data to a
directory and with JMS you can write to a queue or topic.

If this transport will have a default outbound transformer, enter the name of the
transformer?

If the protocol of the application being connected to has its own message type, you can define a default
outbound transformer, that will be invoked by default when defining outbound endpoints that use this
transport. You need to enter the name of the transformer class (without package name) to generate i.e.
ObjectToJmsMessage.

Does this transport support transactions?

If the underlying resource for this transport is transactional, you can have Mule generate a transaction
wrapper that will allow users to enable transactions on endpoints defined using this transport.

Document generated by Confluence on Oct 27, 2008 21:07 Page 306


Does this transport use a non-JTA Transaction manager?

Not all technologies (such as JavaSpaces) support the standard JTA transaction manager. Mule can still
work with different non-JTA Transaction Managers, and this archetype can generate the necessary stubs
for you.

What type of endpoints does this transport use?

Mule supports a number of well defined endpoints

• resource endpoints (i.e. jms://my.queue)


• url endpoints (i.e. http://localhost:1234/context/foo?param=1)
• socket endpoints (i.e. tcp://localhost:1234)
• custom - parse your own

The option allows you to deviate from the existing endpoint styles and parse your own.

Example Console Output


********************************************************************************

Provide a description of what the transport does:


[default: ]
********************************************************************************
[INFO] muleVersion:
********************************************************************************

Which version of Mule is this transport targeted at?


[default: 2.2.0]
********************************************************************************
[INFO] forgeProject:
********************************************************************************

Will this project be hosted on MuleForge? [y] or [n]


[default: y]
********************************************************************************
[INFO] hasCustomSchema:
********************************************************************************

Will this transport have a custom schema for configuring the transport in Xml?
[y] or [n]
[default: y]
********************************************************************************
[INFO] hasReceiver:
********************************************************************************

Can the transport receive inbound requests? [y] or [n]


[default: y]
********************************************************************************
[INFO] isPollingReceiver:
********************************************************************************

Does the Message Receiver need to poll the underlying resource? [y] or [n]
[default: n]
********************************************************************************
[INFO] inboundTransformer:
********************************************************************************

If this transport will have a default inbound transformer, enter the name of the
transformer? (i.e. JmsMessageToObject)
[default: n]
********************************************************************************
[INFO] hasDispatcher:

Document generated by Confluence on Oct 27, 2008 21:07 Page 307


********************************************************************************

Can the transport dispatch outbound requests? [y] or [n]


[default: y]
********************************************************************************
[INFO] outboundTransformer:
********************************************************************************

If this transport will have a default outbound transformer, enter the name of the
transformer? (i.e. ObjectToJmsMessage)
[default: n]
********************************************************************************
[INFO] hasTransactions:
********************************************************************************

Does this transport support transactions? [y] or [n]


[default: n]
********************************************************************************
[INFO] hasCustomTransactions:
********************************************************************************

Does this transport use a non-JTA Transaction manager? [y] or [n]


(i.e. needs to wrap proprietary transaction management)
[default: n]
********************************************************************************
[INFO] endpointBuilder:
********************************************************************************

What type of endpoints does this transport use?


- [r]esource endpoints (i.e. jms://my.queue)
- [u]rl endpoints (i.e. http://localhost:1234/context/foo?param=1)
- [s]ocket endpoints (i.e. tcp://localhost:1234)
- [c]ustom - parse your own
[default: r]
********************************************************************************

Command Line Options


By default, this plug-in runs in interactive mode, but it's possible to run it in 'silent' mode by using the
following option:

-Dinteractive=false

The following options can be passed in:

Name Example Default Value

transportId -DtransportId=tcp none

description -Ddescription="some text" none

muleVersion -DmuleVersion2.0.0 none

hasCustomSchema -DhasCustomSchema=true true

forgeProject -DforgeProject=true true

hasDispatcher -DhasDispatcher=true true

hasTransactions -DhasTransactions=false false

Document generated by Confluence on Oct 27, 2008 21:07 Page 308


version -Dversion=1.0-SNAPSHOT <muleVersion>

inboundTransformer -DinboundTransformer=false false

groupId - org.mule.transport.<transportId>
DgroupId=org.mule.transport.tcp

hasReceiver -DhasReceiver=true true

isPollingReceiver -DisPollingReceiver=false false

outboundTransformer -DoutboundTransformer=false false

endpointBuilder -DendpointBuilder=s r

hasCustomTransactions -DhasCustomTransactions=false false

artifactId -DartifactId=mule-transport-tcp mule-transport-<transportId>

Document generated by Confluence on Oct 27, 2008 21:07 Page 309


Customizing a Transport

This page last changed on Aug 04, 2008 by jackie.wheeler.

This page is under construction

Customizing a Transport
Mule provides one or more connectors for each transport. For some transports, a connector is responsible
for managing a connection resource of the transport where the underlying technology has the notion of a
Connection, such as in JMS or JDBC. These types of connectors will have a one-to-one mapping between
a Mule connector and the underlying connection. Therefore, if you want to have two or more physical
JMS connections in a single Mule instance, for example, the application developer can define a new JMS
connector in the XML configuration for each connection.

Other transports have only one connector that manages all endpoint connections for that transport's
protocol. For example, in socket-based transports such as TCP, each message receiver manages its own
ServerSocket and the connector manages multiple receivers.

##insert diagram showing multiple connectors in transport

To create a new connector, you implement and extend the org.mule.providers.AbstractConnector


class. ##more info

Document generated by Confluence on Oct 27, 2008 21:07 Page 310


Deployment Scenarios

This page last changed on Oct 21, 2008 by jackie.wheeler.

Deployment Scenarios
[ Embedding Mule in a Java Application or Webapp ] [ Embedding Mule in an Application Server ] [ Using
Spring ] [ Using Mule NetBoot ]

There are several ways in which you can deploy Mule. The simplest way is from the command prompt,
or from a script or IDE. For more information, see Running Mule. Following are additional deployment
scenarios:

Embedding Mule in a Java Application or Webapp


You can start and stop Mule from a Java application or embed it in a Webapp (such as a JSP or servlet).
For details, see Embedding Mule in a Java Application or Webapp.

Embedding Mule in an Application Server


You can deploy the Mule JCA Resource Adapter to several J2EE application servers, allowing EJBs to send
and receive Mule events:

• Geronimo: The Geronimo application server uses ActiveMQ as its default JMS provider. For details,
see ActiveMQ Integration.
• JBoss
• WebLogic
• WebSphere

Using Spring
Mule fully integrates with Spring, allowing you to take advantage of Spring's many features, including
support for JNDI and EJB session beans. You can also use Spring remoting to access Mule from an
external applications. For details, see Using Mule with Spring.

Using Mule NetBoot


Mule NetBoot allows you to start and configure multiple instances of Mule simultaneously using Galaxy.
For complete information, see Using Mule NetBoot.

Document generated by Confluence on Oct 27, 2008 21:07 Page 311


Deploying Mule to WebLogic

This page last changed on Oct 24, 2008 by jackie.wheeler.

Deploying Mule to WebLogic


[ Creating a WebLogic Domain for Mule ] [ Preparing Required Files ] [ Deploying Mule ] [ Replacing the
Mule Configuration File ]

This page describes how to deploy the Mule JCA Resource Adapter to the WebLogic Application Server,
allowing EJBs to send and receive Mule events. For details on configuring WebLogic JMS in Mule, see
WebLogic JMS Integration.

These instruction assume you have downloaded and installed WebLogic Application Server version 10.3
and that you have downloaded the Mule JCA Resource Adapter. Note that WebLogic 8.x and 9.x are also
supported, but these instructions are specific to version 10.3, both on BEA Weblogic and Oracle WebLogic.

Creating a WebLogic Domain for Mule


The first step is to create a WebLogic domain for Mule using the BEA WebLogic Configuration Wizard.

1. Launch the Configuration Wizard. For example, on Windows choose Start > All Programs > BEA
Products > Tools > Configuration Wizard.
2. In the Welcome screen, select the option to create a new domain and click Next.
3. In the Select Domain Source screen, select the option to generate a domain for WebLogic Server
and click Next.
4. In the Configure Administrator Username and Password screen, enter the user name and password
you want to use, and then click Next.
5. In the Configure Server Start Mode and JDK screen, select Development Mode, select the Sun SDK
1.5 instead of JRockit, and then click Next.
6. In the Customize Environment and Services Settings screen, leave No selected and click Next.
7. In the Create WebLogic Domain screen, enter Mule2.1 for the domain name, leave the location
set to the default user projects domains directory, and then click Create. Note that you can use
whatever domain name you like, but the rest of this page assumes the name Mule2.1.
8. When the domain has been created, click Done.

Preparing Required Files


Mule uses Commons logging and Commons lang. Because WebLogic does not include the Commons
logging JAR, and because Mule requires a newer version of Commons lang, you must copy these
files and modify your classpath so they are used correctly by Mule and WebLogic. For more
information on Commons logging and WebLogic, see http://edocs.bea.com/wls/docs91/logging/
config_logs.html#1015132.

1. Download the Commons logging JAR as a TAR or ZIP file here.


2. Unzip the file and copy commons-logging.jar to any location on the WebLogic server classpath,
such as APP-INF/LIB or WEB-INF/LIB, or in Mule2.1/lib under the <WLHome>/user_projects/
domains directory.
3. Copy wlcommons-logging.jar from <WLHome>/server/lib to the same location where you copied
commons-logging.jar.
4. Copy commons-lang.osgi-2.4.jar from inside the Mule JCA Resource Adapter RAR file to the
Mule2.1/lib directory under the <WLHome/user_projects/domains directory. You can use any
decompression program that supports RAR files to extract the JAR from it, or unpackage the RAR
using the jar xvf command, such as: jar xvf muleesb-enterprise-jca-2.1.1.rar
5. In the Mule2.1EE/bin directory, modify the startWebLogic file so that the
commons-lang.osgi-2.4.jar in your Mule2.1/lib directory is loaded first.

For example, on Windows, you would modify startWebLogic.cmd and change this line:

set CLASSPATH=%CLASSPATH%;%MEDREC_WEBLOGIC_CLASSPATH%...

to this:

Document generated by Confluence on Oct 27, 2008 21:07 Page 312


set CLASSPATH=%WL_HOME%/user_projects/domains/Mule2.1/lib/commons-lang.osgi-2.4.jar; %CLASSPATH%;
%MEDREC_WEBLOGIC_CLASSPATH%...

Deploying Mule
There are many ways to deploy applications to the WebLogic server. These instructions demonstrate the
two most common approaches: through auto-deployment, which provides a fast method for deploying
for testing and evaluation, and through the Administration console, which provides more control over the
configuration.

To Auto-deploy Mule:

1. Copy muleesb-enterprise-jca-2.1.1.rar (for Mule Enterprise users) or mule-jca-2.1.1.rar


(for Mule Community users) into the <WLHome>/user_projects/domains/Mule2.1/autodeploy
directory.
2. Restart your domain server instance in development mode. During the starting process, the new
RAR file will be auto-discovered and deployed by the domain server.

To Deploy Mule Using the Administration Console:

1. Start the WebLogic server. For example, on Windows choose Start > BEA Products > WebLogic
Server.
2. Start the Admin Server for the Mule2.1 domain. For example, on Windows you would choose Start
> BEA Products > User Projects > Mule2.1 > Start Admin Server for WebLogic Server
Domain.
3. When prompted, log in to the console using the user name and password you specified when
creating the domain. If you close the console and need to restart it later, you can go to the URL
http://localhost:7001/console/console.portal.
4. In the Domain Structure on the left, click Deployments, and then click Lock & Edit.
5. Click Install, and then navigate to the location where you downloaded the Mule RAR file.
6. Select the RAR file and click Next.
7. Specify that you want to go to the deployment's configuration screen, and then click Finish.
8. In the Change Center on the left, click Activate Change.

Mule is now deployed to WebLogic via the Mule JCA Resource Adapter. You must now replace the default
configuration file in the RAR file with the configuration file for your Mule application.

Replacing the Mule Configuration File


Mule includes a placeholder configuration file called mule-config.xml in the RAR file under mule-module-
jca-core-2.1.1.jar. If you simply want to modify this file, you can do the following:

1. Unpackage the RAR and the JAR file.


2. Modify the configuration file.
3. Repackage the JAR and RAR with the updated file and copy the RAR into the <WLHome>/
user_projects/domains/Mule2.1/autodeploy directory.
4. Run the startWebLogic command.

If you want to replace this file, do the following:

1. Unpackage the RAR file and copy your configuration file to the top level where all the JAR files are
located.
2. Open the META-INF folder, and then open weblogic-ra.xml for editing.
3. Immediately after the <enable-global-access-to-classes>true</enable-global-access-to-
classes> entry and right before outbound-resource-adapter, add the following lines, where echo-
axis-config.xml is the name of your configuration file:

<properties>
<property>
<name>Configurations</name>
<value>echo-axis-config.xml</value>
</property>
</properties>

Document generated by Confluence on Oct 27, 2008 21:07 Page 313


4. Repackage the RAR file and deploy it by copying it to the autodeploy directory and running
startWebLogic.

Document generated by Confluence on Oct 27, 2008 21:07 Page 314


Deploying Mule to WebSphere

This page last changed on Oct 13, 2008 by jackie.wheeler.

Deploying Mule to WebSphere


This page is under construction

The following describes how to deploy the Mule JCA Resource Adapter to the WebSphere application
server allowing EJBs to send and receive Mule events. For details on configuring WebSphere MQ in Mule,
see WebSphere MQ Integration.

TODO

Document generated by Confluence on Oct 27, 2008 21:07 Page 315


Embedding Mule in a Java Application or Webapp

This page last changed on May 07, 2008 by jackie.wheeler.

Embedding Mule in a Java Application or Webapp


This page describes how to start and stop Mule from a Java application or to embed it in a Webapp (such
as a JSP or servlet), and how to interact with Mule from your code in both scenarios.

Starting Mule from a Java Application

To start Mule from any Java application, you can call one of its configuration builders. To use Mule XML
configuration:

DefaultMuleContextFactory muleContextFactory = new DefaultMuleContextFactory();


SpringXmlConfigurationBuilder configBuilder = new SpringXmlConfigurationBuilder("mule-config.xml");
muleContext = muleContextFactory.createMuleContext(configBuilder);

You can provide a comma-separated list of configuration files if needed.

Make sure you store a reference to the MuleContext, as you will need it to stop Mule.

Stopping Mule from a Java Application

To stop Mule, you stop its context like this:

muleContext.stop();
muleContext.dispose();

Embedding Mule in a Webapp

To embed Mule inside a webapp, you provide one or more configuration file locations as context params
and include a context listener to initialize the Mule Server. If you are using Mule XML configuration, use
the following -

<context-param>
<param-name>org.mule.config</param-name>
<param-value>mule-config-main.xml,mule-components.xml</param-value>
</context-param>

<listener>
<listener-class>org.mule.config.builders.MuleXmlBuilderContextListener</listener-class>
</listener>

The configuration parameter can be a classpath location or file location. You can also specify multiple
configuration files on the classpath or on the file system.

Interacting with Mule from Your Code

To interact with the Mule server from your application, JSP, or servlet, you can use the Mule Client.

//create a client
MuleClient client = new MuleClient();

//send a jms message asynchronously


client.dispatch("jms://my.queue", "some data", null);

//or to receive a pop3 message via a configured mailbox


UMOMessage message = client.receive("pop3://myInboxProvider", 3000);

//or synchonous send a inter-vm message


UMOMessage message2 = client.send("vm://my.object", "Some more data", null);

Document generated by Confluence on Oct 27, 2008 21:07 Page 316


JBoss Integration

This page last changed on Oct 21, 2008 by jackie.wheeler.

Deploying Mule to JBoss


The recommended approach for integrating with enterprise application deployed in JBoss is to deploy
Mule as a standalone application and use the Mule EJB transport or components configured using
spring EJB proxies (http://static.springframework.org/spring/docs/2.5.x/reference/ejb.html using to
integrate with your EJB's in JBoss. If you need to deploy Mule in the JBoss application server for other
reasons (e.g., to use JBoss clustering), use the instructions on this page. Note that if you are using JBoss
clustering, you cannot use stateful routers.

There are three main approaches you can take to deploying Mule to JBoss:

1. Simple WAR deployment: in this approach, you simply embed Mule in your application and build the
WAR. Your custom implementation classes are part of the WAR.
2. EAR application: you can embed the WAR inside the EAR file and include additional files such as
EJBs.
3. JCA deployment: you can use the Mule JCA Resource Adapter. The Mule JCA adaptor allows you to
use "JCA Message Inflow" to Message Driven Beans (MDB's) and use the Mule "ManagedConnection"
for tighter integration when sending message from your Jee application via Mule.

Classloader Isolation
When JBoss comes to classloading, unless classloader isolation is specified, JBoss will first try to use
its own classes for deployment and only when these are not found will it look for them in the libraries
of the deployment file. Since the versions of the libraries used to load Mule are not the same as the
ones used by JBoss, various errors such as ClassCastExceptions can appear, so classloading isolation is
important. Therefore, for best results, you should use classloader isolation in your JBoss configuration.
For more information, see http://wiki.jboss.org/wiki/ClassLoadingConfiguration. If you're using the JCA
adapter, and you have other applications running on JBoss, you should use classloader isolation. However,
classloader isolation is not supported for JCA deployment on JBoss. Therefore, you must wrap your JCA
adapter in an EAR and configure classloader isolation for the EAR.

Building an EAR File for the Deployment of the Mule JCA


Resource Adapter on JBoss 4.2.x
Although you can deploy the Mule JCA Resource Adapter directly, the best way to deploy Mule on JBoss is
to place the resource adapter inside an EAR file. The advantages of this approach over using the Mule JCA
Resource Adapter directly are the following:

• JBoss allows EAR, WAR, and SAR files to have classloader isolation. This feature is not yet available
for the RAR file.
• The Mule JCA Resource Adapter contained in the EAR file is specific for JBoss deployment.
• In order to avoid deployment issues with JBoss the mule-jboss-ds.xml file has to be moved from
the mule-module-jca-jboss-<muleVersion>.jar file up to the EAR level.

Adaptation of the RAR File for Use with the EAR File

In mule-jca-jboss-x.rar (where x is the Mule version number), you must remove mule-jboss-ds.xml
from mule-module-jca-jboss-2.x.jar. Note that if you are going to repackage mule-jca-jboss-x.rar,
repackage it in a simple zip file format instead of other compression formats.

Mule EAR File Structure

The file structure of the EAR file should have the following format:

META-INF
| - application.xml

Document generated by Confluence on Oct 27, 2008 21:07 Page 317


| - jboss-app.xml
| - MANIFEST.MF
mule-jca-jboss-x.rar
mule-jboss-ds.xml

Mule EAR Configuration Files

Following are the configuration files for the XML files in the above file structure:

mule-jboss-ds.xml

<connection-factories>
<tx-connection-factory>
<jndi-name>mule/ConnectionFactory</jndi-name>
<local-transaction />
<track-connection-by-tx />
<rar-name>my-ear.ear#mule-jca-jboss-2.x.rar</rar-name>
<connection-definition>org.mule.module.jca.MuleConnectionFactory</connection-definition>
</tx-connection-factory>
</connection-factories>

The mule-jboss-ds.xml file is an adaptation of the one you removed from mule-module-jca-
jboss-2.x.jar. Note that because the RAR file is found inside the EAR, the name inside the <rar-name>
tag should be the EAR file name and the RAR file name separated by the # symbol. This will be your data
source.

application.xml

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE application PUBLIC "-//Sun Microsystems, Inc.//DTD J2EE Application 1.3//EN" "http://
java.sun.com/dtd/application_1_3.dtd">
<application>
<display-name>mule-ear</display-name>
<description>EAR packaging for Mule Resource Adapter</description>
<module>
<connector>mule-jca-jboss-2.x.rar</connector>
</module>
</application>

This file is required for telling the EAR file to use mule-jca-jboss-2.x.rar as a connector, allowing it to
be deployed as a resource adapter.

jboss-app.xml

The following configuration file creates a loader-repository that loads the classes during the classloading
operation. The java2ParentDelegation property must be set to false to enable classloader isolation.
The configuration specifies mule-jboss-ds.xml as a service to be loaded.

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE jboss-app PUBLIC "-//JBoss//DTD J2EE Application 1.4//EN" "http://www.jboss.org/j2ee/dtd/
jboss-app_4_0.dtd">
<jboss-app>
<loader-repository>org.mule:loader=mule-ear-2.1.0.ear
<loader-repository-config>
java2ParentDelegaton=false
</loader-repository-config>
</loader-repository>
<module>
<service>mule-jboss-ds.xml</service>
</module>
</jboss-app>

Document generated by Confluence on Oct 27, 2008 21:07 Page 318


Deploying Your Application
The resource adapter comes configured with a dummy mule-config.xml file, which you will replace with
your own configuration file. You can physically replace the mule-config.xml file in the Mule JCA Resource
Adapter (mule-module-jca-core-2.x.jar) with your own, but if your POJOs are bundled in a JAR, you
can take the following more elegant approach:

1. Put the resource files (xslt, properties, etc.) in your JAR file (these should be picked up
automatically when Mule starts)
2. Create a folder in the root of the mule-jca-jboss-2.x.rar file and put your Mule configuration in
there. For the time being, let's call this folder "conf".
3. Edit the ra.xml file found in the mule-jca-jboss-2.x.rar META-INF folder and reference your
configuration file name as seen below.

Alternatively you can put your jar files with classes/resources that will be used by mule in your EAR, but
in order to do this you will need to add a "Class-Path" entry in the rar's MANIFEST.MF referencing the
required libraries.

<config-property-name>Configurations</config-property-name>
<config-property-type>java.lang.String</config-property-type>
<config-property-value>conf/my-config1.xml</config-property-value>

The <config-property-value> should contain a list of configuration files separated by a comma. The
"conf/" is the path name telling the loader to look at the conf folder found in the root of the RAR file. If
only the name of the configuration file is given, the loader will only look for the configuration file inside
the mule-module-jca-core-2.x.jar.

JBoss MQ Configuration
For information on configuring a JBoss JMS connector, see JBoss Jms Integration.

Scenarios your User Application with Mule in JBoss


For this scenario, the deployment is very simple: you simply add your own JAR and WAR archives to you
EAR file. Because everything will be deployed in the same EAR, all the classes required by both the user
application and Mule share the same classloader. However sometimes other classes may be required that
are not deployed within your EAR..

Resolving Cross-dependencies

The situation becomes more complex when you want to deploy Mule-dependent code in a separate EAR
file (for example, you have a custom transformer that extends Mule's AbstractTransformer class). The
user EAR depends on the Mule libraries to be loaded to be able to load the custom transformer library,
while Mule expects the user EAR to be loaded to be able to use the transformer class that is found in
the user EAR. To solve these cross-dependencies, you can create a shared library (in another EAR file,
perhaps) and specify the library in the <loader-repository> element of the jboss-app.xml file in
both the Mule EAR and the user EAR. Mule Enterprise Edition users can see an example of this in the
Knowledge Base article titled "Embedding in JBoss: How to Share Classes Between Your Mule EE EAR and
Another Application".

Document generated by Confluence on Oct 27, 2008 21:07 Page 319


Mule as MBean

This page last changed on Jan 30, 2008 by ross.

Mule as MBean | Creating a Simple MBean | Creating JBoss Service Descriptor | Deploy
MBean to JBoss | References | External References | Related

Mule as MBean
An MBean[MULE:1] is a named managed object representing a resource in an JMX environment. We can
have an MBean deployed with Mule in it easily, the steps as follows:

1. Create an MBean (see MULE:#Creating a Simple MBean)


2. Create service descriptor (see MULE:#Creating JBoss Service Descriptor)
3. Deploy MBean (as .sar) to application server (see MULE:#Deploy MBean to JBoss)
4. Copy dependencies to service's classpath

Just as you have not yet noticed, we are using JBoss application server in this document.

Creating a Simple MBean

To create an MBean, you will need an interface and an implementation, e.g.

package foo.mbean;

public interface FooServiceMBean {


public String getBar();
public void start();
public void stop();
}

package foo.mbean;

import org.jboss.system.ServiceMBeanSupport;
import org.mule.config.builders.MuleXmlConfigurationBuilder;
import org.mule.umo.manager.UMOManager;
import org.mule.umo.manager.UMOServerNotification;

public class FooService extends ServiceMBeanSupport implements FooServiceMBean{

private UMOManager muleManager = null;

public String getBar() {


return "bar";
}

public void start() {


this.getLog().info("MBean being started");

try{
MuleXmlConfigurationBuilder builder = new MuleXmlConfigurationBuilder();
UMOManager manager = builder.configure("mule-config.xml");
manager.start();
manager.registerListener(this);
}
catch(Exception e){
e.printStackTrace();
}
this.getLog().info("MBean started");
}

public void stop() {


this.getLog().info("MBean being stopped");

Document generated by Confluence on Oct 27, 2008 21:07 Page 320


try {
if (muleManager != null) {
muleManager.stop();
muleManager.dispose(); // If we can get the muleServer exposed.. :(

}
this.getLog().info("Done stopping Mule MBean Service!");
}
catch (Exception ex) {
this.getLog().error("Stopping Mule caused and exception!", ex);
}
}
}

The extension of ServiceMBeanSupport is simply to provide you more control over the API provided by
JBoss.

Creating JBoss Service Descriptor

A service descriptor has to be located at META-INF/, here is a simple example of it:

<?xml version="1.0" encoding="UTF-8"?>


<server>
<mbean code="foo.FooService" name="foo:service=Foo">
</mbean>
</server>

Deploy MBean to JBoss

So, your distro looks like this (using the examples above):

.
./foo
./foo/FooService
./foo/FooServiceMBean
./META-INF
./META-INF/jboss-service.xml

Pack it, either as a JAR (which can then be renamed to a *.sar, and eventually you will need to extract it
as JBoss might not be picking it up for whatever reason that I have no idea about) or as a directory called
<whatever>.sar.

Follow the steps below to complete the deployment:

1. Copy your <whatever>.sar/ directory to JBOSS_HOME/server/default/deploy/


2. Copy all dependencies of Mule, i.e. MULE_HOME/lib/*/*.jar to the <whatever>.sar/ directory
3. Start JBoss and you'll see the MBean appears in its MBean console, tada :-)

References

External References

1. Wikipedia - MBean
2. The Java Tutorials - Standard MBeans

Related

Mule as MBean — Deploying Mule into JBoss

Document generated by Confluence on Oct 27, 2008 21:07 Page 321


Developing Service Components

This page last changed on Oct 13, 2008 by jackie.wheeler.

This page is ready for review

Developing Service Components


[ Entry Point ] [ Default Message Flow Behavior ] [ Customizing the Message Flow Behavior ] [
Component Lifecycle ]

When developing service components, you focus on developing code to handle the business logic, not
to integrate the service component with Mule. For example, if you are developing a service component
that adds customer data to an invoice, you focus on writing code that queries the customer database
and updates the invoice as needed. You do not have to write any special code to handle the message
that's passed to the service component or to integrate with Mule, as all integration is handled through
configuration. You can develop the service component as a POJO, or as a web service using popular
containers such as Spring, EJB, or Plexus.

Mule does allow you to enable service components to obtain information about or even control the current
message instead of just working with the message payload. To enable the service component to work
directly with the message, you must implement the Callable() interface in the service component (see
Entry Points below).

To get started with developing Mule service components, you can use the Mule IDE. The Mule IDE is an
Eclipse plug-in that provides an integrated development environment for developing Mule applications.
You can also use the standard components provided with Mule, or use them as a starting point for
building your own.

Entry Point
The entry point is the method in your component that is invoked by Mule when a message is received.
Mule uses an entry point resolver to dynamically choose the method to invoke based on the payload
type of the message. When the match is found, the method is cached with the parameter types so
that introspection is only done once per method for the life of the service. If multiple methods in the
component match the payload type, or no method matches, an error is thrown. You can also call a
method on the component that has no arguments.

Alternatively, your component can implement the org.mule.api.lifecycle.Callable interface. If your


component implements this interface, it will override any dynamic resolution and call the interface
method implementation instead.

For details on configuring entry point resolvers, see Entry Point Resolver Configuration Reference.

Legacy Entry Point Resolver Set

The LegacyEntryPointResolverSet that is used if no other resolver is configured. The


LegacyEntryPointResolverSet provides generic entry point resolution as follows:

1. Use the "method" message property, if one is specified.


2. If the component implements the org.mule.api.lifecycle.Callable lifecycle interface, use the
onCall(MuleEventContext) method to receive the message.
3. If the component has a transformer configured for it, the return type for the transformer will
be matched against methods on the component to see if there is a method that accepts the
transformer return type. If so, this method will be used. Note if there is more than one match, an
exception will be thrown.
4. The message type (without transformer) will be matched against methods on the component to see
if there is a method that accepts the transformer return type. If so, this method will be used. Note if
there is more than one match, an exception will be thrown.
5. If none of the above finds a match, an exception will be thrown and the component registration will
fail.

Document generated by Confluence on Oct 27, 2008 21:07 Page 322


There are many scenarios where the LegacyEntryPointResolverSet is unsuitable. More control is available
by extending its set of implementations, or by configuring a completely new set. There are several
EntryPointResolver implementations, such as org.mule.model.resolvers.CallableEntryPointResolver
, org.mule.model.resolvers.MethodHeaderPropertyEntryPointResolver , and
org.mule.model.resolvers.ReflectionEntryPointResolver . While these are used in the
LegacyEntryPointResolverSet, they can be more comprehensively configured when specified separately.

Calling No-arguments Methods

If you want to call a method with no arguments, you can use the
org.mule.model.resolvers.NoArgumentsEntryPointResolver . Regardless of the payload of the
current message, this resolver looks only for no-argument methods in the component. Additionally,
ReflectionEntryPointResolver supports the resolution of no-argument service methods if the payload
received is of type NullPayload.

Custom Entry Point Resolver

If you want to create your own entry point resolver, you create a class that implements the
EntryPointResolver interface and specify it with the <custom-entry-point-resolver> element in your
Mule configuration.

Default Message Flow Behavior


Mule has some default behavior rules about managing message flow to and from your component.

1. When a message is received, the entry point method is invoked as described above.
2. The response or outbound message is obtained as follows:
• If the method invoked is not void, (that is, Callable.onEvent() returns an Object), the method
return value is used. If null is returned, no further processing is done for the current request.
• If the method is void, the parameters used to invoke the method are used. This assumes that
the parameters themselves were altered or there was no change to the message.
3. If the inbound endpoint used in synchronous then the result of the component invocation is returned
to caller.
4. The outbound message is then routed according the services <outbound> configuration:

See Mule Messaging Styles for more detail about the different configuration options that affect message
flow.

Customizing the Message Flow Behavior


To customize the message flow behavior, you must get a reference to org.mule.api.MuleEventContext .
You can get the reference by implementing the Callable interface, which passes the event context as a
parameter on this interface:

public interface Callable


{
public Object onCall(MuleEventContext eventContext) throws Exception;
}

From the MuleEventContext, you can send and receive events synchronously and asynchronously,
manage transactions, and override the default event flow behavior. For example:

MuleEventContext context = RequestContext.getEventContext();


OutboundEndpoint endpoint = ...

//to send asynchronously


context.dispatchEvent(new MuleMessage("IBM:0.01", null), endpoint);

//or to request
InboundEndpoint endpoint = ...
MuleMessage quote = context.request(endpoint, 5000);

Document generated by Confluence on Oct 27, 2008 21:07 Page 323


Even when you use the event context to manually control event flow, when your method returns, Mule
will route the outbound event as normal. You can stop Mule processing events further as follows:

• If your service method is not void, you can return null. This approach tells Mule there is no further
event information to process.

• If your service method is void, Mule will use the inbound message payload as the outbound message
payload. You can override this behavior using the setStopFurtherProcessing method as described
below.

Halting Message Flow

To halt the message flow, you can either call setStopFurtherProcessing() from the MuleEventContext
or else throw an exception. This will cause the ExceptionStrategy on the component to be invoked.

Note:
The use of additional services or the use of component bindings is much preferred to the above
techniques to control message flow from within your component implementation. This is because it allows
for a much more decoupled implementation that can be modified via your configuration file and avoids
the need to use Mule API in your component implementations. To take this approach, do one of the
following:

• Ensure your service components are implemented in such a way that they do a single unit of work
that do not need to do any message sending/receiving. This additional sending/receiving/routing is
then done using Mule services.
• Design your component in such a way that interface methods can be mapped to outbound endpoints
and then use bindings to map these in configuration. For information on how to configure bindings,
see Configuring Java Components.

Component Lifecycle
Optionally, your component can implement several lifecycle interfaces. Following are some of the most
commonly used interfaces:

• org.mule.api.lifecycle.Initialisable is called only once for the lifecycle of the component. It is called
when the component is created when the component pool initializes.
• org.mule.api.lifecycle.Startable is called when the component is started. This happens once when
the server starts and whenever the component is stopped and started either through the API or
JMX.
• org.mule.api.lifecycle.Stoppable is called when the component is stopped. This happens when the
server stops or whenever the component is stopped either through the API or JMX.
• org.mule.api.lifecycle.Disposable is called when the component is disposed. This is called once when
the server shuts down.

For more information, see the org.mule.api.lifecycle Javadocs .

If your custom component already has its own lifecycle methods, possibly implementing your own API, or
you just prefer not to depend on Mule's, you can implement and configure a LifecycleAdaptorFactory
to map Mule's lifecyle to your component's lifecycle. To do this, you implement your own
org.mule.api.component.LifecycleAdaptorFactory and org.mule.api.component.LifecycleAdaptor . See
Configuring Java Components for information on how to configure a custom life-cycle adaptor factory.

Document generated by Confluence on Oct 27, 2008 21:07 Page 324


Entry Point Resolver Configuration Reference

This page last changed on Oct 22, 2008 by jackie.wheeler.

Entry Point Resolver Configuration Reference


This page provides details on the elements you configure for entry point resolvers and entry point
resolver sets. This information is pulled directly from mule.xsd and is cached. If the information appears
to be out of date, refresh the page.

Entry Point Resolver Sets

<entry-point-resolver-set ...>
An extensible set of entry point resolvers. These determine how a message is passed to a component
in Java. Each entry point resolver is tried in turn until one succeeds in delivering the messge to the
component. This element can be set on the model or component; the model value provides a default
which individual component values can override.

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

abstract-entry- 0..* A placeholder for


point-resolver an entry point
resolver element.
Entry point
resolvers define
how payloads are
delivered to Java
code by choosing
the method to
call.

<legacy-entry-point-resolver-set ...>
An extensible set of entry point resolvers (which determine how a message is passed to a component in
Java) that already contains resolvers to implement the standard logic. This is already provided by default
and is only needed explicitly if it will be extended with other entry point resolvers. This element can be
set on the model or component; the model value provides a default which individual component values
can override.

Document generated by Confluence on Oct 27, 2008 21:07 Page 325


Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

abstract-entry- 0..* A placeholder for


point-resolver an entry point
resolver element.
Entry point
resolvers define
how payloads are
delivered to Java
code by choosing
the method to
call.

<custom-entry-point-resolver-set ...>
A custom entry point resolver set. This allows user-supplied code to determine how a message is passed
to a component in Java. This element can be set on the model or component; the model value provides a
default which individual component values can override.

Attributes

Name Type Required Default Description

class class name no An


implementation
of the
EntryPointResolverSet
interface.

Child Elements

Name Cardinality Description

spring:property 0..*

Entry Point Resolvers

<callable-entry-point-resolver ...>
An entry point resolver for components that implement the Callable interface. This passes a
MuleEventContext to the component. This element can be set on the model or component; the model
value provides a default which individual component values can override. This element can also be used
directly or as part of a set of resolvers; the resolvers in a set are used in turn until one is successful.

Document generated by Confluence on Oct 27, 2008 21:07 Page 326


Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

<custom-entry-point-resolver ...>
A custom entry point resolver. This allows user-supplied code to determine how a message is passed to
a component in Java. This element can be set on the model or component; the model value provides a
default which individual component values can override. This element can also be used directly or as part
of a set of resolvers; the resolvers in a set are used in turn until one is successful.

Attributes

Name Type Required Default Description

class class name no An


implementation
of the
EntryPointResolver
interface.

Child Elements

Name Cardinality Description

spring:property 0..*

<property-entry-point-resolver ...>
Use a message property to select the component method to be called. This element can be set on the
model or component; the model value provides a default which individual component values can override.
This element can also be used directly or as part of a set of resolvers; the resolvers in a set are used in
turn until one is successful.

Attributes

Name Type Required Default Description

transformFirst boolean no Whether the


message should
be transformed
before being
delivered to the
component. By
default, messages
are transformed.

Document generated by Confluence on Oct 27, 2008 21:07 Page 327


acceptVoidMethods boolean no Whether the
resolver should
call void methods.
By default, void
methods are
not considered
as possible
candidates for
message delivery.

property name (no spaces) no The name of the


message property
used to select a
method on the
component.

Child Elements

Name Cardinality Description

<method-entry-point-resolver ...>
Deliver the message to a named method. This element can be set on the model or component; the model
value provides a default which individual component values can override. This element can also be used
directly or as part of a set of resolvers; the resolvers in a set are used in turn until one is successful.

Attributes

Name Type Required Default Description

transformFirst boolean no Whether the


message should
be transformed
before being
delivered to the
component. By
default, messages
are transformed.

acceptVoidMethods boolean no Whether the


resolver should
call void methods.
By default, void
methods are
not considered
as possible
candidates for
message delivery.

Child Elements

Name Cardinality Description

include-entry-point 1..* A possible method for delivery.

Document generated by Confluence on Oct 27, 2008 21:07 Page 328


<reflection-entry-point-resolver ...>
Generate a list of candidate methods from the component via reflections. This element can be set on the
model or component; the model value provides a default which individual component values can override.
This element can also be used directly or as part of a set of resolvers; the resolvers in a set are used in
turn until one is successful.

Attributes

Name Type Required Default Description

transformFirst boolean no Whether the


message should
be transformed
before being
delivered to the
component. By
default, messages
are transformed.

acceptVoidMethods boolean no Whether the


resolver should
call void methods.
By default, void
methods are
not considered
as possible
candidates for
message delivery.

Child Elements

Name Cardinality Description

exclude-object-methods 0..1 If specified, methods in the Java


Object interface are not included
in the list of possible methods
that can receive the message.

exclude-entry-point 0..* Explicitly exclude a named


method from receiving the
message.

<array-entry-point-resolver ...>
Deliver the message to a method which takes a single array as argument. This element can be set on the
model or component; the model value provides a default which individual component values can override.
This element can also be used directly or as part of a set of resolvers; the resolvers in a set are used in
turn until one is successful.

Document generated by Confluence on Oct 27, 2008 21:07 Page 329


Attributes

Name Type Required Default Description

transformFirst boolean no Whether the


message should
be transformed
before being
delivered to the
component. By
default, messages
are transformed.

acceptVoidMethods boolean no Whether the


resolver should
call void methods.
By default, void
methods are
not considered
as possible
candidates for
message delivery.

enableDiscovery boolean no

Child Elements

Name Cardinality Description

exclude-object-methods 0..1 If specified, methods in the Java


Object interface are not included
in the list of possible methods
that can receive the message.

exclude-entry-point 0..* Explicitly exclude a named


method from receiving the
message.

include-entry-point 0..* A possible method for delivery.

<no-arguments-entry-point-resolver ...>
Call a method without arguments (the message is not passed to the component).

Attributes

Name Type Required Default Description

transformFirst boolean no Whether the


message should
be transformed
before being
delivered to the
component. By
default, messages
are transformed.

Document generated by Confluence on Oct 27, 2008 21:07 Page 330


acceptVoidMethods boolean no Whether the
resolver should
call void methods.
By default, void
methods are
not considered
as possible
candidates for
message delivery.

enableDiscovery boolean no

Child Elements

Name Cardinality Description

exclude-object-methods 0..1 If specified, methods in the Java


Object interface are not included
in the list of possible methods
that can receive the message.

exclude-entry-point 0..* Explicitly exclude a named


method from receiving the
message.

include-entry-point 0..* A possible method for delivery.

<include-entry-point ...>
A possible method for delivery.

Attributes

Name Type Required Default Description

method name no The name of the


method.

Child Elements

Name Cardinality Description

Document generated by Confluence on Oct 27, 2008 21:07 Page 331


Error Handling

This page last changed on Sep 12, 2008 by jackie.wheeler.

Error Handling
This page is ready for review

Error handling includes setting exception strategies and connection strategies. Additionally, you can
use exception routers to specify where the message goes when an error occurs. This page describes
these strategies and routers. For details on configuring exception strategies, see Exception Strategy
Configuration Reference.

Exception Strategies
Exception strategies are used to handle exception conditions when an error occurs processing an event.
There are two objects that support Exception strategies; components and connectors, plus a common
component exception strategy for components can be set on the model.

Cannot resolve external resource into attachment.

Exception strategies associated with components or the model are used to handle component exceptions.
These are typically business logic exceptions.
The user will often want to customize the exception handler to control how these exceptions are logged
and routed.

Exceptions strategies associated with the connector handle exceptions thrown when events are received
or sent using a connector. It is less common that these strategies will be customized by the developer,
but they may be configured to route exceptions to a common error queue.

Model and Component Exception Strategies

The default exception strategy used by the model (and thus all components managed by the model)
is org.mule.service.DefaultServiceExceptionStrategy , which you configure with the <default-service-
exception-strategy> element. To configure it at the model level, add the element before the services:

<model name="CreditCheck">
<default-service-exception-strategy>
<vm:outbound-endpoint path="systemErrorHandler"/>
</default-service-exception-strategy>
<service> ... </service>
<service> ... </service>
</model>

To configure it on a service, add it at the end of the service:

<model name="CreditCheck">
<service>
...
<default-service-exception-strategy>
<vm:outbound-endpoint path="systemErrorHandler"/>
</default-service-exception-strategy>
</service>
</model>

You set an endpoint on an exception strategy to forward the event that failed to a destination such as an
error queue.

To implement your own strategy, your class can extend org.mule.AbstractExceptionListener , but a
recommended approach is to extend org.mule.service.DefaultServiceExceptionStrategy and just overload
the defaultHandler() method. Bean properties can be set on your custom exception strategy in the
same way as other Mule configured objects using a <properties> element.

Document generated by Confluence on Oct 27, 2008 21:07 Page 332


It is up to the defaultHandler() method to do all necessary processing to contain the exception, so an
exception should never be thrown from an exception strategy. The exception strategy must manage fatal
errors. For example, if an error queue is being used but the dispatch fails, you might want to stop the
current component and fire a server notification to alert a system monitor and write the event to file.

If you want to change the way exceptions are logged, override the logException() method from the
org.mule.AbstractExceptionListener .

Connector Exception Strategies

The default exception strategy used by a connector is org.mule.DefaultExceptionStrategy , which you


configure with the <default-exception-strategy> element. This strategy simply logs exceptions and
continues. The exceptions this strategy must handle are typically connection-related exceptions that may
or may not be recoverable.

Using an Exception Router


When an exception occurs, the exception router org.mule.routing.outbound.ExceptionBasedRouter
determines where the message goes. You can have multiple endpoints specified on the exception router,
so that if the first endpoint fails with a FatalConnectionException, the next endpoint is tried, and then
the next. If all endpoints fail, an org.mule.api.routing.RoutingException is thrown. Note that the exception
router will override the endpoint mode to synchronous while looking for a successful send, and it will
resort to using the endpoint's mode for the last item in the list.

Following is an example of configuring an exception router:

<outbound-router>
<router className="org.mule.routing.outbound.ExceptionBasedRouter">
<endpoint address="tcp://10.192.111.10:10001" />
<endpoint address="tcp://10.192.111.11:10001" />
<endpoint address="tcp://10.192.111.12:10001"/>
</router>
</outbound-router>

Document generated by Confluence on Oct 27, 2008 21:07 Page 333


Functional Testing

This page last changed on Aug 19, 2008 by jackie.wheeler.

Functional Testing
[ FunctionalTestCase ] [ FunctionalTestComponent ] [ Additional Features ] [ Additional Example: Event
Callback With a Spring Component ]

Because Mule is light-weight and embeddable, it is easy to run a Mule Server inside a test case. Mule
provides an abstract JUnit test case called org.mule.tck.FunctionalTestCase that runs Mule inside a test
case and manages the lifecycle of the server. The org.mule.tck.functional package contains a number of
supporting classes for functionally testing Mule code, including FunctionalTestComponent . These classes
are described in more detail in the following sections.

FunctionalTestCase
FunctionalTestCase is a base test case for Mule functional tests. Your test cases can extend
FunctionalTestCase to use its functionality.

FunctionalTestCase fires up a Mule server using a configuration you specify by overriding the
getConfigResources():

protected String getConfigResources()


{
return "mule-conf.xml";
}

You can use the method getConfigResources to specify a configuration file or comma-
separated list of configuration files to use. All configuration files must exist in your
classpath.

You then create tests that interact with the Mule server. FunctionalTestCase extends
junit.framework.TestCase, so JUnit the framework for creating and running your test cases. For
example, this simple test would send a message to a vm endpoint .

public void testSend() throws Exception


{
MuleClient client = new MuleClient();
String payload = "foo";
MuleMessage result = client.send("vm://test", new DefaultMuleMessage(payload));
assertEquals("foo Received", result.getPayloadAsString());
}

Notice the use of MuleClient to interact with the running Mule server. MuleClient is used to send
messages to and receive messages from endpoints you specify in your Mule configuration file (mule-
conf.xml in this case). The example mule-conf.xml file used in this example is shown below:

<?xml version="1.0" encoding="UTF-8"?>


<mule xmlns="http://www.mulesource.org/schema/mule/core/2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.0"
xmlns:test="http://www.mulesource.org/schema/mule/test/2.0"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-2.0.xsd
http://www.mulesource.org/schema/mule/core/2.0 http://www.mulesource.org/schema/mule/core/2.0/
mule.xsd
http://www.mulesource.org/schema/mule/vm/2.0 http://www.mulesource.org/schema/mule/vm/2.0/mule-
vm.xsd
http://www.mulesource.org/schema/mule/test/2.0 http://www.mulesource.org/schema/mule/test/2.0/mule-
test.xsd">

Document generated by Confluence on Oct 27, 2008 21:07 Page 334


<model name="TestComponentModel">
<service name="TestComponentService">
<inbound>
<inbound-endpoint address="vm://test"/>
</inbound>
<test:component appendString=" Received"/>
</service>
</model>
</mule>

FunctionalTestComponent
The previous example of FunctionalTestCase covers many common (synchronous) test scenarios, where
the service responds directly to the caller. FunctionalTestComponent can help support richer tests, such
as:

1. Simulating asynchronous communication


2. Returning mock data to the caller
3. Common scenarios such as forced exceptions, storing message history, appending text to responses,
and delayed responses.

The component includes two methods: the onCall method and the onReceive method that basically do
the same thing.

• onCall: receives a MuleEventContext as input and returns an Object.


• onReceive: receives an Object as input and returns an Object.

In both methods, FunctionalTestComponent takes the message that is passed to it (either from the
MuleEventContext or from the Object) and transform it into a String. It then creates a message and
sends it back to the caller. It also checks whether any of its properties are set and acts accordingly.

Asynchronous Tests with FunctionalTestComponent

The FunctionalTestComponent supports two event mechanisms for responding to a caller


asynchronously: event callbacks and notifications. Both event callbacks and notifications fire events
that get handled by registered listeners. During functional testing, the listener will typically be a class
accessible in the FunctionalTestCase.

Event Callbacks

User-defined event callbacks get called when the test component is invoked. Following is an example of a
test case and Mule configuration that uses callbacks:

public void testEventCallback() throws Exception


{
EventCallback callback = new EventCallback()
{
public void eventReceived(MuleEventContext context, Object component)
throws Exception
{
System.out.println("Thanks for calling me back");
}
};

DefaultJavaComponent defaultComponent = (DefaultJavaComponent)


muleContext.getRegistry().lookupService("TestComponentService").getComponent();
FunctionalTestComponent testComponent = (FunctionalTestComponent)
defaultComponent.getObjectFactory().getInstance();
testComponent.setEventCallback(callback);

MuleClient client = new MuleClient();

client.send("vm://test", new DefaultMuleMessage("foo"));

Document generated by Confluence on Oct 27, 2008 21:07 Page 335


}

In this example, the eventReceived callback method is invoked as soon as the


FunctionalTestComponent receives the message, and a message is printed to the console. Test
assertions could be made in this method.

The corresponding Mule configuration used in this example is as follows:

<?xml version="1.0" encoding="UTF-8"?>


<mule xmlns="http://www.mulesource.org/schema/mule/core/2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.0"
xmlns:test="http://www.mulesource.org/schema/mule/test/2.0"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-2.0.xsd
http://www.mulesource.org/schema/mule/core/2.0 http://www.mulesource.org/schema/mule/core/2.0/
mule.xsd
http://www.mulesource.org/schema/mule/vm/2.0 http://www.mulesource.org/schema/mule/vm/2.0/mule-
vm.xsd
http://www.mulesource.org/schema/mule/test/2.0 http://www.mulesource.org/schema/mule/test/2.0/mule-
test.xsd">

<model name="TestComponentModel">
<service name="TestComponentService">
<inbound>
<inbound-endpoint address="vm://test"/>
</inbound>
<component>
<singleton-object class="org.mule.tck.functional.FunctionalTestComponent"/>
</component>
</service>
</model>
</mule>

Notice that in this configuration, we did not use the "<test:component>" element, since we need
FunctionalTestComponent to be singleton for the callback to work properly.

For an example of an event callback on a Spring component, see the additional example below.

Notifications

Notifications are an alternative to event callbacks. When an event is received, the


FunctionalTestComponent fires a notification informing us that the event has been received. It is up
to us to set up a listener (the FunctionalTestNotificationListener) on our test to capture this
notification.

To do this, we must first make our test case implement the FunctionalTestNotificationListener
interface. Then, we must implement the method exposed by this listener, which is onNotification.
In the example below, we check notification.getAction to see whether it is the
FunctionalTestNotification fired by the FunctionalTestComponent. If it is, we print it out to the
console.

public void onNotification(ServerNotification notification)


{
if (notification.getAction() == FunctionalTestNotification.EVENT_RECEIVED)
{
System.out.println("Event Received");
}
}

Now, in order for our listener to start listening for notifications, we must register it:

Document generated by Confluence on Oct 27, 2008 21:07 Page 336


muleContext.registerListener(this,"myComponent");

Returning Mock Data from FunctionalTestComponent

FunctionalTestComponent can return mock data specified either in a file or embedded in the Mule
configuration. For example, to have the FunctionalTestComponent return the message "donkey", you
would configure the component as follows:

<test:component>
<test:return-data>donkey</test:return-data>
</test:component>

To return contents from a file, you could use:

<test:component>
<test:return-data file="abc.txt"/>
</test:component>

The file referenced should exist on the Mule classpath.

Other Useful Features of FunctionalTestComponent

Forcing Exceptions

You can use throwException to always return the exception specified by exceptionToThrow, as follows:

<test:component throwException="true" exceptionToThrow="your.service.exception"/>

Storing Message History

By default, every message that is received by the FunctionalTestComponent is stored and can be
retrieved. If you do not want this information stored, you can set enableMessageHistory to false. For
example, if you are running millions of messages through the component, an out-of-memory error would
probably occur eventually if this feature were enabled.

To enable:

<test:component enableMessageHistory="true" />

Messages are stored in an ArrayList. To retrieve a stored message, you use the getReceivedMessage
method to retrieve it by number (e.g., getReceivedMessage(1) to retrieve the first message stored),
or use getLastReceivedMessage to retrieve the last message that was received. You can use
getReceivedMessages to return the total number of messages stored.

Appending Text to Responses

You can use appendString to append text to the response message, as follows:

<test:component appendString="Received" />

Delayed Responses

You can set waitTime to delay responses from this FunctionalTestComponent. In this example,
responses are delayed five seconds:

<test:component waitTime="5000" />

Disable Inbound Transformer

You can set doInboundTransform to false to disable the inbound transformer. For example:

<test:component doInboundTransform="false" />

Document generated by Confluence on Oct 27, 2008 21:07 Page 337


Additional Features
The functional package includes several additional classes, such as CounterCallback, a test callback
that counts the number of messages received. For complete information, see the org.mule.tck.functional
Javadoc.

Additional Example: Event Callback With a Spring Component


This example is identical to the "Event Callbacks" example above, except the component used here is a
Spring component. In this case, we can look up the component using the Spring registry (although using
the Mule registry as in the original example also works).

public void testEventCallback() throws Exception


{
EventCallback callback = new EventCallback()
{
public void eventReceived(MuleEventContext context, Object component)
throws Exception
{
System.out.println("Thanks for calling me back");
}
};

ApplicationContext ac =
(ApplicationContext)muleContext.getRegistry().lookupObject(SpringRegistry.SPRING_APPLICATION_CONTEXT);
FunctionalTestComponent testComponent = (FunctionalTestComponent) ac.getBean("FTC");
testComponent.setEventCallback(callback);

MuleClient client = new MuleClient();

client.send("vm://test", new DefaultMuleMessage("foo"));

The corresponding Mule configuration would be as follows:

<?xml version="1.0" encoding="UTF-8"?>


<mule xmlns="http://www.mulesource.org/schema/mule/core/2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.0"
xmlns:test="http://www.mulesource.org/schema/mule/test/2.0"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-2.0.xsd
http://www.mulesource.org/schema/mule/core/2.0 http://www.mulesource.org/schema/mule/core/2.0/
mule.xsd
http://www.mulesource.org/schema/mule/vm/2.0 http://www.mulesource.org/schema/mule/vm/2.0/mule-
vm.xsd
http://www.mulesource.org/schema/mule/test/2.0 http://www.mulesource.org/schema/mule/test/2.0/mule-
test.xsd">

<spring:bean id="FTC" class="org.mule.tck.functional.FunctionalTestComponent" />

<model name="TestComponentModel">
<service name="TestComponentService">
<inbound>
<inbound-endpoint address="vm://test" />
</inbound>
<component>
<spring-object bean="FTC" />
</component>

Document generated by Confluence on Oct 27, 2008 21:07 Page 338


</service>
</model>
</mule>

Document generated by Confluence on Oct 27, 2008 21:07 Page 339


Installing a Standalone Mule Instance

This page last changed on Aug 04, 2008 by jackie.wheeler.

This page is under construction

Installing a Standalone Mule Instance


##permissions each folder should have, what ports should be open, etc.

Document generated by Confluence on Oct 27, 2008 21:07 Page 340


Installing Upgrades and Hot Fixes

This page last changed on Aug 04, 2008 by jackie.wheeler.

This page is under construction

Installing Upgrades and Hot Fixes


##describe how to obtain and install upgrades and hot fixes, what you need to know about backing up
data first, stopping/restarting the server, etc.

Document generated by Confluence on Oct 27, 2008 21:07 Page 341


Internationalizing Strings

This page last changed on Aug 04, 2008 by jackie.wheeler.

Internationalizing Strings
[ Internationalized Messages ] [ Exceptions ] [ Using Custom Message Bundles ] [ Creating Message
Instances from your Code ]

Mule supports internationalization of exception messages and any other type of string message. Mule has
support for the following Languages:

• English
• Japanese

Internationalized Messages
Mule uses the Java ResourceBundle class to load messages from properties files on the classpath based
on the current system's locale. Mule provides a full set of messages in English and Japanese only, but
there may be additional languages provided in the future.

Mule's internationalized messages are represented by the org.mule.config.i18n.Message class. Instances


are constructed with a message ID and zero or more message parameters. You can see a list of core
messages that Mule provides in META-INF/service/org/mule/i18n/core-messages.properties.

You never create instances of Message directly. Instead, you use subclasses of MessageFactory . The
messages for Mule's core project are accessible through the org.mule.config.i18n.CoreMessages class.

Each of Mule's modules and transports has such a messages class. Its name is equal to the module with
Messages appended. For example, for the JMS transport you will use JmsMessages to retrieve messages.

The dedicated messages class per module/transport has the following advantages:

• Encapsulation of the message code


• Client code is not cluttered with Message constructors
• Client code has typesafe access to its messages
• Client code is not cluttered with formatting of message parameters. Instead, you handle tihs in the
module-specific messages class

Exceptions
MuleException is the base class of all Mule checked exceptions and can only be constructed using
internationalized messages. To create a message for an exception, you use MuleExtension as follows:

MuleException e = new MuleException(CoreMessages.failedToGetPooledObject());


throw e;

Using Custom Message Bundles


When writing Mule extensions or applications that will use the Mule internationalization class, you can
supply custom message bundles containing messages specific to your extension or application. You create
a resource bundle as follows:

1=Error message one


2=Error message with 2 parameters; param {0} and param {1}
...

where the number is the message ID and the actual message comes after. Note that message parameters
are specified using '{0}' notation, which is standard when using the Java MessageFormat class.

Document generated by Confluence on Oct 27, 2008 21:07 Page 342


The file should be named x-messages.properties where x is the identifying name for this bundle.
You must place this file either in your JAR file under META-INF/services/org/mule/i18n/x-
messages.properties or any other location on the classpath.

To access the messages of your own resource bundle, you create a subclass of MessageFactory as
follows:

public class MyMessages extends MessageFactory


{
// getBundlePath puts together the correct path (META-INF/services/org/mule/i18n/my-
messages.properties)
private static final String BUNDLE_PATH = getBundlePath("my");

public static Message errorMessageOne()


{
return createMessage(BUNDLE_PATH, 1);
}

public static Message anotherErrorMessage(Object param1, Object param2)


{
createMessage(BUNDLE_PATH, 2, param1, param2);
}
}

To load a message from this bundle, pass in the resource bundle name as follows:

Message m = MyMessages.anotherErrorMessage("one", "two");


System.out.pritln(m.toString());

This loads the message with ID 2 from x-messages.properties, formats the message with the
parameters "one" and "two", and prints out the message to System.out as follows:

Error message with 2 parameters; param one and param two

Creating Message Instances from your Code


If you need Message instances from your custom code (e.g., from a custom transformer), you create
them as follows:

Message myMessage = MessageFactory.createStaticMessage("Oops");

Document generated by Confluence on Oct 27, 2008 21:07 Page 343


Introduction to Extending Mule

This page last changed on Aug 29, 2008 by jackie.wheeler.

Introduction to Extending Mule


Mule provides a great deal of default functionality that you can use in your implementation. If you need
different functionality, you can extend Mule as described on this page.

Creating New Functionality


A module is a package of related functionality in Mule, such as the XML module, which provides XML-
based utilities such as filters and routers. For a list of the available modules you can use, see Using Mule
Modules. To create a new module, see Creating Additional Extensions.

A transport is a type of module that carries messages between Mule services via a specific protocol. You
can customize a transport, or you can create a new one. For a list of the available transports you can use,
see Available Transports.

Developing Your Module


You can use an integrated development environment (IDE) such as Eclipse, IntelliJ, and Mule IDE to
rapidly develop Mule applications. For more information, see Using IDEs.

Mule provides a Maven Project Archetype and a Maven Transport Archetype that create template files,
including all the necessary Java boilerplate and detailed implementation instructions in comments, for a
new Mule project or transport. For more information, see Using Maven in the Mule Developer's Guide.

Promoting Your Module on MuleForge


After you have created a new module, you can submit it as a project on MuleForge. This allows you to
share it with the Mule community so you can get feedback on the quality and design of the module before
putting it into production. By submitting to MuleForge, you get the benefit of others trying out your
module, and others get the benefit of your work. For more information, see About MuleForge.

Internationalizing Mule
If you will use Mule in countries where English is not spoken, you can extend Mule by internationalizing
the strings in the messages and exceptions. Additionally, there are guidelines you should take
into consideration to make sure your code handles different locales. For more information, see
Internationalizing Strings and Internationalization Guidelines.

Document generated by Confluence on Oct 27, 2008 21:07 Page 344


Introduction to Testing Mule

This page last changed on Jul 18, 2008 by jackie.wheeler.

Introduction to Testing Mule


This page describes the types of testing you can perform on Mule.

Functional and Unit Tests


When you configure and customize Mule, you perform the following types of tests:

• Functional testing of your Mule configuration and setup


• Unit testing of your simple extensions and customizations
• Functional and unit testing of your custom modules and transports

Mule provides functional test classes in the org.mule.tck and org.mule.tck.functional packages
that allow you to test your configuration as well as your custom modules and transports. For more
information, see Functional Testing. Additionally, the Mule test JAR file contains abstract test cases
that you can use for unit testing your simple extensions (e.g., AbstractTransformerTestCase
and AbstractOutboundRouterTestCase) as well as your custom modules and transports (e.g.,
AbstractConnectorTestCase, AbstractReceiverTestCase, AbstractDispatcherTestCase, and
AbstractEndpointTestCase). For more information, see Unit Testing.

Performance Tests
After you have ensured that your setup and configuration are correct and that your customizations are
working, you should ensure that your system is performing correctly. You can run Japex benchmark tests
to test individual packages. Additionally, the Mule Profiler Pack helps you identify memory leaks in your
customizations.

Using MuleForge for Continuous Integration Testing


If you host your Mule project on MuleForge, you can take advantage of continuous integration testing.
MuleForge projects are configured to be automatically built using Bamboo, a Continuous Integration Build
Server from Atlassian. The source code build frequency is set to 30 minutes, while the snapshot build
frequency is set to 1 day. You can request that these frequencies be changed for your project.

For more information on hosting your project on MuleForge, see the Despot's Guide.

Document generated by Confluence on Oct 27, 2008 21:07 Page 345


JavaRebel Integration

This page last changed on Jun 27, 2008 by jackie.wheeler.

This page is under construction

Prerequisites

• Internet connection
• Java 5

Instructions

We'll use a Hello Example bundled with Mule to demonstrate the setup.

1. Download Mule 1.4.4-SNAPSHOT from the downloads page. Instructions apply to Mule 2.x as well.
2. Configure JAVA_HOME, MULE_HOME and run Mule for the first time to accept the license.
3. Download JavaRebel 1.0-M3 snapshot from http://www.zeroturnaround.com/download/
4. Unpack, copy javarebel.jar to $MULE_HOME/bin to keep things simple.
5. Change into $MULE_HOME/examples/hello
6. Generate project files mvn idea:idea (mvn eclipse:eclipse for, right, Eclipse)
7. Change module output path to compile into $MULE_HOME/lib/user
8. Delete mule-example-hello.jar from $MULE_HOME/lib/user. It contains the same classes we're
compiling. JavaRebel supports only exploded class reloading currently.
9. Make the project.
10. Start Mule with an extra switch to enable JavaRebel:
mule -config hello-config.xml -M-javaagent:../../bin/javarebel.jar -M-noverify
Note that we reference the config file as a resource - it's been put on the classpath in lib/user when
you built the project.
11. Type your name when prompted, watch the standard reply. Now let's have some fun.
12. Modify org.mule.samples.hello.Greeter#greet() method. Let's make it more rebellious: modify
the code to set a new greeing:

public Object greet(NameString person) {


...
person.setGreeting("Wazzup ");
...
}
13.
Make the project. Type Dude when prompted. Enjoy

Tips & Tricks

Hey, it works in debug mode as well, including remote. Just add the -debug switch to the Mule start
command and connect your debugger on port 5005 (default). Just make sure to say No when you see

debugger's prompt to reload classes - let JavaRebel rock IDEA users may need to get the JavaRebel
debugger plugin, see the troubleshooting section below.

Troubleshooting

• I get weird exception with strange class names - don't put javarebel.jar in $MULE_HOME/
lib/user. It's easier not to do it, then explain why it may fail for certain cases (complex classloader
tricks).
• It won't reload! - if nothing else works, then the worst to happen is restarting Mule.
• It won't reload Mule core classes! - these instructions apply to custom user classes only.
• Debugger never stops at breakpoint in IDEA - This is a known issue, JetBrains and
ZeroTurnaround are actively working on it. Doesn't affect Eclipse users (uses different mechanism).
Update: this has been resolved now. Download the JavaRebel Debugger plugin from IntelliJ IDEA
plugin repo (or go to http://plugins.intellij.net/plugin/?id=1699). These changes might be included
in IDEA's core in the future.

Document generated by Confluence on Oct 27, 2008 21:07 Page 346


• I can't compile the code in IDEA - make sure the JDK is properly configured for the project. If
you know the name of the JDK as it is listed in IDEA, you can use it during project files generation:
mvn idea:idea -DjdkName=1.6
• I get a JVM core dump under JDK 6 Update N - it may or may not work under Java 6. There's
a regression in Java 6 Update N, which has been identified and reported. Apparently, something is
wrong with their dev process, as they claim to have fixed it in b05 when they haven't in fact. Bug
them! It still works with some Java 6 builds, depending on your setup. Java 5 is more stable for
such work now.

Document generated by Confluence on Oct 27, 2008 21:07 Page 347


Jmx Management

This page last changed on Oct 23, 2008 by jackie.wheeler.

JMX Management
[ Using the Default JMX Support Agent ] [ Jmx Default Config ] [ Configuring the JMX Agent ] [ Jmx
Server ] [ Remote Management ] [ JMX Notifications Agent ] [ Endpoint Notifications Publisher Agent ] [
Log4J Agent ] [ Log4J Notifications Agent ] [ Chainsaw Notifications Agent ] [ MX4J Adapter ] [ Jmx Mx4j
Adaptor ] [ YourKit Profiler ]

Java Management Extensions (JMX) is a simple and standard way to manage applications, devices,
services, and other resources. JMX is dynamic, so you can use it to monitor and manage resources as
they are created, installed, and implemented. You can also use JMX to monitor and manage the Java
Virtual Machine (JVM).

Each resource is instrumented by one or more Managed Beans, or MBeans. All MBeans are registered in
an MBean Server. The JMX server agent consists of an Mbean Server and a set of services for handling
Mbeans.

There are several agents provided with Mule for JMX support. The easiest way to configure JMX is to use
the default JMX support agent.

Using the Default JMX Support Agent


You can configure several JMX agents simultaneously using the <jmx-default-config> element. When
set, this element registers the following agents:

• JMX agent
• RMI registry agent (if necessary) on rmi://localhost:1099
• Remote JMX access on service:jmx:rmi:///jndi/rmi://localhost:1099/server
• Log4J JMX agent, which exposes the configuration of the Log4J instance used by Mule for JMX
management
• JMX notification agent used to receive server notifications using JMX notifications
• (Optional) MX4J adapter, which provides web-based JMX management, statistics, and configuration
viewing of a Mule instance

This element includes the following properties:

Jmx Default Config

Attributes of <jmx-default-config...>

Name Type Required Default Description

registerMx4jAdapter boolean no Whether to enable


the MX4J adaptor.

host string no The host to bind


to. Normally,
override this only
for multi-NIC
servers (default is
localhost).

port port number no The port on


which the RMI
registry will run.
This is also used

Document generated by Confluence on Oct 27, 2008 21:07 Page 348


for remote JMX
management.
Default is 1099.

Child Elements of <jmx-default-config...>

Name Cardinality Description

credentials 0..1 A map of username/password


properties for remote JMX
access. The configuration option
delegates to the JmxAgent.

For example:

<?xml version="1.0" encoding="UTF-8" ?>


<mule xmlns="http://www.mulesource.org/schema/mule/core/2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:management="http://www.mulesource.org/schema/mule/management/2.0"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.mulesource.org/schema/mule/core/2.0
http://www.mulesource.org/schema/mule/core/2.0/mule.xsd
http://www.mulesource.org/schema/mule/management/2.0
http://www.mulesource.org/schema/mule/management/2.0/mule-management.xsd">
<management:jmx-default-config port="1098" registerMx4jAdapter="true">
<management:credentials>
<spring:entry key="jsmith" value="foo"/>
<spring:entry key="dthomas" value="bar"/>
<spring:entry key="clee" value="pwd"/>
</management:jmx-default-config>
</mule>

The default agent does a lot of useful plumbing for JMX but at the expense of defaulting many
parameters. If you need to customize some subsystems, you could either:

• Subclass DefaultJmxSupportAgent and override the corresponding createXXX() factory methods.


• Disassemble the services provided by this support agent into separate agents and configure them
individually.

Configuring the JMX Agent


The JMX agent enables the configuration of a local or remote JMX connection to Mule and registers
Mule services with the MBean server. You can then use JMX to view the configuration state of the
Mule Manager, stop and start the Mule instance, stop and start services, stop/start/resume service
components, and query event processing and endpoint routing statistics on individual services or the
whole server instance.

You configure the JMX agent using the <jmx-server> element. You can set the following properties on the
agent.

Jmx Server

Attributes of <jmx-server...>

Name Type Required Default Description

Document generated by Confluence on Oct 27, 2008 21:07 Page 349


server-ref name (no spaces) no The mBean server
to use.

locateServer boolean no true Whether the agent


should try locating
an MBeanServer
instance before
creating one.

createServer boolean no true Whether the


agent should
create an MBean
server if one
couldn't be found
or locateServer
was set to false.

enableStatistics boolean no true Whether statistics


reporting is
enabled for the
Mule instance.

Child Elements of <jmx-server...>

Name Cardinality Description

connector-server 0..1 Configures the remote JMX


connector server by specifying
the URL and whether to rebind.

credentials 0..1 A map of username/password


entries used to authenticate
remote JMX access. If not
specified, remote access is not
restricted.

For example:

<management:jmx-server >
<management:connector-server url="http://myjmxserver.com:1099" rebind="false" />
<management:credentials>
<spring:entry key="jsmith" value="foo" />
<spring:entry key="dthomas" value="bar" />
</management:credentials>
</management:jmx-server>

Note that the JMX domain for the Mule server is taken from the Mule server ID. To set the server ID, you
the -M-Dmule.serverId=YOUR_MULE_SERVER_ID system property or set it programatically by calling
org.mule.config.DefaultMuleConfiguration.setId().

Remote Management
You can configure the Mule JMX subsystem for remote management with third-party tools like MC4J. Mule
provides an RMI registry agent, which binds to an existing RMI registry or creates a new one on a defined
URI.

You configure the RMI registry agent using the <rmi-server> element. This element has two attributes:
serverUri, which you set to the URI of the RMI server (the
default is rmi://localhost:1099), and createRegistry, which you set to true if you want to create a new
registry instead of binding to an existing one.

Document generated by Confluence on Oct 27, 2008 21:07 Page 350


For example:

<management:rmi-server serverUri="rmi://myServer.com:1099" createRegistry="true" />

JMX Notifications Agent


The <jmx-notifications> element configures the JMX notifications agent, which sends JMX server
notifications. This element takes the following attributes:

Attribute Description

ignoreManagerNotifications Whether to ignore notifications for state changes


on the Mule manager such as initializing, starting,
and stopping.

ignoreModelNotifications Whether to ignore notifications for state changes


on models such as models initializing, starting,
and stopping or components being registered or
unregistered.

ignoreComponentNotifications Whether to ignore notifications for state changes


on components such as when a component is
started, stopped, paused, or resumed.

ignoreConnectionNotifications Whether to ignore notifications when a connector


attempts to connect to its underlying resource.
Notifications are fired when a connection is made,
released, or the connection attempt fails.

ignoreSecurityNotifications Whether to ignore notifications about security.

ignoreManagementNotifications Whether to ignore notifications for when a request


is denied security access.

ignoreCustomNotifications Whether to ignore notifications fired by objects to


custom notification listeners.

ignoreAdminNotifications Whether to ignore administrative notifications


about requests being received by the Mule Admin
agent. These are usually trigged by MuleClient
calls using the RemoteDispatcher, which proxies
calls to a remote server.

ignoreMessageNotifications Whether to ignore message notifications. These


notifications are fired when an event is sent or
received in the system. They are very good for
tracing, but they create a performance impact, so
they should only be used during testing.

For example:

<management:jmx-notifications ignoreAdminNotifications="true" ignoreMessageNotifications="true" />

Endpoint Notifications Publisher Agent


This agent routes server notifications to a specified endpoint URI. You configure it using the <publish-
notifications> element and specify the endpoint using the endpointAddress attribute. For example:

<management:publish-notifications endpointAddress="vm://myService" />

Document generated by Confluence on Oct 27, 2008 21:07 Page 351


Log4J Agent
The log4j agent exposes the configuration of the Log4J instance used by Mule for JMX management. You
enable the Log4J agent using the <jmx-log4j> element. It does not take any additional properties.

For example:

<management:jmx-log4j/>
</mule>

Log4J Notifications Agent


The Log4J notifications agent logs server notifications to a file or console using Log4J. You configure this
agent using the <log4j-notifications> element. It takes the same attributes as the JMX notifications
agent plus two additional attributes: logName, a name used to identify this log, and logConfigFile, the
name of the file where you want to output the log messages.

The Log4J notifications agent also takes the <level-mapping> child element, which takes one or more
pairs of severity/eventId attributes. The severity attribute specifies the severity level of the notifications
you want to log for the corresponding event ID. The severity level can be DEBUG, INFO, WARN, ERROR,
or FATAL. The eventId attribute specifies the type of event to log. The event ID is the notification type
plus the action, such as ModelNotification.stop.

For example:

<management:log4j-notifications logName="myMuleLog" logConfigFile="mule-log.txt">


<management:level-mapping eventId="ModelNotification.stop" severity="WARN"/>
</management:log4j-notifications>

Chainsaw Notifications Agent


The Chainsaw notifications agent logs server notifications to a Chainsaw console. You configure this agent
using the <chainsaw-notifications> element. It takes the same attributes as the JMX notifications
agent plus two additional attributes: chainsawHost and {chainsawPort}}, which specify the host name
and port of the Chainsaw console.

The Chainsaw notifications agent also takes the <level-mapping> child element, which takes one or
more pairs of severity/eventId attributes. The severity attribute specifies the severity level of the
notifications you want to send to the Chainsaw console for the corresponding event ID. The severity
level can be DEBUG, INFO, WARN, ERROR, or FATAL. The eventId attribute specifies the type of
event to send to the Chainsaw console. The event ID is the notification type plus the action, such as
ModelNotification.stop.

For example:

<management:chainsaw-notifications chainsawHost="localhost" chainsawPort="20202">


<management:level-mapping eventId="ModelNotification.stop" severity="WARN"/>
</management:chainsaw-notifications>

MX4J Adapter
MX4J is an open source implementation of the JMX technology. The MX4J agent for Mule configures an
MX4J HTTP adapter to provide JMX management, statistics, and configuration viewing of a Mule instance.
You configure the MX4J agent using the <jmx-mx4j-adaptor> element.

Document generated by Confluence on Oct 27, 2008 21:07 Page 352


Jmx Mx4j Adaptor

Attributes of <jmx-mx4j-adaptor...>

Name Type Required Default Description

jmxAdaptorUrl string no The URL of


the JMX web
console. The
default is http://
localhost:9999.

login string no The login name


for accessing the
JMX web console.

password string no The password for


accessing the JMX
web console.

authenticationMethodnone/basic/digest no basic The type of


authentication
to perform when
the login and
password are
set: basic (the
default), digest, or
none.

cacheXsl string no true Indicates whether


to cache the
transformation
objects, which
speeds-up the
process. It is
usually set to
true, but you can
set it to false for
easier testing.

xslFilePath string no Specifies the path


of the XSL files
used to customize
the adaptor's
stylesheet. If
you specify a
directory, it
assumes that XSL
files are located
in the directory.
If you specify
a .jar or .zip file, it
assumes that the
files are located
inside. Specifying
a file system is
especially useful
for testing.

pathInJar string no If the xslFilePath


is a JAR file,

Document generated by Confluence on Oct 27, 2008 21:07 Page 353


specifies the
directory in the
JAR where the
XSL files are
located.

Child Elements of <jmx-mx4j-adaptor...>

Name Cardinality Description

socketFactoryProperties 0..1 A map containing properties


for SSL server socket factory
configuration. If this element
contains at least one property,
the agent will switch to HTTPS
connections. These properties
will be delegated as is to the
agent's HTTP/S adaptor. For a
list of available properties, see
the MX4J API documentation.

For example:

<management:jmx-mx4j-adaptor jmxAdaptorUrl="https://myjmxserver.com:9999">
<management:socketFactoryProperties>
<spring:entry key="keystore" value="/path/to/keystore" />
<spring:entry key="storepass" value="storepwd" />
</management:socketFactoryProperties>
</management:jmx-mx4j-adaptor>

For security's sake, the management console is accessible from the localhost only. To loosen this
restriction, change "localhost" to "0.0.0.0", which allows access from any computer on the LAN. For more
information, see the MX4J documentation.

MX4J Security

You can protect the JMX web console with a user name and password. If the login property has been
specified, the authentication scheme is applied.

In addition to protecting the console, you can protect the in-transit data using SSL. If the
socketFactoryProperties element contains at least one property, the agent switches to HTTPS
connections. If this element is omitted from the configuration, the agent will always use HTTP, even if you
specify https:// in the jmxAdaptorUrl property.

Viewing Statistics

Mule traps many different statistics about the running state of a server and number of events processed.
You can view the Mule statistics report in the JMX Management Console by pointing your browser to
http://localhost:9999/ and then clicking on any JMX domain name (except for JMImplementation), or go
to the Statistics tab and query the JMX domain for statistics from there.

Document generated by Confluence on Oct 27, 2008 21:07 Page 354


YourKit Profiler
This agent exposes the YourKit profiler to JMX to provide CPU and memory profiling. To use this agent,
you must configure the <yourkit-profiler> element as shown below, and you must install and run the
Profiler as described in Profiling Mule.

<management:yourkit-profiler />

Document generated by Confluence on Oct 27, 2008 21:07 Page 355


Models

This page last changed on Oct 03, 2008 by jackie.wheeler.

About Models
[ Configuring a Model ] [ Model Interface ]

A model is a grouping of services. A model manages the runtime behavior of the service components
that a Mule instance hosts. The manner in which these components are invoked and treated is all
encapsulated inside the current Mule model.

Configuring a Model
To configure a model, you add the <model> element to your Mule configuration file. You then add services
within the model. For configuration details, see the Model Configuration Reference.

Model Interface
Every Mule model implements the Model interface. This interface represents the behavior of a Mule server
and works with the following objects. For a complete list of fields and methods, see in the Model interface
org.mule.api.model.Model . Also, see org.mule.model.AbstractModel , which is an abstract class that
implements this interface and is the parent for all models.

Object Description

Name A string that refers to the name of the model and


is set as an attribute in the <model> element. If
no name is given, a unique value is generated
automatically.

ExceptionListener The exception strategy to use for the entire


model. The exception strategy is used to handle
any exceptions that occur when a component is
processing a message. For more information on
exception strategies, see Error Handling.

EntryPointResolverSet A set of classes that implement the


EntryPointResolver interface. These will be
used to determine the entry point for any hosted
component when a message is received. You
can configure an entry point resolver using the
<abstract-entry-point-resolver> element
or configure an entry point resolver set using
the <abstract-entry-point-resolver-set>
element. For more information on entry point
resolvers, see Developing Service Components.

LifecycleAdapterFactory Used by the model to create lifecycle adapters


that are needed to translate Mule lifecycle events
into messages that components registered with
the model understand. You configure the lifecyle
adapter on the <component> elements, not on
the model itself. For more information on lifecycle
adapters, see Developing Service Components.

Document generated by Confluence on Oct 27, 2008 21:07 Page 356


Mule Agents

This page last changed on Sep 24, 2008 by jackie.wheeler.

Using Mule Agents


[ Configuring an Agent ] [ Creating Custom Agents ]

An agent is a service that is associated with or used by Mule but is not a Mule-managed component.
Agents have the same lifecycle as the Mule instance they are registered with, so you can initialize and
destroy resources when the Mule instance starts or is disposed.

Mule provides several agents for JMX support, including notifications and remote management. You
can also create custom agents to plug any functionality into Mule, such as running functionality as a
background process or embedding a server in Mule.

Configuring an Agent
Agents are defined in the Management module. To use an agent, specify the management namespace and
schema, and then specify the properties for the agents you want to use. For example:

<mule xmlns="http://www.mulesource.org/schema/mule/core/2.0"
...
xmlns:management="http://www.mulesource.org/schema/mule/management/2.0"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-2.5.xsd
http://www.mulesource.org/schema/mule/core/2.0 http://www.mulesource.org/schema/mule/core/2.0/
mule.xsd
http://www.mulesource.org/schema/mule/management/2.0 http://www.mulesource.org/schema/mule/
management/2.0/mule-management.xsd"
...>
<management:jmx-default-config port="1098" registerMx4jAdapter="true" />

<management:log4j-notifications logName="myMuleLog" logConfigFile="mule-log.txt"/>

<management:chainsaw-notifications chainsawPort="8080" chainsawHost="127.0.0.1" />

<management:publish-notifications endpointAddress="vm://myService" />


...

For a list of agents provided with Mule and how to configure them, see JMX Management. You can also
create a custom agent as described below.

Creating Custom Agents


To create your own agent, your agent class must implement org.mule.api.agent.Agent . You then
configure your agent using the <custom-agent> element, which takes two attributes: name specifies a
unique name for this agent, and class specifies the class where it's defined. If your agent requires that
you pass in properties, you can specify them as name/value pairs.

For example:

<management:custom-agent name="test-custom-agent" class="org.mule.tck.testmodels.mule.TestAgent">


<spring:property name="frobbit" value="woggle"/>
</management:custom-agent>

Document generated by Confluence on Oct 27, 2008 21:07 Page 357


Mule Instances

This page last changed on Aug 04, 2008 by jackie.wheeler.

Mule Instances
This page is under construction

##describe Mule instances, when to have multiple instances, etc.

Document generated by Confluence on Oct 27, 2008 21:07 Page 358


Mule Server Notifications

This page last changed on Sep 04, 2008 by jackie.wheeler.

This page is ready for review

Mule Server Notifications


[ Configuring Notifications ] [ Firing Custom Notifications ] [ Notification Interfaces ] [ Registering
Listeners Programmatically ]

Mule provides an internal notification mechanism that you can use to access changes that occur on
the Mule Server, such as a service component being added, a Mule Model being initialized, or the Mule
Manager being started. You can set up your agents or service components to react to these notifications.

Don't confuse notifications with the service events that Mule manages between your service
components and external applications. Notifications are based on changes to the objects
that comprise the Mule Server, whereas service events are the business operations that
your business services process.

Configuring Notifications
Message notifications provide a snapshot of all information sent into and out of the Mule Server. These
notifications are fired whenever a message is received or sent. These additional notifications have some
impact on performance, so they are disabled by default. To enable message notifications, you set the
type of messages you want to enable using the <notifications> element in your Mule configuration file.
You also register the notification listeners and associate interfaces with specific events. For example, first
you create beans for the notification listeners, specifying the class of the type of notification you want to
receive:

<spring:bean name="componentNotificationLogger"
class="org.myfirm.ComponentMessageNotificationLogger"/>
<spring:bean name="endpointNotificationLogger"
class="org.myfirm.EndpointMessageNotificationLogger"/>

Next, you specify the types of messages for which you want to enable the notifications using the
<notification> element, and then register the listeners using the <notification-listener> element:

<notifications>
<notification event="COMPONENT-MESSAGE"/>
<notification event="ENDPOINT-MESSAGE"/>
<notification-listener ref="componentNotificationLogger"/>
<notification-listener ref="endpointNotificationLogger"/>
</notifications>

When you set the COMPONENT-MESSAGE event, a notification is sent before and after a component
is invoked. When you set ENDPOINT-MESSAGE, a notification is sent whenever a message is sent,
dispatched, or received on an endpoint. Because the listeners implement the interface for the type of
notification they want to receive (for example, the ComponentMessageNotificationLogger class would
implement org.mule.api.context.notification.ComponentMessageNotificationListener), the
listeners receive the correct notifications.

For a list of notification event types, see Notifications Configuration Reference. For a list of notification
listener interfaces, see Notification Interfaces below.

Specifying a Different Interface

If you want to change the interface that is associated with an event, you specify the new interface with
the interface-class and interface attributes:

<notifications>

Document generated by Confluence on Oct 27, 2008 21:07 Page 359


<notification event="COMPONENT-MESSAGE" interface-class="org.myfirm.MyMessageNotifications"
interface="myComponentListener"/>

Configuring a Custom Notification

If you create a custom notification, you also specify the event-class attribute:

<notifications>
<notification event="CUSTOM-MESSAGE" event-class="org.myfirm.MyMessageNotificationsCustomMessage"
interface-class="org.myfirm.MyMessageNotifications" interface="myCustomListener"/>
...

Disabling Notifications

If you want to block a specific interface from receiving an event, you specify it with the <disable-
notification> element. You can specify the event, event class, interface, and/or interface class to block.

<notifications>
<disable-notification interface="ComponentMessageNotificationListener"/>
...

Using Event Subscriptions

When registering a listener, you can specify that it only receive notifications from a specific component
using the subscription attribute. For example, to specify that the listener only receive messages from a
service component called "MyService1", you would configure the listener as follows:

<notification-listener ref="endpointNotificationLogger" subscription="MyService1"/>

You can also register listeners and filter the subscriptions from your Java code:

MuleServer.getMuleContext().registerListener(listener, "MyService1");

To register interest in events from all service components with "Service" in the name, you would use a
wildcard string as follows:

MuleServer.getMuleContext().registerListener(listener, "*Service*");

Firing Custom Notifications


Custom notifications can be fired by objects in Mule to notify custom listeners. For example, a discovery
agent might fire a Client Found notification when a client connects.

You fire a custom notification as follows:

CustomNotification n = new CustomNotification("Hello");


MuleServer.getMuleContext().fireNotification(n);

Any objects implementing CustomNotificationListener will receive this event. It's a good idea to
extend CustomNotification and define actions for your custom event type. For example:

DiscoveryNotification n = new DiscoveryNotification(client, DiscoveryNotification.CLIENT_ADDED);


MuleServer.getMuleContext().fireNotification(n);

Non-system objects in Mule can only fire custom notifications through the
manager. Attempting to fire other events such as ModelNotification will cause an
UnsupportedOperationException.

Document generated by Confluence on Oct 27, 2008 21:07 Page 360


Notification Interfaces
The following table describes the Mule server notifications and the interfaces in the
org.mule.api.context.notification class an object can implement to become a listener for that notification.
All listeners extend the ServerNotificationListener interface.

Notification Description Interface

Component Message Notification A message was processed ComponentMessageNotificationListener


by a service component. See
Enabling Message Notifications
below for more info.

Connection Notification A connector connected to ConnectionNotificationListener


its underlying resource or
released the connection, or the
connection attempt failed.

Custom Notification Can be fired by objects CustomNotificationListener


themselves to custom
notification listeners and can be
used to customize notifications
on agents, service components,
connectors, and more.

Endpoint Message Notification A message was sent or received EndpointMessageNotificationListener


from an endpoint. See Enabling
Message Notifications below for
more info.

Exception Notification An exception was thrown. ExceptionNotificationListener

Management Notification The state of the Mule instance or ManagementNotificationListener


its resources have changed.

Message Notification An event was sent or received in MessageNotificationListener


the system. These notifications
are very good for tracing, but
they are not enabled by default
because they have an impact
on performance. See Enabling
Message Notifications below for
more information.

Model Notification The state is changing on a ModelNotificationListener


model, such as initializing,
starting and stopping, or
service components within the
model are being registered or
unregistered.

Mule Context Notification An event occurred on the Mule MuleContextNotificationListener


Manager.

Registry Notification An event occurred on the RegistryNotificationListener


registry.

Routing Notification A routing event such as an RoutingNotificationListener


async-reply miss occurred.

Document generated by Confluence on Oct 27, 2008 21:07 Page 361


Security Notification A request was denied security SecurityNotificationListener
access.

Server Notification Fired when the server, models, ServerNotificationListener


and components stop, start, or
initialize.

Service Notification An event occurred on a service. ServiceNotificationListener

Transaction Notification During transaction life cycle TransactionNotificationListener


after a transaction has begun,
was committed, or was rolled
back.

The listener interfaces all have a single method:

public void onNotification(ServerNotification notification);

Depending on the listener implemented, only certain events will be received. For example, if the object
implements ManagerNotificationListener, only events of type ManagerNotification will be received.
Objects can implement more than one listener to receive more types of events.

Registering Listeners Programmatically


You can register listeners on the Mule Context as follows:

MuleServer.getMuleContext().registerListener(listener);

Each event has an action code that determines the type of event. The action code can be queried in the
onEvent method to determine its type. For example, to have an object do something when the model
initializes:

MyObject.java

public class MyObject implements ModelNotificationListener


{
public MyObject()
{
MuleServer.getMuleContext().registerListener(this);
}

public void onNotification(ServerNotification notification)


{
if (notification.getAction() == ModelNotification.MODEL_INITIALISED)
{
system.out.println("The model is initialized!");
}
}
}

For a list of the action codes available with each notification type, see the Javadocs for the
org.mule.context.notification package and click on the class of the notification type you want.

Notification Payloads

All notifications extend java.util.EventObject, and the payload of the object can be accessed using the
getSource() method. The following table describes the event payloads for each type of event.

Notification Payload Type Resource ID Description

Document generated by Confluence on Oct 27, 2008 21:07 Page 362


Component Message Component Component name The service component
Notification that triggered this
notification

Connection Notification Connectable <connector- The message receiver


or message dispatcher
name>.receiver(<endpoint-
uri>) that was connected

Custom Notification Any object Any String The object type is


custom to the object
firing the event

Endpoint Message ImmutableEndpoint Endpoint URI The endpoint that


Notification triggered this
notification

Exception Notification Throwable Component Name The service component


that triggered this
notification

Management Object The object ID The monitored object


Notification that triggered this
notification

Message Notification MuleMessage Message ID The message sent or


received

Model Notification Model Model Name The Model instance


on the Mule Context.
Equivalent to calling
MuleContext.getRegistry().lookupMod

Mule Context MuleContext Mule context ID The Mule context


Notification instance. Equivalent
to calling
getMuleContext().

Registry Notification Registry Mule registry ID The Mule registry.


Equivalent to calling
MuleContext.getRegistry().

Routing Notification MuleMessage Message ID The message sent or


received

Security Notification SecurityException The exception message The security exception


that occurred

Service Notification Service Service ID The service that


triggered this
notification

Transaction Notification Transaction Component name The component


that triggered this
notification

Document generated by Confluence on Oct 27, 2008 21:07 Page 363


Offline Documentation

This page last changed on Apr 24, 2008 by tcarlson.

A static export of the on-line documentation is created for each major release. This can be useful for
reading off-line.

Name Size Creator Date Comment


396 kb Travis Carlson Apr 24, 2008 Edit |
Remove
mule-2.0.0-
users-
guide.pdf

Document generated by Confluence on Oct 27, 2008 21:07 Page 364


Profiling Mule

This page last changed on Sep 29, 2008 by jackie.wheeler.

Profiling Mule
[ Installing the Profiler Pack ] [ Enabling the Profiler Agent ] [ Running the Profiler ] [ Embedded Mule ]

The Mule Profiler Pack uses YourKit to provide CPU and memory profiling, helping you identify memory
leaks in your custom Mule extensions. The Profiler is useful during development and testing. In your
production environment, you should turn off the Profiler because of the high performance overhead. You
can also use any other Profiler, such as JProfiler, by adding it as an agent in your configuration.

Installing the Profiler Pack


If you are installing Mule Enterprise Edition, simply select the Profiler check box when installing the
product.

If you are installing Mule Community Edition, go to the downloads page, and under the latest stable
community release, expand the Downloads section. You can then click the link to the .zip, .tar, or .gz
version of the Profiler pack. After downloading, unpack it on top of the Mule installation.

Enabling the Profiler Agent


The Profiler agent exposes the YourKit Profiler to JMX to provide CPU and memory profiling. You configure
the Profiler agent with the <management:yourkit-profiler> element. For more information, see JMX
Management.

Running the Profiler


To run the profiler, you run Mule with the -profile switch plus any extra YourKit startup options with
multiple parameters separated by commas, e.g. -profile onlylocal,onexit=memory. This integration
pack will automatically take care of configuration differences for Java 1.4.x and 5.x/6.x.

Embedded Mule
If you are running Mule embedded in a webapp, the Profiler configuration is completely delegated to
the owning container. Launch YourKit Profiler, Tools -> Integrate with J2EE server... and follow the
instructions. Typically, a server's launch script is modified to support profiling, and you then use this
modified start script instead of the original.

Document generated by Confluence on Oct 27, 2008 21:07 Page 365


Resource Adapter

This page last changed on Aug 22, 2008 by jackie.wheeler.

Mule JCA Resource Adapter


The Mule JCA resource adapter enables a Mule instance to be deployed to a J2EE application server. It can
be deployed to any JCA 1.5 compliant container. See Deployment Scenarios for links to information about
specific application server configurations.

You can download the resource adapter here.

EJB configuration
The resource adapter supports inbound and outbound communication.

Outbound Bean Configuration

<session>
<description>A stateless session bean that sends a message over a Mule transport
</description>
<display-name>SenderEJB</display-name>
<ejb-name>SenderEJB</ejb-name>
<home>org.mule.samples.ejb.SenderHome</home>
<remote>org.mule.samples.ejb.Sender</remote>
<ejb-class>org.mule.samples.ejb.SenderBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
<resource-ref>
<res-ref-name>mule/connectionFactory</res-ref-name>
<res-type>org.mule.ra.MuleConnectionFactory</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Unshareable</res-sharing-scope>
</resource-ref>
</session>

Inbound Configuration

The endpoint property must be a valid endpoint URI to receive Mule events.

<message-driven>
<description>An MDB listening on a Tcp socket</description>
<display-name>TcpReceiverMDB</display-name>
<ejb-name>TcpReceiverMDB</ejb-name>
<ejb-class>org.mule.samples.ejb.SimpleReceiverMessageBean</ejb-class>
<messaging-type>org.mule.api.lifecycle.Callable</messaging-type>
<transaction-type>Container</transaction-type>
<activation-config>
<activation-config-property>
<activation-config-property-name>endpoint</activation-config-property-name>
<activation-config-property-value>tcp://localhost:12345
</activation-config-property-value>
</activation-config-property>
</activation-config>
</message-driven>

Document generated by Confluence on Oct 27, 2008 21:07 Page 366


Streaming

This page last changed on Oct 24, 2008 by jackie.wheeler.

Streaming
This page is under construction

Several of Mule's transports support streaming, which enables efficient processing of large data objects
such as files, documents, and records by streaming the data through Mule rather than reading the whole
thing into memory. The following transports support streaming:

• CXF
• File
• HTTP/S
• Jetty/Jetty SSL
• Servlet
• SOAP
• STDIO
• TCP
• UDP
• VM

Advantages of Streaming
Streaming provides the following advantages:

• Allows services to consume very large messages in an efficient way


• Message payloads are not read into memory
• Simple routing rules based on message metadata are still possible
• You can combine streaming and non-streaming endpoints

TODO: update the rest of this page to 2.1

Using Streaming in Mule


Streaming works very differently from the usual SEDA event-driven processing model that most Mule
users are already familiar with. Streaming components need to implement the

org.mule.impl.model.streaming.StreamingService

interface -

public interface StreamingService


{
void call(InputStream in, OutputStream out, UMOEventContext context)
throws Exception;
}

• InputStream in - The data being recived by the inbound endpoint


• OutputStream out - The stream to write processed data to
• UMOEventContext content - Meta information about this stream event including properites, session
info and origin information. Note that routers can be configured to router to different outbound
streaming endpoints based on information in the event context. So manipulating the event context
can change where the Outputstream out actually writes to.

Use Case 1 - File to Tcp


The following examples demonstrates how to configure a simple usecase where the contents of a file are
streamed directly to a socket.

Document generated by Confluence on Oct 27, 2008 21:07 Page 367


<model type="streaming" name="main">
<mule-descriptor name="fileTcpBridge"
implementation=org.mule.components.simple.StreamingBridgeComponent">
<inbound-router>
<endpoint address="file://${mule.working.dir}/in" streaming="true"/>
</inbound-router>
<outbound-router>
<router className="
org.mule.routing.outbound.OutboundPassthroughRouter>
<endpoint address="tcp://localhost:34561" streaming="true"/>
</router>
</outbound-router>
</mule-descriptor>
</model>

Notice that the <model> type is 'streaming' and that each of the <endpoint> elements have their
'streaming' attribute set.
Finally, there is a

org.mule.components.simple.StreamingBridgeComponent

component that can be used to bridge streaming endpoints.

Streaming Model with Multiple Outbound Routers


By default the Streaming model uses the InboundPassThroughRouter when no router is specified.
Unfortunantely this router does not enable the use of the OutboundRouterCollection, and in turn the
matchall or multiple endpoints are not enabled. To be able to use the Mule Streaming Model with multiple
outbound routers or with the Chaining router, you have to set the ForwardingConsumer router on the
inbound endpoint.

Use Case 2 - The Streaming Model with the Chaining Router


<model name="Model" type="streaming">
<mule-descriptor name="Test"
implementation="org.mule.components.simple.StreamingBridgeComponent">
<inbound-router>
<endpoint address="file://${mule.working.dir}/in"streaming="true">
<filterclassName="org.mule.providers.file.filters.FilenameWildcardFilter"pattern="*.txt" />
</endpoint>
<router className="org.mule.routing.inbound.ForwardingConsumer"/>
</inbound-router>
<outbound-router>
<router className="org.mule.routing.outbound.ChainingRouter">
<endpoint address="file:///temp/" streaming="true">
<properties>
<property name="outputPattern" value= "${ORIGINALNAME}-${DATE}.done"/>
</properties>
</endpoint>
<endpoint address="stream://System.out" streaming= "true"/>
</router>
</outbound-router>
</mule-descriptor>
</model>

Please notice the use of the ForwardingConsumer router set on the inbound-router.

Document generated by Confluence on Oct 27, 2008 21:07 Page 368


Suggested Reading

This page last changed on Aug 19, 2008 by jackie.wheeler.

Suggested Reading
ESB
ESB Introduction Part 1
This first article in this series described the basic concepts and role of the Enterprise Service Bus (ESB). It
focuses on describing scenarios and issues for ESB deployment to support a Service-Oriented Architecture
(SOA). One or more of these scenarios might apply to the SOA and ESB needs of your organization. - by
Rick Robinson

ESB Introduction Part 2


In Part 2 of this series on the Enterprise Service Bus (EBS), the author describes and analyzes some
commonly observed scenarios in which ESBs and other Service-Oriented Architecture (SOA) solutions are
implemented. - by Rick Robinson

ESB Introduction Part 3


In the third installment of this series, the author examines possible solutions for the various scenarios
outlined in Part 2. The ideas on the role of the Bus as explained in Part 1 provide the foundation for the
scenarios. - by Rick Robinson

The ESB Learning Guide - everything you want to know about ESB is here.

Enterprise Integration
Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions - by Gregor
Hohpe, Bobby Woolf
Provides a consistent vocabulary and visual notation framework to describe large-scale integration
solutions across many technologies. It also explores in detail the advantages and limitations of
asynchronous messaging architectures.

SEDA
SEDA
SEDA is an acronym for staged event-driven architecture, and decomposes a complex, event-driven
application into a set of stages connected by queues. This design avoids the high overhead associated
with thread-based concurrency models, and decouples event and thread scheduling from application
logic. Mule uses ideas from SEDA to provide a highly scalable server.

An Architecture for Highly Concurrent,Well-Conditioned Internet Services - (PDF) Dissertation by Matt


Welsh that introduces SEDA

JBI
The Sun JBI Site

Concurrency
Java Concurrency in Practice by Brian Goetz

Concurrent Programming in Java: Design Principles and Patterns by Doug Lea

Open Source Development Process


Producing Open Source Software: How to Run a Successful Free Software Project by Karl Fogel

Document generated by Confluence on Oct 27, 2008 21:07 Page 369


The Cathedral and the Bazaar by Eric Raymond

Quality Improvement in Volunteer Free and Open Source Software Projects: Exploring the Impact of
Release Management by Martin Michlmayr

Open Source Java


The Server Side

Document generated by Confluence on Oct 27, 2008 21:07 Page 370


Third-party Software in Mule

This page last changed on Aug 01, 2008 by jackie.wheeler.

Third-party Software
Mule products include the following third-party software as part of the source code, examples, or as
dependencies. The license type for each third-party software product is indicated in parentheses.

Software License Software License

Acegi Apache 2.0 Graphviz CPL 1.0

Antlr BSD Style GreenMail LGPL 2.1

Apache Axis Apache 2.0 Groovy Apache 2.0

Apache Axis Jaxrpc Apache2.0 Hibernate 3.2.2 LGPL 2.1

Apache Catalina Apache 2.0 Hivemind-1.1.1 Apache 2.0

Apache Cocoon Apache 2.0 Howl-logger-0.1.11 BSD


Project
Http-Client Apache 2.0
Apache Commons Apache 2.0
Attributes iHarder Base64 Public Domain/
Permissive
Apache Commons Apache 2.0
Beanutils IzPack Apache 2.0

Apache Commons Apache 2.0 Jakarta Oro Apache 1.1


Codec
Java Scripting API Sun BCLA
Apache Commons Apache 2.0
Collections Java Service Wrapper Tanuki Software/Silver
Egg Technology
Apache Commons Apache 2.0
DBUtils Java UUID Generator Apache 2.0

Apache Commons Apache 2.0 Javaassist MPL 1.1


Digester
JavaDoc for BSD Style
Apache Commons Apache 2.0 JNDI Container
Discovery Implementation

Apache Commons- Apache 2.0 Jaxen-1.1.1 BSD style


lang
JBoss Business LGPL 2.1
Apache Commons- Apache 2.0 Process Management
logging – JBPM

Apache Commons IO Apache 2.0 JBoss Transactions LGPL 2.1

Apache Commons Net Apache 2.0 JDOM BSD style license

Apache Derby Apache 2.0 Jetty 5.1.12 Apache 1.1

Apache FtpServer Apache 2.0

Document generated by Confluence on Oct 27, 2008 21:07 Page 371


Apache Geronimo Apache 2.0 JPEG Library (bundled IJG/JPEG Permissive
with GraphViz) license
Apache Jakarta Apache 2.0
Commons Transaction JUnit CPL 1.0
Source
Libpng (bundled with Libpng OSI license
Apache Maven Apache 2.0 GraphViz)

Apache Tomcat Utility Apache 2.0 Linguine Maps LGPL 2.1

Apache Xalan Apache 2.0 Log4j Apache 2.0

Apache XML Security Apache 2.0 Mockobjects Apache 2.0

Apache Velocity Apache 2.0 Mx4j 1.2 MX4J License 1.0

Apache WebServices Apache 2.0 Mx4j-tools MX4J License 1.0


Commons
Nanocontainer BSD Style
Apache Web Services Apache 2.0
Axis OGNL Attribution

Apache Web Services Apache 2.0 OpenSAML Apache 1.1


Project (Wss4j)
Picocontainer BSD
Apache Xerces Apache 2.
Quartz 1.6 Apache 2.0
Apache XML Apache 2.0
Commons XML APIs Retrotranslator BSD style

Apache Xpath Apache 2.0 Simple Logging MIT Style


Facade for Java
ASM – Bundled with BSD (SLF4J)
CGLIB
Smack Apache 2.0
Axis-Saaj Project Apache 2.0
Spring Framework / Apache 2.0
Axis/Web Services Apache 2.0 Modules JBPM

Backport-util- Creative Commons StaX Apache 2.0


concurrent Public Domain
Sun JNDI Sun BCLA
Bouncy Castle Java Bouncy Castle License
Cryptography APIs TrueType Font GPL/LGPL
Library (bundled with
c3p0: JDBC LGPL 2.1 GraphViz)
DataSources/Resource
Pools Truststore files Unknown

CAROL: Common LGPL 2.1 Web Services CPL 1.0


Architecture for Description Language
ObjectWeb for Java (wsdl4j)

Codehaus XFire Envoi Solutions Woodstox Apache 2.0


Permissive License
xapool LGPL 2.1
Commons-cli-1.0 Apache 1.1
XMLUnit BSD style
Cryptix OpenPGP
XPP3

Document generated by Confluence on Oct 27, 2008 21:07 Page 372


Cryptix General Indiana University
License Extreme! Lab
Software License
Commons-pool Apache 2.0
XStream BSD
CGLIB Apache 2.0
YourKit Java Profiler Commercial
Cryptix Cryptix General
License ZLIB (bundled with Zlib license
GraphViz)
Dom4j-1.4 BSD

DTDParser referenced Apache Style


by Linguine Maps

Expat Parser MIT

FreeType Project, FreeType License


bundled with GraphViz

Document generated by Confluence on Oct 27, 2008 21:07 Page 373


Transaction Management

This page last changed on Jul 30, 2008 by dirk.

This page is ready for review

Transaction Management
[ Single-resource Transactions ] [ XA Transactions ] [ Transaction Manager Lookup ] [ Transaction
Coordination ]

Mule's transaction framework is agnostic to the underlying transaction manager. The transaction could
be a JDBC transaction, XA transaction, or a JMS transaction or message acknowledgment. All transaction
types can be handled the same way. Mule transactions are configured on inbound endpoints, where an
endpoint can be configured to start a new transaction or join an existing one. The outbound endpoints
will automatically enlist in the current transaction, provided that the managed resource is compatible with
the transaction. Transactions are configured on an endpoint using <transaction>, which maps to the
org.mule.transaction.MuleTransactionConfig class. This element defines what action an endpoint should
take when it receives an event and the transaction factory to use to create transactions.

If you have multiple inbound or outbound endpoints in a service and you specify a
transaction for one of them, you must specify transactions for all of them. For example, if
you have two outbound endpoints and you specify a transaction for the first one, you must
also specify a transaction for the second one.

Single-resource Transactions
Single-resource transactions are transactions that are provided by the underlying resource, such as
JDBC transactions and JMS transactions. These kind of transactions can be used to receive and/or send
messages using a single resource only.

An example configuration for a single-resource transaction might look like this:

<jms:endpoint name="In" queue="test.In" connector-ref="jmsConnector1" />


<jms:endpoint name="Out" queue="test.Out" connector-ref="jmsConnector1" />
...
<inbound>
<inbound-endpoint ref="In">
<jms:transaction action="ALWAYS_BEGIN" />
</inbound>
...
<outbound>
<outbound-pass-through-router>
<outbound-endpoint ref="Out">
<jms:transaction action="ALWAYS_BEGIN" />
</outbound-endpoint>
</outbound-pass-through-router>
</outbound>

This configuration defines a global JMS endpoint that receives on a "test.In" queue and another global
JMS endpoint that sends on a "test.Out" queue. The action attribute tells Mule what to do for each
message. In this case, a new transaction will be created for every message received. The outbound
endpoint will use the resource enlisted in the current transaction, if one is running. In this case, it will use
the same JMS session that has been used to receive the event. When the message has been routed from
the inbound endpoint to the outbound endpoint, the transaction will be committed or rolled back.

You can send multiple messages using the recipient list router, which will send all messages in the same
transaction.

You can set action values on the <transaction> element as follows:

• NONE - Never participate in a transaction.

Document generated by Confluence on Oct 27, 2008 21:07 Page 374


• ALWAYS_BEGIN - Always start a new transaction when receiving a message. If a previous
transaction exists, it commits that transaction.
• BEGIN_OR_JOIN - If a transaction is already in progress when an event is received, join the
transaction, otherwise start a new transaction.
• ALWAYS_JOIN - Always expects a transaction to be in progress when an event is received. If there is
no transaction, an exception is thrown.
• JOIN_IF_POSSIBLE - Will join the current transaction if one is available. Otherwise, no transaction is
created.

XA Transactions
You can use XA transactions if you want to enlist multiple managed resources within the same
transaction. The inbound endpoints are configured in the same manner as for single-resource
transactions, but the connectors need to be configured to use XA-enabled resources.

If you run Mule outside an application server, you can use JBoss Transaction Manager to configure an
embedded transaction manager.

Currently, only three transports support XA transactions:

• VM Transport
• JDBC Transport
• JMS Transport

The following example of an XA transaction configuration uses a single transaction to read from a JMS
queue and write to a database.

<service name="JmsToJdbc">
<inbound>
<inbound-router>
<jms:inbound-endpoint queue="my.queue" reuseSession="false"/>
<xa-transaction action="ALWAYS_BEGIN" timeout="60000"/>
</jms:inbound-endpoint>
</inbound-router>
</inbound>
<outbound>
<outbound-pass-through-router>
<jdbc:outbound-endpoint address="writeTest" type="2">
<xa-transaction action="ALWAYS_JOIN"/>
</jdbc:outbound-endpoint>
</outbound-pass-through-router>
</outbound>
</service>

Because the inbound JMS endpoint has an XA transaction configured on it, any outbound endpoints must
also be configured with XA transaction support to become part of the XA transaction. This requires that
the transport type supports XA transactions. For this configuration to work, you will need to configure a
JMS connector that uses a JMS XA Connection Factory and a JDBC connector that is configured to use an
XA data source.

Transaction Manager Lookup


Mule uses javax.transaction.TransactionManager for managing transaction spanning multiple
resources (XA). If you need the SUSPEND semantics for your transactions (which is what EJB's
RequiresNew transaction attribute value does), you must use the transaction manager. Conversely,
the more typical javax.transaction.UserTransaction is just a thin handle to a transaction manager
with limited (though in most cases sufficient) functionality that does not let you suspend the current
transaction.

Note: Depending on your application server vendor, the transaction manager might be available via JNDI
or only through proprietary APIs.

The following table summarizes some common Java EE servers:

Document generated by Confluence on Oct 27, 2008 21:07 Page 375


Application Remote Embedded Common Lookup class
Server Location

JBoss java:/ org.mule.transaction.lookup.JBo


TransactionManager

Weblogic javax.transaction.TransactionManager
org.mule.transaction.lookup.We

WebSphere Proprietary API org.mule.transaction.lookup.We


call

Resin java:comp/ org.mule.transaction.lookup.Res


TransactionManager

JRun java:/ org.mule.transaction.lookup.JRu


TransactionManager

Other Specified via a org.mule.transaction.lookup.Ge


jndiName property

For example, to use Weblogic's transaction manager, you would configure Mule as follows:

<transaction-manager factory="org.mule.transaction.lookup.WeblogicTransactionManagerLookupFactory"
/>

Transaction Coordination
Transaction demarcation is set on endpoints. The actual management of transactions is handled by the
Mule Transaction Coordinator . Note that any transacted event flows will be synchronous. The Transaction
Coordinator is a singleton manager that looks after all the transactions for a Mule instance and provides
methods for binding and unbinding transaction and retrieving the current transaction state.

Document generated by Confluence on Oct 27, 2008 21:07 Page 376


Transport Service Descriptors

This page last changed on Aug 21, 2008 by jackie.wheeler.

Transport Service Descriptors


A service descriptor is a file containing properties that describes how the internals of a transport is
configured, such as which dispatcher factory to use or which endpoint builder to use. The service
descriptor file must have the same name as the protocol of the transport and must be stored in the
META-INF directory.

META-INF/services/org/mule/providers/<protocol>.properties

Following are the properties that can be set in a transport service descriptor.

Property Description Required

connector The name of the default Yes


connector class to use. This
must be an implementation of
org.mule.api.transport.Connector
.

dispatcher.factory The name of the dispatcher No (if inbound only)


factory class to use. This
must be an implementation of
org.mule.api.transport.MessageDispatcherFactory
.

requester.factory The name of the requester No


factory class to use.
org.mule.api.transport.MessageRequesterFactory
.

message.receiver The name of the message No (if inbound only)


receiver class to use. This
must be an implementation of
org.mule.api.transport.MessageReceiver
.

transacted.message.receiver The name of the message No


receiver class to use for
transacted messages. Some
transports implement a
transacted message receiver
separately, in which case the
MessageReceiver class can
be specified here so Mule
knows which receiver to use
when creating endpoints that
are transacted. This must
be an implementation of
org.mule.api.transport.MessageReceiver

xa.transacted.message.receiver If the transport supports XA No


transactions, the name of
the XA transacted message
receiver implementation to use.
Some transports implement
an XA transacted message
receiver separately, in which

Document generated by Confluence on Oct 27, 2008 21:07 Page 377


case the MessageReceiver
class can be specified here so
Mule knows which receiver to
use when creating endpoints
that are XA transacted. This
must be an implementation of
org.mule.api.transport.MessageReceiver
.

message.adapter The name of the message No (if outbound only)


adapter class to use for this
connector when receiving
messages. This must be
an implementation of
org.mule.api.transport.MessageAdapter
.

inbound.transformer The default transformer to No


use on inbound endpoints
using this transport if no
transform has been explicitly
set on the endpoint. The
property is the class name of
a transformer that implements
org.mule.api.transformer.Transformer
.

response.transformer The default transformer to use No


on inbound endpoints using
this transport if no transformer
has been explicitly set for
the response message flow
in Request/Response style
messaging. The property
is the class name of a
transformer that implements
org.mule.api.transformer.Transformer
.

outbound.transformer The default transformer to No


use on outbound endpoints
using this transport if no
transform has been explicitly
set on the endpoint. The
property is the class name of
a transformer that implements
org.mule.api.transformer.Transformer
.

endpoint.builder The class name of the Yes


endpoint builder used
to build an EndpointURI
from a URI address. Mule
provides a standard set of
endpoint builders such as
ResourceNameEndpointURIBuilder
used by JMS and VM,
SocketEndpointURIBuilder used
by TCP, HTTP, and UDP, and
UrlEndpointURIBuilder used
by SOAP. Custom endpoint
builders should extend
org.mule.endpoint.AbstractEndpointBuilder
.

Document generated by Confluence on Oct 27, 2008 21:07 Page 378


session.handler The name of the session No
handler class to use for
reading and writing session
information to and from the
current message. This must
be an implementation of
org.mule.api.transport.SessionHandler
.

Document generated by Confluence on Oct 27, 2008 21:07 Page 379


Tuning Performance

This page last changed on Oct 23, 2008 by jackie.wheeler.

Tuning Performance
About Threading Profiles | Calculating Threads | Additional Performance Tuning Tips | Threading Profile
Configuration | About Pooling Profiles | About Queue Profiles

A Mule application is a collaboration of a set of services. Messages are processed by services in three
stages:

1. Connector receiving stage


2. Service component processing stage
3. Connector dispatching stage

Tuning performance in Mule involves analyzing and improving these three stages for each service. You
can start by applying the same tuning approach to all services and then further customize the tuning for
each service as needed.

Messaging Styles
Mule can send messages asynchronously or synchronously. By default, Mule uses the SEDA model, which
is asynchronous. Asynchronous is the "fire-and-forget" style, where a message is sent with no response.
If you need a response back, you must configure the Mule service as synchronous. When a service is
configured as asynchronous, a connector receiver and dispatcher are used, whereas a synchronous
service uses only the connector receiver.

About Thread Pools


Each request that comes into Mule is processed on its own thread. A connector's receiver has a thread
pool with a certain number of threads available to process requests on the inbound endpoints that use
that connector.

If you are using synchronous processing, the same thread will be used to carry the message all the way
through Mule, whereas if you are doing asynchronous processing, the receiver thread is used only to
carry the message to the component, at which point the message is transferred to a component thread,
and the receiver thread is released back into the receiver thread pool so it can carry another message.
Finally, the component transfers the asynchronous message to a dispatcher thread where it is sent on its
way.

In summary, the receiver, component, and dispatcher all have separate thread pools that are in use
during asynchronous processing, whereas only the receiver thread pool is in use for synchronous
processing. The exception to this rule is the rare case when your component does explicit dispatching, in
which case the dispatcher thread is used even for synchronous requests.

Document generated by Confluence on Oct 27, 2008 21:07 Page 380


Configuring Threading Profiles
The threading profile specifies how the thread pools behave in Mule. You specify a separate threading
profile for each receiver thread pool, component thread pool, and dispatcher thread pool. The most
important setting of each is maxThreadsActive, which specifies how many threads are in the thread
pool. Mule also tries to keep a core pool size, which is the result of subtracting maxThreadsIdle from
maxThreadsActive. Mule also maintains a work queue to hold submitted tasks when all the core threads
are running. The queue's size is defined by maxBufferSize. When the queue is full and a new task is
submitted, a new thread will be constructed unless this would exceed maxThreadsActive, in which case,
the new task will be rejected by Mule.

Calculating Threads
To calculate the number of threads to set, you must take the following factors into consideration.
Concurrent User Requests
In general, the number of concurrent user requests is the total number of requests to be processed
simultaneously at any one time by the Mule server. For a service, concurrent user requests is the number
of requests a service inbound endpoint can process simultaneously. Concurrent user requests at the
connector level is the total concurrent requests of all services who share the same connector.

Processing Time
Processing time is the average time Mule takes to process a user request from the time a connector
receiver starts the execution until it finishes and then sends the response to the outbound endpoint by
connector dispatcher or back to the caller by connector receiver after a round trip.

Response Time
In a thread pooling environment, when a request arrives, there is no guarantee that a thread will be
immediately available. In this case, the request is put into an internal thread pool work queue to wait for
the next available thread.

If a service runs in synchronous mode, the response time is the amount of time the end user is required
to actually wait for the response to come back. If the service runs in asynchronous mode, it is the
total time from when a request arrives in Mule until it is dispatched out of the service by the outbound
dispatcher. The formula for response time is the following:

Response time = average of thread pool waiting time in work queue + average of processing time

Usually, processing time data is generated from the unit test, whereas concurrent user requests and
response times come directly from business requirements.

To calculate how many threads you should assign to the receiver thread pool, multiply the required
number of simultaneous requests by the number of components that use that connector for their inbound
endpoints. For example, if you have three components whose inbound endpoints use a connector,

Document generated by Confluence on Oct 27, 2008 21:07 Page 381


and your business requirements dictate that you should be able to process 50 requests at a time, set
maxThreadsActive to 150 in the receiver threading profile for that connector.

If you have requirements for timeout settings for synchronous processing, you need to do some
additional calculations for the receiver thread pool.

1. Calculate the required simultaneous requests multiplied by the components as described above.
2. Figure out how long each round trip request takes by running some test cases with synchronous
requests.
3. Subtract the round-trip time from the timeout setting dictated by your business requirements. This
is your maximum wait time.
4. Divide the maximum wait time by the round-trip time to get the batch time.
5. Divide the required simultaneous requests by the batch time to get the thread size for
maxThreadsActive.
6. Set maxBufferSize to the required simultaneous requests minus the maxThreadsActive setting.

For example, if you require the ability to process 200 requests simultaneously, and your timeout setting
is 10 seconds, and a request takes 2 seconds, your maximum wait time is 8 seconds (10 seconds
timeout minus round-trip time). Divide the maximum wait time (8 seconds) by the round-trip time (2
seconds) to get your batch time (4 seconds per batch). Finally, divide your requests requirement (200
requests) by the batch time (4 seconds) to get the maxThreadsActive setting (50) for the receiver
thread pool. Subtract this same number (50) from the required simultaneous requests (200) to get your
maxBufferSize (150).

After you have calculated your receiver threads, look at how many components use synchronous
processing and asynchronous. If most do asynchronous process, apply the same number to the
component thread pool and dispatcher thread pool. If you do mostly synchronous process, these numbers
can be much lower. When you configure your component thread pool, be sure to set the the component
pool at the same time as described in "About Pooling Profiles" below.

Additional Performance Tuning Tips


• In the log4j.properties file in your conf directory, set up logging to a file instead of the console,
which will bypass the wrapper logging and speed up performance. To do this, create a new file
appender (org.apache.log4j.FileAppender), specify the file and optionally the layout and other
settings, and then change "console" to the file appender. For example:

log4j.rootCategory=INFO, mulelogfile

log4j.appender.mulelogfile=org.apache.log4j.FileAppender
log4j.appender.mulelogfile.layout=org.apache.log4j.PatternLayout
log4j.appender.mulelogfile.layout.ConversionPattern=%-22d{dd/MMM/yyyy HH:mm:ss} - %m%n
log4j.appender.mulelogfile.file=custommule.log
• If polling is enabled for a connector, one thread will be in use by polling, so you should increment
your maxThreadsActive setting by one. Polling is available on connectors such as File, FTP, and
STDIO that extend AbstractPollingMessageReceiver .
• If you are using VM to pass a message between components, you can typically reduce the total
number of threads because VM is so fast.
• If you are processing very heavy loads, or if your endpoints have different simultaneous request
requirements (for example, one endpoint requires the ability to process 20 simultaneous requests
but another endpoint using the same connector requires 50), you might want to split up the
connector so that you have one connector per endpoint.

Thread pools in Mule use the JDK 1.4-compatible util.concurrent backport library, so all
the variables defined on org.mule.config.ThreadingProfile are synonymous with
ThreadPoolExecutor.

Threading Profile Configuration Reference


Following are the elements you configure for threading profiles. You can create a threading profile at the
<configuration>, <connector>, or <service> level and reference it.

Document generated by Confluence on Oct 27, 2008 21:07 Page 382


Receiver Threading Profile

Attributes of <receiver-threading-profile...>

Name Type Required Default Description

maxThreadsActive integer no The maximum


number of threads
that will be used.

maxThreadsIdle integer no The maximum


number of idle or
inactive threads
that can be in the
pool before they
are destroyed.

threadTTL integer no Detemines how


long an inactive
thread is kept in
the pool before
being discarded.

poolExhaustedAction WAIT/DISCARD/ no When the


DISCARD_OLDEST/ maximum pool
ABORT/RUN size or queue size
is bounded, this
value determines
how to handle
incoming tasks.
Possible values
are: WAIT
(wait until a
thread becomes
available. This
policy should,
in general, not
be used if the
minimum number
of threads is zero,
in which case
a thread may
never become
available.),
DISCARD
(throw away the
current request
and return),
DISCARD_OLDEST
(throw away the
oldest request
and return),
ABORT (throw a
RuntimeException),
and RUN (the
thread making
the execute
request runs the
task itself. This
policy helps guard
against lockup.)

Document generated by Confluence on Oct 27, 2008 21:07 Page 383


threadWaitTimeout integer no How long to wait
in milliseconds
when the pool
exhausted
action is WAIT.
If the value is
negative, it will
wait indefinitely.

doThreading boolean no true Whether threading


should be used
(default is true).

maxBufferSize integer no Determines how


many requests
are queued when
the pool is at
maximum usage
capacity and the
pool exhausted
action is WAIT.
The buffer is used
as an overflow.

Component Threading Profile


The threading profile to use on the component.

Attributes of <component-threading-profile...>

Name Type Required Default Description

maxThreadsActive integer no The maximum


number of threads
that will be used.

maxThreadsIdle integer no The maximum


number of idle or
inactive threads
that can be in the
pool before they
are destroyed.

threadTTL integer no Detemines how


long an inactive
thread is kept in
the pool before
being discarded.

poolExhaustedAction WAIT/DISCARD/ no When the


DISCARD_OLDEST/ maximum pool
ABORT/RUN size or queue size
is bounded, this
value determines
how to handle
incoming tasks.
Possible values
are: WAIT
(wait until a
thread becomes

Document generated by Confluence on Oct 27, 2008 21:07 Page 384


available. This
policy should,
in general, not
be used if the
minimum number
of threads is zero,
in which case
a thread may
never become
available.),
DISCARD
(throw away the
current request
and return),
DISCARD_OLDEST
(throw away the
oldest request
and return),
ABORT (throw a
RuntimeException),
and RUN (the
thread making
the execute
request runs the
task itself. This
policy helps guard
against lockup.)

threadWaitTimeout integer no How long to wait


in milliseconds
when the pool
exhausted
action is WAIT.
If the value is
negative, it will
wait indefinitely.

doThreading boolean no true Whether threading


should be used
(default is true).

maxBufferSize integer no Determines how


many requests
are queued when
the pool is at
maximum usage
capacity and the
pool exhausted
action is WAIT.
The buffer is used
as an overflow.

Dispatcher Threading Profile

Attributes of <dispatcher-threading-profile...>

Name Type Required Default Description

maxThreadsActive integer no The maximum


number of threads
that will be used.

Document generated by Confluence on Oct 27, 2008 21:07 Page 385


maxThreadsIdle integer no The maximum
number of idle or
inactive threads
that can be in the
pool before they
are destroyed.

threadTTL integer no Detemines how


long an inactive
thread is kept in
the pool before
being discarded.

poolExhaustedAction WAIT/DISCARD/ no When the


DISCARD_OLDEST/ maximum pool
ABORT/RUN size or queue size
is bounded, this
value determines
how to handle
incoming tasks.
Possible values
are: WAIT
(wait until a
thread becomes
available. This
policy should,
in general, not
be used if the
minimum number
of threads is zero,
in which case
a thread may
never become
available.),
DISCARD
(throw away the
current request
and return),
DISCARD_OLDEST
(throw away the
oldest request
and return),
ABORT (throw a
RuntimeException),
and RUN (the
thread making
the execute
request runs the
task itself. This
policy helps guard
against lockup.)

threadWaitTimeout integer no How long to wait


in milliseconds
when the pool
exhausted
action is WAIT.
If the value is
negative, it will
wait indefinitely.

Document generated by Confluence on Oct 27, 2008 21:07 Page 386


doThreading boolean no true Whether threading
should be used
(default is true).

maxBufferSize integer no Determines how


many requests
are queued when
the pool is at
maximum usage
capacity and the
pool exhausted
action is WAIT.
The buffer is used
as an overflow.

Configuring Pooling Profiles


Each pooled component (see PooledJavaComponent ) has a component pool, which contains multiple
instances of the component to handle simultaneous incoming requests. The pooling profile configures
the component pool. The most important setting is maxActive, which specifies the maximum number
of instances of the component Mule will create to handle simultaneous requests. Note that this number
should be the same as the maxThreadsActive setting on the thread pool so that you have enough
component instances available to handle the threads. You can use Mule HQ to monitor your component
pools and see the maximum number of components you've used from the pool to help you tune the
number of components and threads.

Each service has its own pooling profile. You configure the pooling profile using the <pooling-profile>
element on the <pooled-component> element.

Pooling Profile

Attributes of <pooling-profile...>

Name Type Required Default Description

maxActive string no Controls the


maximum
number of Mule
components that
can be borrowed
from a session
at one time.
When set to a
negative value,
there is no limit
to the number of
components that
may be active at
one time. When
maxActive is
exceeded, the
pool is said to be
exhausted.

maxIdle string no Controls the


maximum
number of Mule
components that

Document generated by Confluence on Oct 27, 2008 21:07 Page 387


can sit idle in the
pool at any time.
When set to a
negative value,
there is no limit
to the number of
Mule components
that may be idle
at one time.

initialisationPolicy INITIALISE_NONE/ no INITIALISE_ONE Determines how


INITIALISE_ONE/ components in
INITIALISE_ALL a pool should
be initialized.
The possible
values are:
INITIALISE_NONE
(will not load
any components
into the pool
on startup),
INITIALISE_ONE
(will load one
initial component
into the pool
on startup), or
INITIALISE_ALL
(will load all
components in the
pool on startup)

exhaustedAction WHEN_EXHAUSTED_GROW/
no WHEN_EXHAUSTED_GROW
Specifies the
WHEN_EXHAUSTED_WAIT/ behavior of the
WHEN_EXHAUSTED_FAIL Mule component
pool when the
pool is exhausted.
Possible
values are:
"WHEN_EXHAUSTED_FAIL",
which will throw a
NoSuchElementException,
"WHEN_EXHAUSTED_WAIT",
which will
block (invoke
Object.wait(long))
until a new or
idle object is
available, or
WHEN_EXHAUSTED_GROW,
which will create
a new Mule
and return
it, essentially
making maxActive
meaningless. If a
positive maxWait
value is supplied,
it will block for at
most that many
milliseconds,
after which a
NoSuchElementException
will be thrown. If
maxThreadWait

Document generated by Confluence on Oct 27, 2008 21:07 Page 388


is a negative
value, it will block
indefinitely.

maxWait string no Specifies the


number of
milliseconds to
wait for a pooled
component to
become available
when the pool is
exhausted and the
exhaustedAction
is set to
WHEN_EXHAUSTED_BLOCK.

Configuring Queue Profiles


When requests come in to a SEDA service (the default model type), they are stored on a queue until
threads from the component thread pool can pick them up and process them. The queue profile specifies
how this queue behaves. Typically, you do not need to configure the queue profile for performance, as the
endpoints and not the queue are the usual bottleneck. However, you can specify that you want the queue
to be persistent if you want to store a copy of all messages processed by the component.

If required, you can write your own persistence strategy to write to a database or some other store.
Persistence strategies must implement QueuePersistenceStrategy .

You configure the queue profile using the <queue-profile> element on the model. Note that you can use
Mule HQ to monitor your queues and see historically how many messages it has contained.

Queue Profile
A Queue Profile is used to describe the properties of an internal Mule queue. Internal queues are used to
queue events for each component managed by Mule.

Attributes of <queue-profile...>

Name Type Required Default Description

maxOutstandingMessages
integer no Defines the
maximum number
of messages that
can be queued.

persistent boolean no false Whether Mule


messages are
persisted to a
store. Primarily,
this is used for
persisting queued
messages to
disk so that the
internal state
of the server is
mirrored on disk
in case the server
fails and needs
to be restarted.
Default is false.

Document generated by Confluence on Oct 27, 2008 21:07 Page 389


Unit Testing

This page last changed on Jul 22, 2008 by jackie.wheeler.

Unit Testing
Mule provides a Test Compatibility Kit (TCK) of unit tests that you can use to test your simple
extensions as well as your custom modules and transports. The unit tests are located in the -
tests.jar file, such as mule-core-2.0.2-tests.jar for Mule version 2.0.2. All unit tests inherit from
org.mule.tck.AbstractMuleTestCase .

These unit tests are beneficial for the following reasons:

• Components tested with a TCK test case ensure that the common behavior of the component is
compatible with the Mule framework.
• Using a TCK test case allows the developer to concentrate on writing tests for specific behavior of
their component.
• Where testing of a method in the Service Component API cannot be tested by the TCK test case,
the test cases provides an abstract method for the test, ensuring the developer tests all areas of the
component.
• The TCK provides a default test model that is a simple set of test classes. The developer doesn't
need to worry about writing new test classes for their test cases each time.
• The abstract test cases in the TCK use JUnit's TestCase, so they are compatible with other test
cases.

Following is a description of some of the unit tests in the Mule TCK:

Testing Component Description

AbstractMuleTestCase A helper test case providing methods for creating


test and mock object types. This is the base class
for all other abstract TCK classes.

AbstractConnectorTestCase Used to test the common behavior of a connector.


This tests dispatching and sending events using
mock objects.

AbstractMessageAdapterTestCase Provides tests for all the standard methods


defined in the MessageAdapter interface. It's
usually enough to just extend this test case
without writing any further tests.

AbstractMessageReceiverTestCase Used to test the common behavior of a


MessageReceiver. This tests receiving messages
using mock objects.

AbstractComponentTestCase This is the base class for unit tests that


test custom component implementations.
Concrete subclasses of this base class
include DefaultJavaComponentTestCase,
PooledJavaComponentTestCase, and
SimpleCallableJavaComponentTestCase,
each of which contains methods for testing
that component type. For example, the
DefaultJavaComponentTestCase includes
methods for testing the creation, lifecycle, and
disposal of a basic Java component.

AbstractTransformerTestCase Used to test transformers. This class defines


a number of tests that ensures that the
transformer works in single scenarios as well
as in round trip scenarios. There are many
concrete sub-classes of this abstract class that

Document generated by Confluence on Oct 27, 2008 21:07 Page 390


test specific types of transformers, such as
StringByteArrayTransformersTestCase.

DefaultMuleContextTestCase Tests the creation and disposal of the Mule


context.

AbstractServiceTestCase An abstract test case that provides methods for


testing the starting, stopping, pausing, resuming,
and disposing of services.

Document generated by Confluence on Oct 27, 2008 21:07 Page 391


Using IDEs

This page last changed on Jul 02, 2008 by jackie.wheeler.

Using IDEs
You can use an integrated development environment (IDE) such as Eclipse, IntelliJ, and Mule IDE to
rapidly develop Mule applications. For more information on the Mule IDE, see the Mule IDE User Guide.

Usually, you simply attach the src.zip file that comes with the Mule distribution to the Mule JARs in your
project so you can browse the source code while developing your classes. If you want to build Mule from
source, see the following topics in the Mule Developer's Guide:

• Setting Up the Development Environment


• Working with an IDE
• Building from Source

Document generated by Confluence on Oct 27, 2008 21:07 Page 392


Using JMS with Mule

This page last changed on Aug 27, 2008 by jackie.wheeler.

Using JMS with Mule


This page is under construction

The following topics describe how to use JMS with Mule.

Configuring JMS - A guide for configuring various JMS servers with Mule, including ActiveMQ, JBoss MQ,
Joram OpenJms, Oracle AQ, SeeBeyond, Sun JMS Grid, UberMQ, Weblogic JMS, and IBM WebSphere MQ.

JMS Transport - How to configure the Mule JMS transport.

Transaction Management - Managing JMS Local and distributed (XA) transactions.

Examples
Error Handler Example and Loan Broker Example - Demonstrate using the Active MQ connector and
various JMS transformers.

Using JMS Redelivery - How to configure Jms Redelivery in Mule (Mule 1.x).

Configuring Multiple JMS Clients - How to configure more than one JMS connection in a single Mule
instance (Mule 1.x).

Configuring a Component Exception Queue - configuring a JMS error queue for your components (Mule
1.x).

JMS Provider Bridging - Moving JMS messages between JMS servers from different vendors (Mule 1.x).

Document generated by Confluence on Oct 27, 2008 21:07 Page 393


Configuring JMS

This page last changed on Oct 21, 2008 by jackie.wheeler.

Configuring JMS
The following links describe how to set up various JMS Servers in Mule. For general configuration
information, see JMS Transport. Note that the configurations provided are just examples. Configuration
values will change depending on your application environment.

• ActiveMQ
• FioranoMQ
• JBoss MQ
• OpenJms
• Oracle AQ
• SeeBeyond
• SonicMQ
• Sun JMS Grid
• SwiftMQ
• Tibco EMS
• WebLogic JMS
• WebSphere MQ

JMS Endpoint URIs and JNDI destinations


Some JNDI implementations treat dot (.) and forward slash symbols differently in destination names, so
jms://order/incoming might not be the same as jms://order.incoming. The former will not give you
the order/incoming destination but incoming. If you are dealing with such a server (JBoss is known to
behave this way), here is a trick to help you:

jms:////order/incoming

For topics, add the standard prefix, so it takes the following form:

jms:////topic:order/incoming

Note: If using JBoss, remember to omit the queue/ and topic/ from the full JNDI name.

See Mule Endpoint URIs for reference.

Document generated by Confluence on Oct 27, 2008 21:07 Page 394


ActiveMQ Integration

This page last changed on Oct 21, 2008 by jackie.wheeler.

ActiveMQ Integration
You can integrate Mule with Apache ActiveMQ. To configure a default embedded broker, you use the
<activemq-connector> or <activemq-xa-connector> (for transaction support) element in your Mule
configuration. These connectors take all the same attributes and elements as the JMS connector with the
additional attribute brokerURL.

<?xml version="1.0" encoding="UTF-8" ?>


<mule xmlns="http://www.mulesource.org/schema/mule/core/2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mule="http://www.mulesource.org/schema/mule/core/2.0"
xmlns:jms="http://www.mulesource.org/schema/mule/jms/2.0"
xmlns:test="http://www.mulesource.org/schema/mule/test/2.0"
xsi:schemaLocation="http://www.mulesource.org/schema/mule/test/2.0
http://www.mulesource.org/schema/mule/test/2.0/mule-test.xsd
http://www.mulesource.org/schema/mule/core/2.0
http://www.mulesource.org/schema/mule/core/2.0/mule.xsd
http://www.mulesource.org/schema/mule/jms/2.0
http://www.mulesource.org/schema/mule/jms/2.0/mule-jms.xsd">

<jms:activemq-connector name="jmsConnector" specification="1.1" brokerURL="vm://localhost"


connectionFactory-ref="activeMqConnectionFactory"/>

<--! or use the XA connector to support transactions -->


<jms:activemq-xa-connector name="xaConnector" maxRedelivery="1">
<dispatcher-threading-profile doThreading="false" />
</jms:activemq-xa-connector>
...

The specification attribute tells Mule to use the JMS 1.1 specification, which is the specification
ActiveMQ supports. The connectionFactory-ref attribute specifies a set of connection factory properties
you define in your Spring configuration.

activemq-spring.xml

<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/
schema/beans/spring-beans-2.5.xsd">

<bean id="activeMqConnectionFactory" class="org.activemq.ActiveMQConnectionFactory">


<property name="brokerXmlConfig"
value="classpath:/org/mule/test/activemq-config.xml"/>
<!-- More properties you want set on ActiveMQConnectionFactory -->
</bean>
</beans>

Your ActiveMQ configuration file uses standard settings. For example, to use in-JVM messaging without
persistent queues (very useful for testing), the file might look like this:

activemq-config.xml

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE beans PUBLIC "-//ACTIVEMQ//DTD//EN" "http://activemq.org/dtd/activemq.dtd">

<beans>
<broker>
<connector>
<serverTransport uri="vm://localhost"/>
</connector>

Document generated by Confluence on Oct 27, 2008 21:07 Page 395


<persistence>
<vmPersistence/>
</persistence>
</broker>
</beans>

Document generated by Confluence on Oct 27, 2008 21:07 Page 396


Fiorano Integration

This page last changed on Oct 21, 2008 by jackie.wheeler.

Configuring the JMS Connector for FioranoMQ


2007
FioranoMQ is a High Performance Enterprise Communication Backbone.

<jms:connector name="FioranoJMSConnector"
connectionFactoryJndiName="PrimaryCF"
jndiInitialFactory="fiorano.jms.runtime.naming.FioranoInitialContextFactory"
specification="1.1"
jndiProviderUrl="http://localhost:1856"
username="anonymous"
password="anonymous">

<!-- A few optional values for the factory -->


<spring:property key="connectionFactoryProperties">
<spring:map>
<spring:entry key="clientID" value="sampleClientID"/>
<spring:entry key="ConnectURL" value="http://localhost:1856"/>
<spring:entry key="BackupConnectURLs" value="http://localhost:1956"/>
</spring:map>
</spring:property>
</jms:connector>

You will need the following jars on your classpath:

• FioranoMQ2007/fmq/lib/client/all/fmq-client.jar
• FioranoMQ2007/framework/lib/all/fiorano-framework.jar

Sample Usage
The following steps illustrate modifying the "Echo" sample shipped with Mule. Instead of using
System.out in the outbound router, we will write the output onto a Topic in FioranoMQ using the above
configuration.

Modify the outbound router in the echo-config.xml under examples\echo\conf to use a Topic:

<jms:outbound-endpoint topic="muleTopic"/>

Start the durable connection sample available in FioranoMQ from a command prompt in fmq/samples/
PubSub/DurableSubscribers as shown below:

runClient DurableSubscriber -clientid sampleClientID -topicName muleTopic

Now on starting Mule with the above echo-config.xml file we can push messages onto the topic and
consequently to the subscriber.
The durable connection property can also be tested by killing the subscriber, pumping in more messages
and then again starting the subscriber.

Document generated by Confluence on Oct 27, 2008 21:07 Page 397


Integrating SwiftMQ with Mule

This page last changed on Oct 21, 2008 by jackie.wheeler.

Integrating SwiftMQ with Mule


This page describes how to use SwiftMQ with Mule.

Configuring a Mule JMS Connector


The best approach for integrating SwiftMQ is via JNDI. You will specify the following attributes:

Attribute Description Recommended Value

jndiInitialFactory InitialContext factory com.swiftmq.jndi.InitialContextFactoryImpl

jndiProviderUrl JNDI Provider URL smqp://localhost:4001/


timeout=10000

jndiDestinations JNDI lookup of queues/topics true

forceJndiDestinations Forces a JNDI exception if a true


destination was not found in
JNDI

specification Version of the JMS specification 1.1

connectionFactoryJndiName Name of the JMS connection ConnectionFactory


factory to use

Example:

<jms:connector name="jmsConnector"
connectionFactoryJndiName="ConnectionFactory"
jndiDestinations="true"
forceJndiDestinations="true"
jndiInitialFactory="com.swiftmq.jndi.InitialContextFactoryImpl"
jndiProviderUrl="smqp://localhost:4001/timeout=10000"
specification="1.1"/>

After you have configured the connector, copy swiftmq.jar into the Mule lib/user directory and start
the SwiftMQ Router. You can now use SwiftMQ from Mule.

Configuring the Loan Broker ESB Example with SwiftMQ


The following example shows you how to modify the Loan Broker ESB example to use SwiftMQ. The only
change necessary is to modify the JMS connector in both example configuration files. With a SwiftMQ
Router running on the local host, the connector would look like this:

<jms:connector name="jmsConnector"
connectionFactoryJndiName="ConnectionFactory"
jndiDestinations="true"
forceJndiDestinations="true"
jndiInitialFactory="com.swiftmq.jndi.InitialContextFactoryImpl"
jndiProviderUrl="smqp://localhost:4001/timeout=10000"
specification="1.1"/>

The Loan Broker ESB example uses the following JMS queues (Mule syntax):

Document generated by Confluence on Oct 27, 2008 21:07 Page 398


jms://esb.loan.quotes
jms://esb.credit.agency
jms://esb.lender.service
jms://esb.banks

SwiftMQ does not allow dots '.' in queue names. Instead, use underscores '_' in SwiftMQ's
routerconfig.xml:

<swiftlet name="sys$queuemanager">
<queue-controllers>
<queue-controller name="01" persistence-mode="non_persistent" predicate="tmp$%"/>
<queue-controller name="02" predicate="sys$%"/>
<queue-controller name="03" predicate="swiftmq%"/>
<queue-controller name="04" predicate="rt$%"/>
<queue-controller name="05" predicate="unroutable"/>
<queue-controller name="06" predicate="%$%"/>
<queue-controller name="07" predicate="%"/>
</queue-controllers>
<queues>
<queue name="esb_banks"/>
<queue name="esb_credit_agency"/>
<queue name="esb_lender_service"/>
<queue name="esb_loan_quotes"/>
</queues>
</swiftlet>

To match with the Loan Broker ESB example's JMS queue names, define JNDI aliases in SwiftMQ's
routerconfig.xml:

<swiftlet name="sys$jndi">
<aliases>
<alias name="esb.banks" map-to="esb_banks@router1"/>
<alias name="esb.credit.agency" map-to="esb_credit_agency@router1"/>
<alias name="esb.lender.service" map-to="esb_lender_service@router1"/>
<alias name="esb.loan.quotes" map-to="esb_loan_quotes@router1"/>
</aliases>
<jndi-replications/>
<remote-queues/>
</swiftlet>

You now rebuild the Loan Broker ESB example with Ant or Maven so that the configuration changes can
take effect, then start the SwiftMQ Router and the Loan Broker ESB example.

Note that the @ sign can be escaped with %40 in the Mule URI, so for an alternate configuration you can
use the following:

<endpoint name="LoanBrokerRequestsREST" address="jetty:rest://localhost:8080/loanbroker"/>


<vm:endpoint name="LoanBrokerRequests" path="loan.broker.requests"/>
<jms:endpoint name="LoanQuotes" address="jms://esb_loan_quotes%40router1"/>
<jms:endpoint name="CreditAgencyGateway" address="jms://esb_credit_agency%40router1"/>
<!-- here we're telling Mule to invoke a remote Ejb directly (not host a
proxy service for the remote object as with the other example in mule-config-with-ejb-container.xml
example)
-->
<ejb:endpoint name="CreditAgency" host="localhost" port="1099" object="local/CreditAgency"
method="getCreditProfile" />
<!-- endpoint name="CreditAgency" address="ejb://localhost:1099/local/CreditAgency?
method=getCreditProfile" / -->
<endpoint name="LenderGateway" address="jms://esb.lender.service" />
<endpoint name="LenderService" address="vm://lender.service" />
<endpoint name="BankingGateway" address="jms://esb.banks%40router1" />
<endpoint name="Bank1" address="axis:http://localhost:10080/mule/TheBank1?method=getLoanQuote"
synchronous="true" />
<endpoint name="Bank2" address="axis:http://localhost:20080/mule/TheBank2?method=getLoanQuote"

Document generated by Confluence on Oct 27, 2008 21:07 Page 399


synchronous="true" />
<endpoint name="Bank3" address="axis:http://localhost:30080/mule/TheBank3?method=getLoanQuote"
synchronous="true" />
<endpoint name="Bank4" address="axis:http://localhost:40080/mule/TheBank4?method=getLoanQuote"
synchronous="true" />
<endpoint name="Bank5" address="axis:http://localhost:50080/mule/TheBank5?method=getLoanQuote"
synchronous="true" />

Keep in mind that a SwiftMQ JNDI alias also decouples a queue from its physical location. You can move
a queue to another router without affecting clients. So it's always best practice to avoid physical queue
names.

Document generated by Confluence on Oct 27, 2008 21:07 Page 400


JBoss Jms Integration

This page last changed on Oct 21, 2008 by jackie.wheeler.

JBoss JMS Integration


You configure a JBoss JMS connector for Mule as follows:

<?xml version="1.0" encoding="UTF-8"?>


<mule xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns="http://www.mulesource.org/schema/mule/core/2.0"
xmlns:jms="http://www.mulesource.org/schema/mule/jms/2.0"
...
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-2.5.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-
util-2.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-
jee-2.0.xsd
http://www.mulesource.org/schema/mule/core/2.0 http://www.mulesource.org/schema/mule/core/2.0/
mule.xsd
http://www.mulesource.org/schema/mule/jms/2.0 http://www.mulesource.org/schema/mule/jms/2.0/mule-
jms.xsd
...>

<spring:beans>
<util:properties id="jndiEnv">
<spring:prop key="java.naming.factory.initial">org.jnp.interfaces.NamingContextFactory</
spring:prop>
<spring:prop key="java.naming.provider.url">jnp://localhost:1099/</spring:prop>
</util:properties>
<jee:jndi-lookup id="connectionFactory" jndi-name="java:/ConnectionFactory" environment-
ref="jndiEnv"/>
</spring:beans>

<jms:connector name="jmsConnector" connectionFactory-ref="connectionFactory"/>

The JNDI provider and JBoss properties are specified in Spring.

If you use user credentials to connect to JBoss MQ, make sure that the user has the 'guest'
role assigned to it. This will ensure that there are no issues if Temporary Topics or Queues
(e.g., in RemoteSync calls) are used.

Document generated by Confluence on Oct 27, 2008 21:07 Page 401


OpenJms Integration

This page last changed on Oct 21, 2008 by jackie.wheeler.

OpenJMS Integration
The following example configuration describes how to configure a Mule JMS connector for OpenJMS.
You will probably need to change the connectionFactoryJndiName to one that is configured from your
OpenJMS configuration.

<jms:connector name="jmsConnector"
jndiInitialFactory="org.exolab.jms.jndi.InitialContextFactory"
jndiProviderUrl="tcp://localhost:3035"
connectionFactoryJndiName="QueueConnectionFactory"/>

Document generated by Confluence on Oct 27, 2008 21:07 Page 402


SeeBeyond JMS Server Integration

This page last changed on Oct 22, 2008 by jackie.wheeler.

SeeBeyond JMS Server Integration


The following configuration is for the SeeBeyond ICAN IQManager JMS Server. Note the values in [ ]
(square brackets), which should be replaced by values relevant to your installation. Port 18006 is the
default, which you can change in the SeeBeyond designer.

<jms:connector name="jmsConnector"
jndiInitialFactory="com.stc.is.naming.NamingContextFactory"
jndiProviderUrl="[ServerName]:18006"
connectionFactoryJndiName="/jms/connectionfactory/queue/[LogicalHostName]_[JMS iqManager Name]"/>
</jms:connector>

For a topic, the connectionFactoryJndiName would be /jms/connectionfactory/topic/


[LogicalHostName]_[JMS iqManager Name].

You will need the following files from the Java API Kit on your classpath:

• com.stc.jmsis.jar
• fscontext.jar
• providerutil.jar
• jms.jar
• jta.jar
• log4j.jar
• log4j.properties

Document generated by Confluence on Oct 27, 2008 21:07 Page 403


SonicMQ Integration

This page last changed on Oct 21, 2008 by jackie.wheeler.

SonicMQ Integration
The following configuration was tested with versions 6.1 and 7.0 of SonicMQ.

<jms:connector name="jmsSonicMQConnector"
jndiInitialFactory="com.sonicsw.jndi.mfcontext.MFContextFactory"
specification="1.1"
connectionFactoryJndiName="sonic-cf"
jndiProviderUrl="tcp://localhost:2506"
username="Administrator"
password="Administrator">

<spring:property key="connectionFactoryProperties">
<spring:map>
<spring:entry key="clientID" value="clientIDString"/>
<spring:entry key="connectID" value="connectIDString"/>
<spring:entry key="connectionURLs" value="somURLStrings here"/>
<spring:entry key="defaultUser" value="userString"/>
<spring:entry key="defaultPassword" value="passwordString"/>
<spring:entry key="prefetchCount" value="10"/>
<spring:entry key="prefetchThreshold" value="10"/>
<spring:entry key="faultTolerant" value="true"/>
<spring:entry key="persistentDelivery" value="true"/>
<spring:entry key="loadBalancing" value="true"/>
<spring:entry key="sequential" value="false"/>
</spring:map>
</spring:property>

<spring:property key="jndiProviderProperties">
<spring:map>
<spring:entry key="com.sonicsw.jndi.mfcontext.domain" value="Domain1"/>
<spring:entry key="java.naming.security.principal" value="Administrator"/>
<spring:entry key="java.naming.security.credentials" value="Administrator"/>
<!-- optional, default is 30sec -->
<spring:entry key="com.sonicsw.jndi.mfcontext.idleTimeout" value="5000"/>
</spring:map>
</spring:property>

</jms:connector>

Document generated by Confluence on Oct 27, 2008 21:07 Page 404


Sun JMS Grid Integration

This page last changed on Oct 22, 2008 by jackie.wheeler.

Sun JMS Grid Integration


The following configuration demonstrates how to configure Mule to use the Sun JMS Grid server.

<jms:connector name="jmsConnector" specification="1.1"


connectionFactoryJndiName="QueueConnectionFactory"
jndiInitialFactory="com.spirit.directory.SpiritVMDirectoryContextFactory"
<spring:property name="jndiProviderProperties">
<spring:map>
<spring:entry key="driverName" value="WMSEmbedded"/>
</spring:map>
</spring:property>
</jms:connector>

Document generated by Confluence on Oct 27, 2008 21:07 Page 405


Tibco EMS Integration

This page last changed on Oct 21, 2008 by jackie.wheeler.

TIBCO EMS Integration


This page demonstrates how to configure Mule to use the TIBCO Enterprise Message Server (EMS) with
authentication in place.

<jms:connector name="jmsConnector"
jndiProviderUrl="tibjmsnaming://host:port"
connectionFactoryJndiName="QueueConnectionFactory"
username="username"
password="password"
jndiDestinations="true"
forceJndiDestinations="true"
jndiInitialFactory="com.tibco.tibjms.naming.TibjmsInitialContextFactory"
specification="1.1">
<spring:property name="jndiProviderProperties">
<spring:map>
<spring:entry key="java.naming.security.principal" value="jndiUsername"/>
<spring:entry key="java.naming.security.credentials" value="jndiPassword"/>
</spring:map>
</spring:property>
</jms:connector>

For XA transactions, you must create an XA Connection Factory from the TIBCO administration-tool
(tibemsadmin) as follows:

> create factory XAQueueConnectionFactory xaqueue url=tcp://7222

Document generated by Confluence on Oct 27, 2008 21:07 Page 406


WebLogic JMS Integration

This page last changed on Oct 21, 2008 by jackie.wheeler.

WebLogic JMS Integration


Before using Mule with WebLogic, copy the weblogic.jar file to $MULE_HOME/lib/user.

JNDI destinations syntax


If Mule fails to look up topics or queues in WebLogic's JNDI, but the JNDI tree lists them
as available, try replacing JNDI subcontext delimiters with dots, so tracker/topic/
PriceUpdates becomes tracker.topic.PriceUpdates.

WebLogic 8.x and Earlier


<jms:connector name="jmsConnector"
jndiProviderUrl="t3://localhost:7001"
connectionFactoryJndiName="javax.jms.QueueConnectionFactory"
jndiDestinations="true"
forceJndiDestinations="true"
jndiInitialFactory="weblogic.jndi.WLInitialContextFactory"
specification="1.0.2b"/>

WebLogic 9.x
For WebLogic 9.x, the configuration is almost the same. The only differences are:

• Supported JMS specification level is 1.1 (1.0.2b should still work, however)
• The unified JMS connection factory can be used as a result of the above. The following example
demonstrates using the default factories available out of the box.

<jms:connector name="jmsConnector"
jndiProviderUrl="t3://localhost:7001"
connectionFactoryJndiName="weblogic.jms.ConnectionFactory"
jndiDestinations="true"
forceJndiDestinations="true"
jndiInitialFactory="weblogic.jndi.WLInitialContextFactory"
specification="1.1"/>

Document generated by Confluence on Oct 27, 2008 21:07 Page 407


WebSphere MQ Integration

This page last changed on Oct 21, 2008 by jackie.wheeler.

WebSphere MQ Integration
If you are using WebSphere MQ, there are two transports you can use:

• The Mule WMQ transport provides support for native MQ. This transport is available only with Mule
Enterprise 1.6 or later.
• The JMS Transport includes a WebSphere connector that does not provide support for native MQ
but provides more functionality than the Mule WMQ connector and is available with the community
edition of Mule. The rest of this page describes the WebSphere connector in the JMS transport.

To configure the WebSphere MQ JMS connector for Mule, you do the following:

1. Set up a connection factory in the WAS admin console


2. Configure the <websphere-connector> in your Mule configuration file to use the connection factory.

Setting Up the Connection Factory


1. In the WAS Admin Console, go to Resources > WebSphere MQ JMS Provider > WebSphere MQ
Queue Connection Factories.
2. Set the following properties:

• Name: Connection Factory


• JNDI Name: jms/ConnectionFactory
• Queue Manager: (Your QMGR Here)
• Host, Port, etc.

Configuring Mule
In your Mule configuration file, add the following connector configuration:

<jms:connector name="jmsConnector"
connectionFactoryJndiName="jms/ConnectionFactory"
jndiInitialFactory="com.ibm.websphere.naming.WsnInitialContextFactory"
specification="1.1">
<spring:property name="connectionFactoryProperties">
<spring:map>
<spring:entry key="hostName" value="myMQServer"/>
<spring:entry key="transportType" value="1"/>
<spring:entry key="name" value="myMQConnector"/>
</spring:map>
</spring:property>
</jms:connector>

The hostName property is mandatory and refers to a name that will be used for this connection. This is
different from the host property, which refers to an IP address or network name of the server hosting
WebSphere MQ. In addition to the name attribute for the connector, you must also set a name property for
WebSphere.

If you're using IBM's connection factory, you may additionally need the following configuration - the
connection factory is configured in Spring here:

<jms:connector name="jmsConnector"
connectionFactoryJndiName="jms/ConnectionFactory"
jndiInitialFactory="com.ibm.websphere.naming.WsnInitialContextFactory"
specification="1.1"
connectionFactory-ref="MQConnectionFactory"/>

<spring:beans>

Document generated by Confluence on Oct 27, 2008 21:07 Page 408


<spring:bean name="MQConnectionFactory" class="com.ibm.mq.jms.MQQueueConnectionFactory">
<spring:property name="hostName" value="MyHost"/>
<spring:property name="port" value="6969"/>
<spring:property name="channel" value="S_machine"/>
<spring:property name="queueManager" value="QM_machine"/>
<spring:property name="transportType" value="1"/>
<spring:property name="specification" value="1.1"/>
</spring:bean>
</spring:beans>

Note that WebSphere MQ v5.3 requires at least Fix Pack 6 (CSD06) applied for JMS 1.1 support. Earlier
levels must set the specification property to 1.0.2b.
The latest WebSphere MQ Fix Packs can be downloaded here: http://www-1.ibm.com/support/
docview.wss?uid=swg27006037

You will also need the following IBM WebSphere JARs on your classpath:

• com.ibm.mq.jar
• com.ibm.mqjms.jar
• connector.jar

If you are using WAS, refer to this discussion for some known limitations.

Document generated by Confluence on Oct 27, 2008 21:07 Page 409


Using Mule HQ

This page last changed on Oct 20, 2008 by jackie.wheeler.

Using Mule HQ

[ Overview ] [ HQ Architecture ] [ Enabling Mule to Use Mule HQ ] [ Installing Mule HQ ] [ Starting


and Stopping Mule HQ ] [ Logging in to Mule HQ ] [ Importing Mule ] [ Configuring Mule in Mule HQ ] [
Setting Up Availability Alerts ] [ Configuring Remote Agents Manually ] [ Monitoring and Controlling Your
Resources ] [ Uninstalling Mule HQ ]

Overview
Mule HQ provides a centralized way to manage all of your Mule deployments as well as all of the disparate
systems and services in your SOA infrastructure. For example, a typical stack that Mule HQ monitors
might include Redhat Enterprise Linux, MySQL, JBoss Application Server, OpenMQ, and Mule.

Mule HQ provides integrated log, configuration, and server event tracking. It can detect Mule servers
and associated software and hardware, and report real-time and historical details of events. If you need
to debug a problem with your deployment, you can turn on the Profiler and view the details of memory
consumption at the message level.

Mule HQ is available with Mule Enterprise Edition only. It can monitor both Community Edition and
Enterprise Edition instances of Mule 1.x and 2.1 servers.

HQ Architecture
Mule HQ is based on Hyperic HQ. This section describes the Hyperic HQ Server and Agent.

Hyperic HQ Server

As HQ's central nervous system, the HQ Server coordinates all system functions, including:

• Processing incoming monitoring data


• Detecting alert conditions and sending out alerts
• Managing inventory, including merging auto-discovery information into current inventory
• Enforcing security
• Maintaining HQ operational schedules (for control actions and auto-discovery scans)
• Processing user-driven actions initiated via the HQ GUI or command line interface

In large environments, the HQ Server can be clustered to enhance fault tolerance and to share the overall
system load across multiple machines.

Document generated by Confluence on Oct 27, 2008 21:07 Page 410


Hyperic HQ Agent

Acting as the sensory facilities of the HQ system, Agents are deployed throughout the network
infrastructure to provide points-of-presence for discovering inventory, gathering data, controlling
software, and other "in the trenches" tasks.

The HQ Shell's Agent installer makes quick work of installing and managing all your HQ Agents - without
ever having to visit each managed machine.

Enabling Mule to Use Mule HQ


To use Mule with Mule HQ, you must enable the JMX support agent and (if installed) the Mule Profiler in
your Mule configuration.

Your Mule configuration files must be available to Mule HQ on a relative or absolute path.
They cannot be embedded in a JAR file.

Configure the JMX Support Agent

The default JMX support agent configures several JMX agents simultaneously. To add this to your
configuration, you add the management workspace and the <management:jmx-default-config> element
to your configuration file. For example:

<?xml version="1.0" encoding="UTF-8" ?>


<mule xmlns="http://www.mulesource.org/schema/mule/core/2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:management="http://www.mulesource.org/schema/mule/management/2.0"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.mulesource.org/schema/mule/core/2.0
http://www.mulesource.org/schema/mule/core/2.0/mule.xsd
http://www.mulesource.org/schema/mule/management/2.0
http://www.mulesource.org/schema/mule/management/2.0/mule-management.xsd">
<management:jmx-default-config port="1098">
<management:credentials>
<spring:entry key="jsmith" value="foo"/>
<spring:entry key="dthomas" value="bar"/>

Document generated by Confluence on Oct 27, 2008 21:07 Page 411


<spring:entry key="clee" value="pwd"/>
</management:jmx-default-config>
...

You can also provide more advanced configuration, such as using the RMI registry agent and specifying
the JMX server explicitly:

<management:rmi-server serverUri="rmi://localhost:9000"/>
<management:jmx-server>
<management:connector-server url="service:jmx:rmi:///jndi/rmi://localhost:9000/server"/>
<management:credentials>
<spring:entry key="user" value="pass"/>
</management:credentials>
</management:jmx-server>

For more information, see JMX Management.

Enable the Profiler Pack

The Mule Profiler pack allows you to profile your application (see Profiling Mule). After downloading and
installing the Profiler pack, you add the following element to your Mule configuration file:

<management:yourkit-profiler />

You must also add the -profile attribute to the bash/cmd script. For example, if you are using Windows,
you would edit stockquote.bat as follows:

IF '%Choice%'=='1' call "%MULE_BASE%\bin\mule.bat" -config


".\conf\stdio-config.xml,.\conf\stockquote-rest-config.xml" -builder spring -profile

If you are using a non-Windows operating system, you would edit it as follows:

if [ 1 = $i ]
then
exec "$MULE_BASE/bin/mule" -config "./conf/stdio-config.xml,./conf/stockquote-rest-config.xml" -
builder spring -profile

The configuration file you specify in the batch file depends on which variation and Mule instance you want
to use. The previous example specified the REST version of the Stock Quote example.

Setting the Server ID

When you run Mule, you must specify the -M-Dmule.serverId=MULE_SERVER_ID switch on the command
line (where MULE_SERVER_ID is the name of your Mule server) or set it programatically by calling
org.mule.config.DefaultMuleConfiguration.setId(). This will create the Mule.MULE_SERVER_ID JMX
domain, which Mule HQ will use to detect the Mule instance. You'll set this same domain ID when you
configure Mule in Mule HQ.

Verify the Configuration

Verify that your configuration changes were applied by starting the Mule instance you just configured (be
sure to specify the server ID as described in the previous section). For example, launch the stock quote
example and select REST when prompted:

Document generated by Confluence on Oct 27, 2008 21:07 Page 412


You should see an output similar to the one below at the end:

Installing Mule HQ
This section describes how to install the HQ Server and Agent. By default, Mule HQ uses its own
internal database. To install Mule HQ with an external database, see Installing Mule HQ with an External
Database.

Prerequisites

Before you install Mule HQ, you must do the following:

1. Log in as a non-root user and install Mule. Make sure that this non-root user account has Java in
the environment variable PATH and has write permission to <MULE_BASE>/conf/wrapper* files or
<MULE_HOME>/conf/wrapper* files, depending on whether MULE_BASE is set.
2. Configure your Mule instance to support Mule HQ (see Enabling Mule to Use Mule HQ).
3. On UNIX platforms, ensure that libXp.so.6 is installed. HQ Server requires this library to create
charts and other graphics in the user interface.

For more information on prerequisites, see the Installation Overview on the Hyperic site.

Install Mule HQ

1. On the computer where you want to install Mule HQ, log in as the same non-root user you used
when you installed Mule, and then create a directory called MuleHQ, such as C:\Program Files
\MuleHQ.

Document generated by Confluence on Oct 27, 2008 21:07 Page 413


2. Download the Mule HQ distribution (mule-hq-installer) and decompress it to the Mule HQ
directory.
3. In the Mule HQ directory, run setup.bat (on Windows) or setup.sh (on UNIX) at the command
prompt.
4. Follow the instructions on the screen (see the example below for details) and enter the following
values:
• When prompted to choose which software to install, press 1 and 3 to install both the HQ server
and agent.
• For the HQ server installation path, specify the MuleHQ directory you created in step 1, such as
C:\Program Files\MuleHQ.

Example Installation

This example illustrates what you see during installation. For simplicity, everything will be installed on the
localhost. The values you enter during installation are marked in bold.

Buildfile: C:\Temp\mule-hq-installer\installer-3.1.2-EE\bin\..\data\setup.xml
Initializing Mule HQ 3.1.2-EE Installation...
Loading taskdefs...
Taskdefs loaded
Choose which software to install:
1: Mule HQ Server
2: Mule HQ Shell
3: Mule HQ Agent
You may enter multiple choices, separated by commas.
1,3
HQ server installation path [default 'C:\Program Files']:
C:\Program Files\MuleHQ
HQ agent installation path [default 'd:/server/MuleHQ']:
Loading install configuration...
Install configuration loaded.
Preparing to install...
Validating agent install configuration...
Validating server install configuration...
Checking server webapp port...
Checking server secure webapp port...
Checking server JRMP port...
Checking server JNP port...
Verifying admin user properties
Validating server DB configuration...
Installing the agent...
Looking for previous installation
Unpacking agent to: d:/server/MuleHQ/agent-3.1.2-EE...
Installing the JRE ...
Unpacking JRE x86-win32-jre.exe to: d:/server/MuleHQ/agent-3.1.2-EE...
Setting permissions on agent binaries...
Fixing line endings on text files...
--------------------------------------------------------------------------------
Installation Complete:
Agent successfully installed to: d:/server/MuleHQ/agent-3.1.2-EE
--------------------------------------------------------------------------------
You can now start your HQ agent by running this command:
d:\server\MuleHQ\agent-3.1.2-EE\hq-agent.exe start
Installing the server...
Unpacking server to: d:/server/MuleHQ/server-3.1.2-EE...
Creating server configuration files...
Copying binaries and libraries to server installation...
Copying server configuration file...
Copying server control file...
Copying server binaries...
Copying server libs...
Setting up server database...
Setting up JDBC driver...
Copying database files...

Document generated by Confluence on Oct 27, 2008 21:07 Page 414


Configuring database...
Starting repopulation of configuration table...
Waiting for built-in database to start (on port 9432)...
Starting built-in database...
Preparing database...
Vacuuming database...
Waiting for server to stop...
Stopping built-in database...
Built-in database stopped.
Installing the JRE ...
Unpacking JRE x86-win32-jre.exe to: d:/server/MuleHQ/server-3.1.2-EE...
Setting permissions on server binaries...
Fixing line endings on text files...
--------------------------------------------------------------------------------
Installation Complete:
Server successfully installed to: d:/server/MuleHQ/server-3.1.2-EE
--------------------------------------------------------------------------------
You should now install the HQ server as a Windows Service using this command:
d:\server\MuleHQ\server-3.1.2-EE\bin\hq-server.exe -i
You can then use the Service Control Manager (Control Panel->Services) to
start the HQ server. Note that the first time the HQ server starts up it may
take several minutes to initialize. Subsequent startups will be much faster.
Once the HQ server reports that it has successfully started, you can log in
to your HQ server at:
http://localhost:7080/
username: hqadmin
password: hqadmin
To change your password, log in to the HQ server, click the "Administration"
link, choose "List Users", then click on the "hqadmin" user.
Setup completed.
A copy of the output shown above has been saved to:
D:\Temp\mule-hq-installer\installer-3.1.2-EE\bin\../hq-install.log
Press the Enter key to exit setup.

Detailed HQ Installation Instructions

For more detailed installation instructions, see the following Hyperic documentation:

• Windows
• Non-Windows

Install the HQ Server as a Windows Service

You can install the HQ Server as a Windows Service so that you can leave the HQ Server running even
after you log out of Windows. To install it as a service, navigate to the Mule HQ Server bin directory
(such as C:\Program Files\MuleHQ\server-3.1.2-EE\bin) and enter the following command at the
command prompt:

hq-server.exe -i

This command creates two services: Hyperic HQ Database and Hyperic HQ Server. You start the database
service first and then the server.

Starting and Stopping Mule HQ


The first time you start the HQ Server, it can take several minutes to initialize. Note that this happens
only the first time you start the server; subsequent starts are much faster.

Starting Mule HQ

To start Mule HQ, you start the database, then the server, and then the agent.

Document generated by Confluence on Oct 27, 2008 21:07 Page 415


Start the Database and Server

Navigate to the Mule HQ Server bin directory and execute the following commands:

db-start
hq-server

Note that there will be no console output from the first script. The second script should indicate that the
core system was initialized and that it is configuring from URL: resource:log4j.xml. Leave this command
window open while you are running Mule HQ.

If you installed the HQ Server as Windows services, you can start and stop the services from the Services
application in the Control Panel, or you can enter the following commands at the command prompt:

net start "Hyperic HQ Database"


net start "Hyperic HQ Server

Start the Agent

In a new command window, navigate to the agent directory (such as C:\Program Files\MuleHQ
\agent-3.1.2-EE) and enter the following command at the command prompt:

hq-agent

You must now answer several questions at the prompt. If you are testing the setup, you can specify
localhost for the server IP address and accept the defaults for everything else. For more information on
the agent settings, see Mule HQ Agent Settings.

If the connection fails, and you are using an evaluation version of Mule HQ, your license
may have expired. Click here to contact MuleSource about purchasing a license.

Stopping Mule HQ

To stop the server, log out of your Windows session, or enter the following command:

hq-server stop

If you installed the HQ Server as a Windows service, you can stop the service from the Services
application, or by entering net stop "Hyperic HQ Server" at the command prompt.

Logging in to Mule HQ
To log in to Mule HQ, do the following:

1. In a web browser, navigate to port 7080 of the server on which Mule HQ is installed, such as
http://localhost:7080/ or http://hostname.network.com:7080/.
The Mule HQ Login screen appears.

If the login screen does not appear, and you are using an evaluation version of
Mule HQ, your license may have expired. Click here to contact MuleSource about
purchasing a license.

2. Enter the default Administrator Login (hqadmin)and Password (hqadmin).


The Mule HQ Dashboard displays. Mule might be in the Auto-discovery list already. If it is not,
continue to the next section to import Mule into HQ.

Importing Mule
The Dashboard consists of several portlets that provide information about the HQ deployment. The first
portlet is the Auto-Discovery portlet, which discovers platforms, servers, and services on your system
and displays them here. After first starting Mule HQ, the portlet displays several entries (platform and
servers) for the newly registered HQ Agent on the local machine and for any other resource it has found

Document generated by Confluence on Oct 27, 2008 21:07 Page 416


on the host so far. These resources need to be "imported" (added to the HQ inventory) so that the Agent
can start collecting default metrics for them. You will know that the platform has been successfully
imported when you see its hostname in the Recently Added portlet (at the left).

You can manually import the platform, or use scripts to manage integration with Mule.

Importing the Platform Manually

On the Dashboard, select the radio button next to your host (and next to any other platform and server
entries in this portlet) and click Add to Inventory.

Using the Mule Integration Scripts

Mule HQ provides scripts for managing integration with Mule from the command line or programmatically.
To enable these scripts, copy the file commons-cli-1.1.jar from MULE_HOME\lib\boot to the following
location under your Mule HQ server directory: hq-engine\server\default\deploy\hq.ear\lib

To run these scripts, you enter the following command at the command prompt:

java -jar mule-sdk.jar <subcommand> <hq_host> <hq_port> <hq_username> <hq_password>

The following optional parameters constrain the subcommand to a specific Mule platform (otherwise, all
Mule platforms are affected):

• hq_host is the host where Mule HQ server is installed


• hq_port is the port of Mule HQ server
• hq_username, hq_password are credentials for the Mule HQ user

The subcommand must be one of the following:

Command Description

ai:approve Automatically approves and configures pending


Mule resources in the auto-discovery list.

ai:delete Deletes the pending Mule resources from the


auto-discovery list. In complex scenarios, you
must call this before calling ai:rescan.

ai:rescan Rescans Mule resources so that they will re-


appear in the auto-discovery list.

delete Deletes all approved Mule platforms from Mule


HQ.

ai:revert Reverts all skipped Mule instances from the


ignored state so that they can reappear in the
auto-discovery list.

Viewing Imported Resources

After importing a Mule instance manually or through the scripts, the Mule servers are added to Mule HQ.

Document generated by Confluence on Oct 27, 2008 21:07 Page 417


All imported Mule servers appear on the Mule Center tab.

After importing the Mule platform, if you want to run auto-discovery manually to discover recently added
Mule instances, do the following:

1. At the top of the Mule HQ window, click Browse Resources.


2. On the Platforms tab, click the Mule platform to display its details.
3. Click Tools Menu in the upper-right corner, and then choose New Auto-Discovery.

Document generated by Confluence on Oct 27, 2008 21:07 Page 418


4. Select the Mule check box and specify your Mule home directory for the directories to scan.
5. Leave the defaults for everything else and click OK.

Click the Dashboard to see the newly discovered resources that are ready for import.

Document generated by Confluence on Oct 27, 2008 21:07 Page 419


Configuring Mule in Mule HQ
After you have imported Mule into Mule HQ, you might need to perform some additional configuration.

To configure Mule:

1. On the Dashboard, click the Mule platform, click the Mule instance you want to configure, and click
the Inventory tab.
2. Scroll down until you see the Configuration Properties group, click it to expand its contents, and
then click Edit.
3. Enter the following settings:
• Specify the domain as Mule followed by a period followed by the Mule server ID you specified
when you ran Mule (see Setting the Server ID), such as Mule.MyMuleServer. This step is very
important. If the domain was already imported through auto-discovery, you can leave it as is.
• Specify the JMX URL used by your Mule instance. This URL is displayed on the startup screen
when you start Mule under Agents Running. If you do not see the JMX Agent listed, you have
not properly configured your Mule instance to work with Mule HQ--see Enabling Mule to Use
Mule HQ above.
• Leave the user name and password as empty values.
• Enable the Auto-Discover Components, Connectors, and Other Services option.

Make sure the metrics you want are collected often enough so you see the
results faster. Otherwise, it defaults to 1 minute.

4. Click OK.

For complete instructions on configuring resources in HQ, see Getting Started with HQ.

Setting Up Availability Alerts


Mule HQ can alert you when availability is lost. To enable this feature, take the following steps:

1. Navigate to the conf directory in your Mule HQ Server directory, and then open hq-server.conf for
editing.
2. Configure your mail server and set up email addresses for all Mule HQ users you want to notify, then
save and close the file.
3. In Mule HQ, click Mule, click the Alert tab, click New, and then specify a condition where the
availability metric's value is less than 100%.
4. Save the alert definition and specify the users to be notified for this condition.

For complete information on configuring alerts, click here.

Document generated by Confluence on Oct 27, 2008 21:07 Page 420


Configuring Remote Agents Manually
JBoss 4.2 does not provide or expose the JMX service URL. You can view Mule within JBoss by enabling a
remote JMX connection. This approach makes JBoss visible through JConsole and enables some remote
actions. However, this approach does not enable Mule HQ access.

To work around this limitation, Mule can start a local RMI registry (the JBoss 4.x registry will not work,
as it is not pure RMI) and connect via this lookup. To enable this approach, set the port attribute on
the <jmx-default-config> element in Mule as shown in Configure the JMX Support Agent above. This
ensures both the registry and JMX connector are coordinated properly and allows you to assign custom
connection ports. You then specify the JMX ServiceURL in MuleHQ as:

service:jmx:rmi:///jndi/rmi://localhost:1098/server

Because Mule HQ will not automatically discover this Mule instance, you must add it manually in the Mule
HQ application. You can specify a dummy server directory but specify the correct JMX URL and port. After
loading Mule HQ Server, the new Mule instance is discovered along with its components, routers, and
more.

For complete information on configuring agents in Mule HQ, click here.

Monitoring and Controlling Your Resources


Now that you have completed the installation and configuration, see the following topics for more
information on using Mule HQ:

• Monitoring Basics
• Controlling Resources

Following is a description of some of the key features for monitoring and controlling your resources in
Mule HQ.

As you monitor your components, note that statistics are not generated for
BridgeComponents, such as the BridgeComponent in the Stock Quote example.

Stopping, Starting, and Restarting Mule from Mule HQ

You can use the Stop, Start, and Restart control actions on the Control tab in Mule HQ to control a Mule
server, component, endpoint, router, or connector.

• The Stop command stops the Mule server and all related processes.

• The Start command launches a new Mule server instance using the HQ Agent. The HQ Agent creates
and executes a new command line using the configuration parameters stored in the inventory.

• The Restart command send a "restart" signal to restart the JVM and re-read the configuration
file. The Wrapper is not stopped, and external parameters like debug, profile, service, and the
configuration file are unchanged. Therefore, Restart is not the same as using the Stop and Start
commands.

Document generated by Confluence on Oct 27, 2008 21:07 Page 421


Profiling Mule

Mule is integrated with YourKit Java Profiler 7.0, the industry leader among profiling tools. If you installed
Mule and Mule HQ with the profiling option, you can use the Profiling tab in Mule HQ to create a snapshot,
start CPU profiling, and more. Captured snapshots are saved in ~/Snapshots/ on Linux.

If you did not install the Profiling kit with Mule or did not enable it, the Profiling tab indicates that the
profiler is not installed or enabled. If you want to install it now, you can download the ZIP or GZ version
of the mule-profiler-pack file here and follow the instructions here to install it.

Patch Management

The Mule Center tab in Mule HQ provides a list of all your Mule servers. It also allows you to install Mule
patches to remote servers that have been distributed to you by MuleSource.

Viewing Mule Log Files

You can view the Mule log files from remote servers in Mule HQ by clicking the Show Log link on the
Indicators tab when viewing the details of a Mule server.

Document generated by Confluence on Oct 27, 2008 21:07 Page 422


Uninstalling Mule HQ
To uninstall Mule HQ, you run the hq-server and hq-agent scripts with the -u parameter. For example, on
Windows you would run:

hq-server.exe -u
hq-agent.exe -u

For complete information on uninstalling HQ, see Uninstalling Hyperic HQ on the Hyperic site.

Document generated by Confluence on Oct 27, 2008 21:07 Page 423


Installing Mule HQ with an External Database

This page last changed on May 29, 2008 by jackie.wheeler.

Installing Mule HQ with an External Database


By default, Mule HQ uses its own internal database. This section describes how to install Mule HQ with
a standalone PostgreSQL, Oracle, or MySQL database. To install, navigate to the Mule HQ directory, and
then run one of the following commands to perform a quick install, which prompts you for the database
connection information and uses defaults for all other settings:

PostgreSQL

UNIX: setup.sh -postgresql

Windows: setup.bat -postgresql

Oracle

UNIX: setup.sh -oracle

Windows: setup.bat -oracle

MySQL

UNIX: setup.sh -mysql

Windows: setup.bat -mysql

Notes

PostgreSQL 8.0

During installation, Mule HQ creates a language in the PostgreSQL database, but Mule HQ cannot create
the language automatically in PostgreSQL 8.0. Therefore, to use version 8.0, you must run the following
command on the Mule HQ database before starting the Mule HQ Server.

createlang plpgsql [MULEHQ:DATABASE NAME]

The createlang executable is located in the bin directory of your PostgreSQL installation.

MySQL 5.0

MySQL 5.0 or higher is not yet supported by Hyperic HQ and is currently in Beta. Support is expected for
Hyperic HQ 3.2.

For advanced database preparation, see the Database Preparation Guide

Document generated by Confluence on Oct 27, 2008 21:07 Page 424


Mule HQ Agent Settings

This page last changed on May 29, 2008 by jackie.wheeler.

Mule HQ Agent Settings


When you run the Mule HQ Agent, it prompts you for connection information to your HQ Server.

[MULEHQ: Running agent setup ]


What is the HQ server IP address: 172.30.46.145
Should Agent communications to HQ always be secure [MULEHQ:default=yes]: yes
What is the HQ server port [MULEHQ:default=7080]: 7080
- Testing secure connection ... Success
What is your HQ login [MULEHQ:default=hqadmin]: hqadmin
What is your HQ password: **Not echoing value**
What IP should HQ use to contact the agent [MULEHQ:default=172.30.46.145]: 172.30.46.145
What port should HQ use to contact the agent [MULEHQ:default=2144]: 2144
- Received temporary auth token from agent
- Registering agent with HQ
- HQ gave us the following agent token
1192444751142-7096515327909319777-6396758454203270452
- Informing agent of new HQ server
- Validating
- Successfully setup agent

To make the Agent deployment process easier, you can specify these settings in the agent.properties
file located in the agent root directory. The file looks like this:

agent.properties

agent.setup.camIP=172.30.46.145
agent.setup.camPort=7080
agent.setup.camSSLPort=7443
agent.setup.camSecure=yes
agent.setup.camLogin=hqadmin
agent.setup.camPword=hqadmin
agent.setup.agentIP=*default*
agent.setup.agentPort=*default*

where values of camIP, camLogin and camPword parameters should be replaced with your HQ Server IP,
user name, and password. By setting these values in the file, you will no longer need to interactively
answer questions when you first start up the Mule HQ Agent.

Additionally, the MuleServerDetector uses an Internet connection to get some DTDs. If you use an
external HTTP proxy for your Internet connection, you must add the following value to the agent.javaOpts
property:

-Dhttp.proxyHost=<PROXY_HOST> -Dhttp.proxyPort=<PROXY_PORT>

For more information on agent properties see the HQ Agent Configuration page on the Hyperic site.

Document generated by Confluence on Oct 27, 2008 21:07 Page 425


Using Mule Modules

This page last changed on Oct 20, 2008 by jackie.wheeler.

Using Mule Modules


Modules are similar to transports in that they provide pluggable functionality, configured via dedicated
schema, but they differ in that there is no underlying transport to send or receive data. Following is a list
of the default Mule modules.

Acegi Module Security via Acegi.

Client Module MuleClient and the remote dispatcher, giving


simple access to the Mule server.

JAAS Module Security via JAAS.

JBoss Transaction Manager JBoss transaction support.

Management Module Mule agents for server management using JMX.

OGNL Module Provides a filter using OGNL expressions. For


details, see Using OGNL Expressions.

PGP Module Security via PGP.

Scripting Module Interface between Mule and scripting languages


(currently Groovy).

Spring Extras Module Extensions for using the Spring framework with
Mule.

SXC Module A very fast streaming XPath router and filter.

XML Module XML based utilities (mainly filters and routers).

Document generated by Confluence on Oct 27, 2008 21:07 Page 426


Acegi Module

This page last changed on Oct 20, 2008 by jackie.wheeler.

Acegi Module
This module provides Acegi-based security and delegates authorization to some other provider.

Security Manager

Child Elements of <security-manager...>

Name Cardinality Description

delegate-security-provider 0..1 An Acegi-based security provider


that delegates authorization to
some other provider.

Delegate Security Provider


An Acegi-based security provider that delegates authorization to some
other provider.

Attributes of <delegate-security-provider...>

Name Type Required Default Description

delegate-ref name (no spaces) no

Child Elements of <delegate-security-provider...>

Name Cardinality Description

security-property 0..*

Http Security Filter


This appears to authenticate users via information in standard HTTP headers.

Attributes of <http-security-filter...>

Name Type Required Default Description

realm string no

securityProviders string no The delegate-


security-provider
to use for
authenticating.
Use this element

Document generated by Confluence on Oct 27, 2008 21:07 Page 427


in case you
have multiple
security managers
defined in your
configuration.

Document generated by Confluence on Oct 27, 2008 21:07 Page 428


JAAS Module

This page last changed on Jun 12, 2008 by jackie.wheeler.

JAAS Module
This module provides security via JAAS.

Security Manager
This is the security provider type that is used to configure JAAS related functionality.

Child Elements of <security-manager...>

Name Cardinality Description

security-provider 0..1 This is the security provider type


that is used to configure JAAS
related functionality.

password-encryption-strategy 0..*

Security Provider
This is the security provider type that is used to configure JAAS related functionality.

Attributes of <security-provider...>

Name Type Required Default Description

loginContextName string no

credentials string no

loginConfig string no

loginModule string no

Jaas Security Filter


This appears to authenticate users via information in standard HTTP headers.

Document generated by Confluence on Oct 27, 2008 21:07 Page 429


JBoss Transaction Manager

This page last changed on Jul 31, 2008 by jackie.wheeler.

JBoss Transaction Manager


This module enables Mule to use the JBoss transaction manager (previously Arjuna) to configure XA
transactions. Developers can configure one Transaction Manger per Mule instance. For more information,
see JBoss Transactions.

Transaction Manager
To configure an instance of the JBoss transaction manager within Mule, add this element to your Mule
XML config file. You can configure arbitrary properties on the transaction manager that will be passed on
to the underlying transaction manager. For example:

<jbossts:transaction-manager>
<property key="test" value="TEST"/>
</jbossts:transaction-manager>

You can then declare XA transactions on endpoints supporting XA transactions, and all those transactions
will be managed by the JBoss transaction manager.

Document generated by Confluence on Oct 27, 2008 21:07 Page 430


Scripting Module

This page last changed on Oct 24, 2008 by jackie.wheeler.

Table of Contents

Click here to expand...

• Scripting Module
• ° Script Context Bindings
° Transformers
° Component
° - Attributes of <component...>
- Child Elements of <component...>
- Example Configurations
- Example Configurations
° Script
° - Attributes of <script...>
- Child Elements of <script...>
° Groovy Refreshable
° - Attributes of <groovy-refreshable...>
° Lang
° Script Configuration Builder

Scripting Module
The scripting module provides facilities for using scripting languages in Mule. Any scripting languages
that supports JSR-223 can be used inside Mule. Scripts can be used as implementations of service
components or transformers. Also, scripts can be used for expression evaluations, meaning message
routing can be controlled using script evaluations on the current message. You can even configure Mule
instances from scripts.

Script Context Bindings


When run inside Mule, scripts have a number of objects available to them in the script context. These
are:

Name Description

log a logger that can be used to write to Mule's log


file.

muleContext a reference to the MuleContext object.

eventContext A reference to the eventcontext. This allows you


to dispatch events progammatically from your
script

message the current message.

originalPayload the payload of the current message before any


transforms.

payload the transformed payload of the current


message if a transformer is configured on the
service. Otherwise this is the same value as
originalPayload.

src same as payload, kept for backward


compatability.

Document generated by Confluence on Oct 27, 2008 21:07 Page 431


service a reference to the current service object.

id the current event id.

result a placeholder object where the result of the script


can be written to. Usually it's better to just return
a value from the script unless the script method
doesn't have a return value.

Transformers
These are transformers specific to this transport. Note that these are added automatically to the Mule
registry
at start up. When doing automatic transformations these will be included when searching for the correct
transformers.

Name Description

transformer Runs a script to perform transformation on the


current message. To use Groovy as an example,
the following transformer configuration will
converts a comma-separated string of values to a
java.util.List.

Component
Defines a script component backed by a JSR-223 compliant script engine such as Groovy, JavaScript, or
Ruby. Scripting allows you to either directly embed your script inside the XML config or reference a script
using Spring's dynamic language support: http://static.springframework.org/spring/docs/2.5.x/reference/
dynamic-language.html.

Attributes of <component...>

Name Type Required Default Description

script-ref name (no spaces) no A reference to


a script object
bean, that is, a
<script:script ...>
definition.

Child Elements of <component...>

Name Cardinality Description

script 0..1 A script to be executed by


a JSR-223 compliant script
engine such as Groovy,
JavaScript(Rhino), Python, Ruby
or Beanshell (etc).

java-interface-binding 0..* A binding associates a Mule


endpoint with an injected Java
interface (this is like using
Spring to inject a bean, but

Document generated by Confluence on Oct 27, 2008 21:07 Page 432


instead of calling a method on
the bean a message is sent to
an endpoint). Script bindings
will only work with Java-based
scripting languages. Right
now there is no validation on
when languages support java
bindinngs since there are so
many scripting languages.

Example Configurations

This example demonstrates how to configure a Groovy Script component with an in-line script.

Click here to expand...


An error occurred: null. The system administrator has been notified.

Example Configurations

This example demonstrates how to orchestrate message flows using bindings. The example calls out to
two different services and passes the results on to the outbound router.

Click here to expand...


An error occurred: null. The system administrator has been notified.

Script
Represents a script that can be used as a component for a service or a transformer. The script text can
be pulled in from a script file or be embedded inside this element. A script to be executed by any JSR-223
compliant script engine such as Groovy, JavaScript(Rhino), Python, Ruby or Beanshell (etc).

Attributes of <script...>

Name Type Required Default Description

name string no The name used


to identify this
script object. This
is used when you
want to reference
this script object
from a component
or transformer.

engine string no The name of the


script engine
being used.
All scripting
languages that
support JSR-223
have a script
engine name such
as groovy, ruby,
python, etc. If this
value is not set,
but a script file is
configured, Mule
will attempt to
load the correct

Document generated by Confluence on Oct 27, 2008 21:07 Page 433


script engine
according to
the script file's
extension.

file string no The script file


to load for this
object. The file
can be on the
classpath or local
file system.

Child Elements of <script...>

Name Cardinality Description

text 0..1 Used for embedding script code


inside the XML. This is useful
for simple scripts where you
are just mocking up a quick
application.

Groovy Refreshable
A wrapper for a component object that allows the underlying object to be reloaded at runtime. This
makes it possible to hot-deploy new component logic without restarting.

Attributes of <groovy-refreshable...>

Name Type Required Default Description

name string no The name for this


refreshable groovy
bean wrapper.

refreshableBean- name (no spaces) no The referecne to a


ref groovy.lang.Groovy
object to use for
this component.

methodName string no The entrypoint


method to invoke
when a message
is received for the
object.

Lang
This element allows the http://www.springframework.org/schema/lang namespace to be embedded.
Within this element developers can include the spring lang namespace.

Script Configuration Builder


The ScriptConfigurationBuilder allows developers to create a Mule instance from a JSR-223 compliant
script. To load the manager from Groovy:

Document generated by Confluence on Oct 27, 2008 21:07 Page 434


ConfigurationBuilder builder = new ScriptConfigurationBuilder("groovy", "../conf/mule-
config.groovy");
MuleContext muleContext = new DefaultMuleContextFactory().createMuleContext(builder);

Or to start the server from the command line:

mule -M-Dorg.mule.script.engine=groovy
-builder org.mule.module.scripting.builders.ScriptConfigurationBuilder
-config ../conf/mule-config.groovy

For more information about configuring a Mule instance from code or script see Configuration Overview.

Document generated by Confluence on Oct 27, 2008 21:07 Page 435


Spring Extras Module

This page last changed on Jul 31, 2008 by jackie.wheeler.

Spring Extras Module


This page is ready for review

This module provides extensions for using the Spring framework with Mule, such as using the Spring
container to build components managed by Mule.

Package Description

org.mule.module.spring.events A Spring EventMulticaster that allows any Spring


bean to send and receive Mule events through the
ApplicationContext and event listeners.

org.mule.module.spring.i18n Spring messages that can be localized.

org.mule.module.spring.interceptor Includes an interceptor adapter for use with


Spring AOP.

org.mule.module.spring.remoting Classes for using Spring remoting. For more


information, see the Spring Remoting example.

org.mule.module.spring.transaction Provides classes for a transaction factory and


transaction manager factory.

Document generated by Confluence on Oct 27, 2008 21:07 Page 436


SXC Module

This page last changed on Oct 20, 2008 by jackie.wheeler.

SXC Module
The SXC module contains an outbound router and a filter which utilize the SXC project for streaming
XPath routing.

SXC allows listening for XPath expressions as the document is being parsed. As soon as an expression
is found, an event is fired, and parsing is stopped. This allows for much more efficient XPath evaluation.
XPath evaluators such as Jaxen work with a DOM model, so even when working with lazy-loading DOMs,
such as AXIOM, there is more overhead than in just reading directly off the XML stream.

SXC does not support all XPath expressions, only a limited subset. For a reference of what it supports,
see the SXC documentation. To request support for a missing XPath feature, please file a SXC JIRA.

Using the SXC Outbound Router and Filter


SXC requires a special filtering outbound router. This can be combined with the SXC Filter and any other
filters which do not work on the XML payload itself (i.e. AndFilter, OrFilter, MessagePropertyFilter, etc).

Here is a simple example which routes a message based on an XML attribute:

<sxc:filtering-router>
<outbound-endpoint address="vm://log"/>
<sxc:filter pattern="//purchaseOrder[@country]"/>
<sxc:namespace prefix="test" uri="http://foo"/>
</sxc:filtering-router>

Document generated by Confluence on Oct 27, 2008 21:07 Page 437


XML Module

This page last changed on Aug 15, 2008 by jackie.wheeler.

XML Module
This page is under construction

Transport (schemadoc:page-title not set)


Transformers
These are transformers specific to this transport. Note that these are added automatically to the Mule
registry
at start up. When doing automatic transformations these will be included when searching for the correct
transformers.

Name Description

dom-to-xml-transformer

dom-to-output-handler-transformer

jxpath-extractor-transformer

object-to-xml-transformer

xml-to-dom-transformer

xml-to-object-transformer

xslt-transformer A transformer used to perform XSLT transforms


on the current message payload. Transform
objects are pooled for better performance. You
can set context properties on the transformer
by pulling them from the current message using
Expression Evaluators.

xml-prettyprinter-transformer Formats an XML string using the Pretty Printer


functionality in org.dom4j.io.OutputFormat.

Filters
Filters can be used on inbound endpoints to control which data is received by a service.

Name Description

is-xml-filter

jxpath-filter

jaxen-filter

Document generated by Confluence on Oct 27, 2008 21:07 Page 438


Message Splitter

Attributes of <message-splitter...>

Name Type Required Default Description

splitExpression string no

externalSchemaLocation
string no

validateSchema boolean no

Child Elements of <message-splitter...>

Name Cardinality Description

namespace 0..*

Round Robin Splitter

Attributes of <round-robin-splitter...>

Name Type Required Default Description

splitExpression string no

externalSchemaLocation
string no

validateSchema boolean no

endpointFiltering boolean no If true then the


message part is
sent to the first
endpoint whose
filter accepts the
part. The default
is false.

deterministic boolean no If
endpointFiltering
is false and this
option is true (the
default) then the
first message part
if routed to the
first endpoint, the
second part to the
second endpoint,
etc, with the nth
part going to the
(n modulo number
of endpoints)
endpoint. If
false then the
messages will

Document generated by Confluence on Oct 27, 2008 21:07 Page 439


be distributed
equally amongst
all endpoints.

Document generated by Confluence on Oct 27, 2008 21:07 Page 440


Using Mule with Spring

This page last changed on Aug 13, 2008 by jackie.wheeler.

Using Mule with Spring


Mule and Spring can integrate on different levels. You can can choose as much or little Mule in your
Spring application or Spring in your Mule application. The following pages describe in detail how you can
use Mule and Spring together.

• Using Spring Beans as Service Components


How to configure Spring beans as service components in Mule.

• Sending and Receiving Mule Events in Spring


A really easy way for your beans to send and receive Mule events via the Spring Application Context
without any code changes.

• Spring Remoting
An example of accessing Mule from an external application using Spring remoting.

Additionally, there are two Spring-related projects in the Developer Sandbox.

Document generated by Confluence on Oct 27, 2008 21:07 Page 441


Sending and Receiving Mule Events in Spring

This page last changed on Aug 01, 2008 by jackie.wheeler.

Sending and Receiving Mule Events in Spring


You can configure Spring beans to publish events to Mule and configure Spring event listeners to receive
Mule events. This page describes how to set up the configuration.

Spring Events Overview


Spring provides a simple mechanism for sending and receiving events between beans. To receive an
event, a bean implements ApplicationListener, which has a single method:

ApplicationListener.java

public void onEvent(ApplicationEvent event);

To publish events to listeners, you call the publishEvent() method on the ApplicationContext. This will
publish the same event to every listener in the context. You can also plug in custom event handlers to the
application context.

Mule Events in Spring


To start receiving Mule events, you create a bean based on MuleEventMulticaster in your Mule
configuration file. This class is an Application Event Multicaster that enables Spring beans to send and
receive Mule events. You also add one or more endpoints on which to receive events:

xmlns:spring="http://www.springframework.org/schema/beans"
...
<spring:beans>
<spring:bean id="applicationEventMulticaster"
class="org.mule.module.spring.events.MuleEventMulticaster">
<spring:property name="subscriptions">
<spring:list>
<spring:value>jms://my.queue</value>
<spring:value>pop3://ross:secret@mail.muleumo.org</value>
</spring:list>
</spring:property>
</spring:bean>
</spring:beans>

With this configuration, any emails received for ross@muleumo.org or any JMS messages sent to
my.queue will be received by all Spring event listeners. Note that the MuleEventMulticaster does
not interfere with normal Spring event behavior. If a non-Mule applicationEvent is sent via the
ApplicationContext, all beans registered to receive events will still get the event.

The inbound endpoints can be any valid Mule Endpoint, so you can receive JMS messages, SOAP
requests, files, HTTP and servlet requests, TCP, multicast, and more.

Adding Bean Subscriptions

You can have beans subscribe only to relevant events. The MuleSubscriptionEventListener includes two
methods for getting and setting an array of endpoints on which the bean will receive events.

TestSubscriptionBean.java

package org.mule.module.spring.events;
public class TestSubscriptionEventBean extends TestMuleEventBean implements
MuleSubscriptionEventListener
{
private String[] subscriptions;

Document generated by Confluence on Oct 27, 2008 21:07 Page 442


public void setSubscriptions(String[] subscriptions)
{
this.subscriptions = subscriptions;
}
public String[] getSubscriptions()
{
return subscriptions;
}
}

You configure this bean like any other bean:

xmlns:spring="http://www.springframework.org/schema/beans"
...
<spring:beans>
<spring:bean id="subscriptionBean" class="org.mule.module.spring.events.TestSubscriptionEventBean">
<spring:property name="subscriptions">
<spring:list>
<spring:value>vm://event.*</value>
</spring:list>
</spring:property>
</spring:bean>
</spring:beans>

Publishing Events to Mule

Publishing events is just as easy as receiving them. You use the standard publishEvent() method on
the application context. Your bean can get a reference to the application context by implementing
ApplicationContextAware or by querying MuleApplicationEvent .

//Create a new MuleEvent.


Object message = new String("This is a test message");
MuleApplicationEvent muleEvent = new MuleApplicationEvent(
message, "jms://processed.queue");

//Call publishEvent on the application context, and Mule does the rest
applicationContext.publishEvent(muleEvent);

For more information on publishing events, see the Error Handler Example.

Document generated by Confluence on Oct 27, 2008 21:07 Page 443


Using Spring Beans as Service Components

This page last changed on Oct 10, 2008 by jackie.wheeler.

Using Spring Beans as Service Components


[ Defining the Beans ] [ Configuring the Beans ] [ Configuring the Component ] [ Using JNDI and EJB
Session Beans ]

You can construct service components from Spring beans that you define in a separate Spring
context file or right in the Mule configuration file. This pages provides an example using two beans; a
RestaurantWaiter bean that receives and logs orders and then passes them to the KitchenService bean,
which receives the orders.

Defining the Beans


The Java code for the beans look like this:

public class RestaurantWaiter


{
private KitchenService kitchen = null;

public void takeOrder(Order order) {


//log order

//notify kitchen
this.kitchen.submitOrder(order);
}

public void setKitchenService(KitchenService kitchen) {


this.kitchen = kitchen;
}

public KitchenService getKitchenService() {


return kitchen;
}
}

Configuring the Beans


First, you configure the beans in your Spring application context:

<beans>
<bean id="restaurantWaiter" scope="prototype" class="com.foo.RestaurantWaiter">
<property name="kitchenService">
<ref local="kitchenService"/>
</property>
</bean>

<bean id="kitchenService" class="com.foo.KitchenService"/>


</beans>

We now have beans called restaurantWaiter and kitchenService that will be created by Spring. Notice
the resturantWaiter bean scope is set to prototype (by default, all beans in Spring are singletons unless
specified otherwise). This is important because Mule will pool your components, and telling Spring not to
create a singleton ensures that each pooled instance will be a unique instance.

If you want to configure the beans right in your Mule configuration file instead of in a separate Spring
context file, you could specify them like this:

xmlns:spring="http://www.springframework.org/schema/beans"
...

Document generated by Confluence on Oct 27, 2008 21:07 Page 444


<spring:beans>
<spring:bean id="restaurantWaiter" scope="prototype" class="com.foo.RestaurantWaiter">
<spring:property name="kitchenService">
<spring:ref local="kitchenService"/>
</spring:property>
</spring:bean>
<spring:bean id="kitchenService" class="com.foo.KitchenService"/>
</spring:beans>

Configuring the Component


After you have configured the beans, you can create your reference to restaurantWaiter in
the component. For example, the following configuration creates a component that will enable
restaurantWaiter to receive events from VM. This example assumes the beans are in a separate file, so if
you configured them right in the Mule configuration file, you do not need the <spring:import> tag.

xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.0"
xmlns:spring="http://www.springframework.org/schema/beans"
...
<spring:import resource="conf/applicationContext.xml"/>
...
<service name="Restaurant Waiter">
<inbound>
<vm:inbound-endpoint path="order.queue"/>
</inbound>
<pooled-component>
<spring-object bean="restaurantWaiter"/>
</pooled-component>
</service>

When the Mule server starts, each of the <service> elements are loaded, and the bean you specified in
the <spring-object> tag is created. When an event is received on vm://orders.queue, an Order object
is passed to the takeOrder() method on the RestaurantWaiter, which then logs the order and passes it
to the KitchenService.

For more information on component configuration, see Configuring Components. For more information on
the elements you use to configure components, see Component Configuration Reference.

Using JNDI and EJB Session Beans


If you define JNDI and EJB session beans in Spring using the generic <bean> element, you configure
them exactly as any other Spring bean in Mule. However, if you use the <jee> elements to define them
in Spring (<jee:jndi-lookup>, <jee:local-slsb>, and <jee:remote-slsb>), you must include the jee
namespace and schema locations in your Mule configuration file as follows:

xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="
...
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-
jee-2.5.xsd"
...
<jee:remote-slsb id="creditAgencyEJB" jndi-name="local/CreditAgency"
business-interface="org.mule.example.loanbroker.credit.CreditAgency">
<jee:environment>
java.naming.factory.initial=org.openejb.client.LocalInitialContextFactory
java.naming.provider.url=rmi://localhost:1099 openejb.base=${openejb.base}
openejb.configuration=${openejb.configuration} logging.conf=${logging.conf}
openejb.nobanner=${openejb.nobanner}
</jee:environment>
</jee:remote-slsb>
...
<mule:service name="CreditAgencyService">
<mule:inbound>
<mule:inbound-endpoint ref="CreditAgency" />

Document generated by Confluence on Oct 27, 2008 21:07 Page 445


</mule:inbound>
<mule:component>
<mule:spring-object bean="creditAgencyEJB" />
</mule:component>
</mule:service>
...

For more information, see Enterprise Java Beans (EJB) integration and the jee schema reference on the
Spring site.

Document generated by Confluence on Oct 27, 2008 21:07 Page 446


Using the Mule Client

This page last changed on Oct 20, 2008 by jackie.wheeler.

Using the Mule Client


[ Using Send and Dispatch ] [ Configuring the Mule Client ] [ MuleClient as a Web Services Client ] [
Performing an Event Request Call ] [ Associating Properties with the Message ] [ When Not to Use the
Mule Client ] [ Handling Message Collections ] [ Future Results ] [ Using the Remote Dispatcher ] [
Sending Messages to Components Directly ]

In most Mule applications, messages are triggered by an external occurrence such as a message being
received on a queue or a file being copied to a directory. However, if you want to send and receive
messages programmatically, you can create a Mule client.

The Mule client is a simple interface for Java clients to send and receive messages from a Mule server and
other applications. The client serves the following functions:

• Sending and receiving messages to and from a local or remote Mule server
• Communicating with other applications using any Mule transport
• Making requests to a Mule server behind a firewall using the RemoteDispatcher

The Mule client can be used as a web services client to make SOAP requests using popular SOAP
implementations such as Apache CXF. It can also send messages directly to a service component and
bypass the transports layer completely, which is useful for testing your service components or when
triggering an event from a script or JSP page.

The Mule client can be used with any of the Mule transports, making it a universal client for many types
of transports such as JDBC, JMS, FILE, POP3, XMPP, HTTP, etc.

The following sections describe how to use the MuleClient in various scenarios.

Using Send and Dispatch


The Mule client allows the user to send and receive messages programmatically. For example, to send a
JMS message to any application or Mule component listening on my.queue, you can use the dispatch()
method. The dispatch() method provides the ability to "fire and forget" messages over an endpoint.

MuleClient client = new MuleClient();


client.dispatch("jms://my.queue", "Message Payload" null);

To make a regular synchronous call to a service and receive a result, you can use the send() method:

MuleClient client = new MuleClient();


MuleMessage result = client.send("tcp://localhost:3456", "Message Payload", null);

The client send() and dispatch() methods expect the following arguments:

1. The Mule URL endpoint: any valid Mule Endpoint used to determine the transport, endpoint, and
other information about delivery of the message. This can also be an endpoint name stored in
configuration.
2. The message payload: any object carried by the message.
3. Properties: any properties or meta-data to associate with the message being sent

Don't use physical endpoints in your code

For clarity, the examples on this page use a physical endpoint URI, such as jms://myQueue.
However, it is much better practice to define all your endpoints inside a Mule configuration
file using the <endpoint> tag and then reference those endpoint names in your code.

Document generated by Confluence on Oct 27, 2008 21:07 Page 447


Configuring the Mule Client
If you are using the Mule client in the same classloader (e.g., a Web App or Mule stand-alone), the client
will have access to the server configuration. For example, if you had some endpoints defined in your
server configuration file:

<http:endpoint host="192.168.0.1" port="80" path="/services" name="serviceEndpoint"/>

This endpoint will be accessible by the Mule client:

MuleClient client = new MuleClient();


client.dispatch("serviceEndpoint", dataObject, null);

Essentially, the Mule client will have the same configuration information as the Mule server, since they will
both have access to the same registry.

If you are running the Mule client in stand-alone mode, you can still configure it using its own Mule XML
configuration file(s). You pass in these files when the client is created:

MuleClient client = new MuleClient("http-client-config.xml, shared-client-config.xml");


client.getMuleContext().start();

Note that you must start the local Mule context used by the client. You can also create your own Mule
context and pass it into the client:

//Create a MuleContextFactory
MuleContextFactory muleContextFactory = new DefaultMuleContextFactory();

//create the configuration builder and optionally pass in one or more of these
ConfigurationBuilder builder =
new SpringConfigurationBuilder("http-client-config.xml, shared-client-config.xml"));
//The actual context builder to use
MuleContextBuilder contextBuilder = new DefaultMuleContextBuilder();

//Create the context


MuleContext context = muleContextFactory.createMuleContext(builder, contextBuilder);

//Start the context


context.start();

//Create the client with the context


MuleClient client = new MuleClient(context);

MuleClient as a Web Services Client


The Mule client can be used as a web services client to make SOAP requests using popular SOAP
implementations such as Apache Axis or CXF.

MuleClient client = new MuleClient();

//Arguments for the addPerson WS method


String[] args = new String[]{"Ross", "Mason"};

//Call the web service


client.dispatch("axis:http://localhost:38004/PersonService?method=addPerson", args, null);

//Call another method to look up the newly added person


MuleMessage result = client.send
("axis:http://localhost:38004/PersonService?method=getPerson", "Ross", null);

//A person object is returned, and all type mapping is handled for you
Person person (Person)result.getPayload();

System.out.println(person.toString());

Document generated by Confluence on Oct 27, 2008 21:07 Page 448


The Mule SOAP Transport supports Apache Axis and CXF. For more information about Mule Axis support,
see Axis Web Services and Mule.

Performing an Event Request Call


Making a request to an endpoint is useful when using a transport that has a store of events that you want
to request rather then have a listener on the resource.

To make a request for a message, use the request() method:

MuleClient client = new MuleClient();


MuleMessage result = client.request("pop3://ross:blah@mail.my.org", 5000);

This code will attempt to receive a message from a mailbox called ross on mail.my.org and will return
after five seconds if no message was received. Calling request() works for all Mule supported transports,
but it is more usual to make event request calls where there is a store to be queried such as a queue, file
directory, or some other repository.

Associating Properties with the Message


The previous examples set the properties argument to null. Properties can be arbitrary, such as to pass
around custom metadata with your messages, or they can be transport-specific. The following example
demonstrates an asynchronous request/response using JMS and the JMS-specific JMSReplyTo property.
When the JMSReplyTo is set, it is stated in the JMS spec that a receiver of the message should send back
any results to the destination defined in the JMSReplyTo header. Mule does this for you.

//create the client instance


MuleClient client = new MuleClient();

//create properties to associate with the message


Map props = new HashMap();

//Set the JMSReplyTo property, which is where the response message will be sent
props.put("JMSReplyTo", "replyTo.queue");

//dispatch the message asynchronously


client.dispatch("jms://test.queue", "Test Client Dispatch message", props);

//Receive the return message on the replyTo.queue


MuleMessage message = client.request("jms://replyTo.queue", 5000);

//This is the message sent back from the first component to process our message
System.out.println(message.getPayload());

When Not to Use the Mule Client


It's generally not good practice to make calls using the Mule client from your service objects or within
extensions to Mule such as routers or transformers.

When you need to dispatch or request events in Mule, you should use the current
org.mule.api.MuleEventContext and call the send/dispatch/request methods on the context instead.

To gain access to the MuleEventContext inside your services, you can implement the
org.mule.api.lifecycle.Callable interface.

If you need to make an event request from a transformer, filter, or interceptor, you should reconsider your
design strategy for that event flow.

Handling Message Collections


Since Mule 2.1, some outbound routers such as the Message Splitter, Multicaster, and Recipient List may
return more that one result message in the following cases:

Document generated by Confluence on Oct 27, 2008 21:07 Page 449


• There is more than one endpoint configured on the router
• More than one of the endpoints has the synchronous=true attribute set

To handle situations where multiple results occur, Mule has introduced a new message type
org.mule.api.MuleMessageCollection . This type of message contains all message results in the order they
were received. Note that org.mule.api.MuleMessageCollection extends org.mule.api.MuleMessage , so
the interface is similar. If there are multiple results, the MuleMessage.getPayload() method returns a
java.util.List containing the payloads of each of the returned messages.

When using the Mule client, you can cast the message return type to get access to all MuleMessage
objects.

MuleClient client = new MuleClient();


MuleMessage result = client.send("myEndpoint", "some data", null);

if(result instanceof MuleMessageCollection)


{
MuleMessageCollection resultsCollection = (MuleMessageCollection)result;
System.out.println("Number of messages: " + resultsCollection.size());
MuleMessage[] messages = resultsCollection.getMessagesAsArray();
}

Future Results
The Mule client allows you to make synchronous calls without blocking by using the sendAsync() method,
which returns a FutureMessageResult that can be queried later.

MuleClient client = new MuleClient();


FutureMessageResult result = client.sendAsync("http://localhost:8881",
"Message Payload", null);
//Do some more stuff here

if(result.isready())
{
Object payload = result.getMessage().getPayload();
}

The FutureMessageResult returned is a placeholder for the real result message when the call returns.
By using a future result, you can continue with other tasks while the remote call executes. Calling
getMessage() will block until the call returns. Optionally, you can specify a timeout of how long to wait
(as shown in the example). You can also check if the call has returned using result.isReady().

Using the Remote Dispatcher


The Mule client can connect to, send, and receive messages from a remote Mule server through a
firewall using a remote dispatcher. This should only be used when the remote service being invoked does
not expose an endpoint accessible by the Mule client. Note that there is performance overhead when
using the remote dispatcher, because all requests and responses are serialized, sent to the server, and
deserialized before the real invocation is made from within the firewall.

To use the remote dispatcher, you enable it on the server instance by configuring the remote dispatcher
agent. You can ensure that the server can handle both asynchronous and synchronous calls by setting
the synchronous attribute to true. You can also set the remoteSyncTimeout setting, although often it is
better to control it at the MuleClient call level, as each call might have a different timeout requirement.

<client:remote-dispatcher-agent>
<client:remote-endpoint address="http://localhost:81" synchronous="true" remoteSyncTimeout="10000"/
>
</client:remote-dispatcher-agent>

On the client side, you can now communicate with the remote server via the remote dispatcher agent.
For example:

MuleClient client = new MuleClient();


RemoteDispatcher dispatcher = client.getRemoteDispatcher("http://localhost:81");

Document generated by Confluence on Oct 27, 2008 21:07 Page 450


MuleMessage result = dispatcher.sendToRemoteComponent("StockManager", "give me the price of XXX",
null);

StockQuote sq = (StockQuote)result.getPayload();

The Mule client executes the StockManager component on a remote Mule server, returning the result to
the client. Mule handles all the call marshalling. The first null argument is an optional string of comma-
separated transformers to use on the result message. The second null argument contains properties
associated with the request.

If you do not want to wait for the result to be returned from the remote server, you can use the
sendAsyncToRemoteComponent() method, which returns a FutureMessageResult:

MuleClient client = new MuleClient();


RemoteDispatcher dispatcher = client.getRemoteDispatcher("tcp://localhost:60504");
FutureMessageResult result = dispatcher.sendAsyncToRemoteComponent("StockManager", null, "give me
the price of XXX", null);

//do some other stuff

StockQuote sq = (StockQuote)result.getMessage(1000).getPayload();

Specifying the Wire Format

You can specify the wire format to use for dispatching messages by configuring one of the following:

• <xml-wire-format>: uses the XML-Object transformers


• <serialization-wire-format>: uses the ByteArray-Serializable transformers
• <custom-wire-format>: set the class attribute to the class file of the transformer you want to use.

If you do not set the wire format, the serialization format is used. For more information on transformers,
see Using Transformers.

For example:

<client:remote-dispatcher-agent>
<client:remote-endpoint address="http://localhost:81" synchronous="true" remoteSyncTimeout="10000"/
>
<client:xml-wire-format/>
</client:remote-dispatcher-agent>

Sending Messages to Components Directly


The Mule client provides a convenient way to send a message directly to a component without needing
to use a transport when the Mule server is running in the same classloader as the client. This approach
can be very useful in testing as well as triggering messages from a JSP page or JavaScript. For example,
to dispatch a message directly to your stock quote component called StockManager, you would do the
following:

MuleClient client = new MuleClient();


MuleMessage result = client.sendDirect("StockManager", null, "give me the price of XXX", null);

StockQuote sq = (StockQuote)result.getPayload();

Note that the call is sendDirect, which tells the Mule client to go directly to the component and not
through a transport. You can specify a comma-separated list of transformers to use in the second
argument of this call.

Document generated by Confluence on Oct 27, 2008 21:07 Page 451


Using the Mule RESTpack

This page last changed on Oct 10, 2008 by jackie.wheeler.

Using the Mule RESTpack


[ Understanding REST ] [ Architecting RESTful Applications ] [ Mule REST Connectors ]

The Mule RESTpack is geared toward helping you build RESTful applications with Mule. REST is a very
powerful concept that enables scalable, decentralized growth.

Understanding REST
REST can be confusing. For an introduction to its advantages, disadvantages, and notes on using it, see
Making Sense of REST.

Architecting RESTful Applications


Mule is well suited for building RESTful applications, as it can easily bridge between the web and nearly
anything else in your enterprise. For more information on architecture considerations when using REST
with Mule, see Architecting RESTful HTTP applications.

Mule REST Connectors


The Mule RESTpack uses a series of connectors for building RESTful services. This section describes each
connector and links to more information on downloading and using them.

HTTP Connector

The Mule HTTP Transport contains most of the basic HTTP functionality that the connectors in the
RESTpack build on, including:

• Client and Server HTTP transport


• Support for running over a Servlet
• Support for polling resources via the PollingHttpMessageReceiver

The Mule HTTP transport is included with your Mule installation.

Apache Abdera Connector

The Mule Abdera connector makes it possible to integrate easily with Atom feeds and Atom Publishing
Protocol servers via the Apache Abdera project. The connector supports consuming Atom feeds,
publishing of Atom entries and server side AtomPub service.

To download and learn about using the Mule Abdera connector, go to the MuleForge Abdera page.

Jersey JAX-RS Connector

Jersey is the open source JAX-RS (JSR 311) reference implementation for building RESTful web services
via simple annotations. The Mule Jersey connector enables developers to embed these JAX-RS services
inside of Mule.

To download and learn about using the Mule Jersey connector, go to the MuleForge Jersey page.

Restlet Connector

Restlet is an open source REST framework, providing a powerful abstraction for building and consuming
RESTful services. The Mule Restlet connector facilitates the deployment and consumption of RESTful

Document generated by Confluence on Oct 27, 2008 21:07 Page 452


services using the Restlet APIs inside of Mule. In addition, the transport exploits Restlet's simple URL
routing engine to provide RESTful routing of messages to Mule services.

To download and learn about using the Restlet connector, go to the MuleForge Restlet page.

Document generated by Confluence on Oct 27, 2008 21:07 Page 453


Architecting RESTful HTTP applications

This page last changed on Oct 10, 2008 by jackie.wheeler.

Architecting RESTful HTTP Applications


[ Modeling services and data ] [ Reliability ] [ Security ]

Modeling services and data


An important step in achieving the benefits REST has to offer is modeling your services and data
correctly. It is very different from the typical RPC (Remote Procedure Call) mindset that most people are
used to. It is however similar to object-oriented programming.

Imagine that each resource is an object. You can then perform the following operations on this object:

Operation Description

Get() Get a representation of the resource. This is a


safe operation. It does not change the state of the
resource.

Post(Representation) Perform an unsafe operation that changes the


state of the server and puts a new resources
somewhere or modifies an existing resource.

Put(Representation) Store a new representation of the resource.

Delete() Delete the resource

Head() Get metadata about the resource. This is a safe


operation. It does not change the state of the
resource

Options() Get information about which operations are


available to be used on the resource. This is a
safe operation. It does not change the state of the
resource.

Modeling your application can be broken down into roughly four steps:
1. Decompose your application into resources whose state you wish to access and modify.
2. Define the applicable operations of each resource
3. Give each resource a URI
4. Decide how to represent each resource

Decompose the application into resources

Anything inside your application can be a resource. So how do you decide what resources to create?
Typically you'll want to make a piece of your application a resource if:
1. You wish to link to that specific piece of data
2. You wish to modify or delete the data the resource represents

The prototypical example is often a CRUD based application. For instance, you may have a database of
orders which need to be fulfilled. If this was to be broken down into resources, you may have a "/orders"
URI for listing the contents of the orders database. You would also have an individual resource for each
order (i.e. "/order/1") which could be accessed, modified or deleted.

Document generated by Confluence on Oct 27, 2008 21:07 Page 454


Give Each Resource a URI

Define the applicable methods of each resource

After (or while) breaking down your application into resources, you must determine which HTTP methods
you wish to support. It is very important that you respect the semantics of each HTTP method. GET,
HEAD, and OPTIONS are safe. PUT and DELETE are idempotent. POST is unsafe and may have side-
effects.

See the section on reliability for an explanation of how to apply these methods to build a robust service.

Decide how to represent each resource

There are many different data types you can choose to represent your resource. Many times you will not
have to think about what data type to use as it will be obvious. For instance, if you store an image of a
product in the database - the typical way to serve that would be return an image type, i.e. "image/jpeg".
A structured data type such as XML would make no sense.

For structured data, the choices are more complex. There is XML, specific formats of XML such as Atom,
JSON, XHTML, CSV, etc. On top of this, you may wish to multiple different representations of the resource
as well.

The most common formats for structured data are XML, Atom, JSON and XHTML. The table below gives a
quick summary of these formats and when you may wish to consider applying them.

XML
XML is the universal data format. Every system can understand it. It also has advanced tools for
modeling, parsing and querying such as XML schema, XPath, and XQuery. It is typically slower than other
formats as it is verbose, but can perform well for most applications.

Atom
Atom is a standard XML format for syndication. An Atom feed contains a series of entries. Each entry has
a place for a title, last update time, summary, content, authors, and more. It also allows extensions for
proprietary fields. Atom inherits all the benefits of XML, but introduces another very important property
- it is universally understood. If a user or machine understands Atom, it automatically understands your
application to some degree.

JSON
JSON stands for JavaScript Object Notation. One of its great advantages is that it is itself JavaScript. This
means that it becomes trivial to parse and use JSON inside a JavaScript application - especially when
compared to navigating XML. It is also extremely simple. It does not have the concept of namespaces nor
does it have modeling tools XML schema.

XHTML
Over the recent years Microformats have arise as a very powerful alternative to XML based data.
Microformats create a standard XHTML representation for data which allows it to both be parsed reliably
by machines and be used inside a web browser. Consider using a data format whenever possible as it
often allows you to tackle two birds with one stone.

Reliability
An important part of distributed system design is dealing with problems that occur in between the client
and the server it is talking to. Some examples of this include proxies going down or connections being
dropped.

HTTP does not have an inbuilt mechanism for achieving reliable deliveries of messages. Instead, reliability
is typically achieved through idempotent operations. An idempotent operation is one that can be repeated
over and over and still yield the same result. In the case of HTTP, this means that a message can be sent
again and again until confirmation is received. Even if the message is received twice, the ultimate result,
changing the resource state, will be the same.

Let us say that you want to update a resource which represents a customer - maybe they've changed
their address. In this case you would want to PUT the new representation to this resource which contains

Document generated by Confluence on Oct 27, 2008 21:07 Page 455


the new address. If a connection drops and an error occurs, you can simply try putting the message
again as the operation is idempotent.

The same concept can be applied to the DELETE operation. The DELETE request can simply be repeated it
succeeds.

Creating new resources is trickier to do reliably in a RESTful manner. Typically resources are created
with a POST message. A simple example might go like this: you create a new order by POSTing the
representation to the "/orders" resource. You would then be redirected to the new resource. What
happens if the connection drops here though? You are not sure if the new order resource has been
created. If you simply retry the POST you could end up with two orders, which would be less than idea.
The trick is to use a two step process. First, the client must do a POST to the "/orders" resource with no
data. The server will then respond with a Location header which contains a new URL that the order can be
PUT to.

TODO: put code example in confluence

Now reliability can be achieved by simply repeating each step until it succeeds. If the POST fails and the
client submits the POST again, the worst that can happen is the creation of a URL that is not used. These
URLs can either be ignored or they can be expired. If the PUT fails, it can simply be retried.

There is a limitation of the above approach for reliability though - message ordering is not preserved.
To preserve message ordering, you will have to develop application specific extensions or move to a
technology like HTTPR or WS-ReliableMessaging.

Security
There are many options to provide security to your application depending on your requirements.

Authentication

HTTP has built in support for authentication. The "basic" and "digest" mechanisms are the most
commonly used authentication mechanisms. Basic authentication passes a username and password
in plain text to the server. Because of this, it should only be used over an SSL connection. Digest
authentication sends the username as plain text and an MD5 checksum of the password.

Another option for authentication is to use client side certificates with SSL. If the server has a copy of the
client's public key, it can verify that the messages were in encrypted with that key, and hence from the
client.

Privacy

The most often used mechanism for message privacy is SSL. It is efficient and widely supported. Other
alternatives include the message level security mechanisms mentioned below.

Limitations of SSL

There are two primary limitations of using SSL. First, it does not work well with intermediaries. Imagine
a situation where a gateway handles the SSL processing. In this case, your application will receive none
of the SSL information. This means you cannot use SSL certificates to verify who the client/server is
and that there may be unsecured routes along the network. Second, there is limited ability for other
authentication tokens, such as SAML.

Message level security

If you need message level security XML Signature/Encryption is one of your few options. This does
constrain you to use an XML data format though.

Another option that has been discussed is S/MIME. This has many disadvantages to it though which are
discussed here.

Document generated by Confluence on Oct 27, 2008 21:07 Page 456


Making Sense of REST

This page last changed on Oct 10, 2008 by jackie.wheeler.

Making Sense of REST


[ Advantages of RESTful Architectures and Implementations ] [ Disadvantages of RESTful Architectures
and Implementations ] [ Notes on Building Your Application with WS-* or RESTful HTTP ]

REST is the formalized architecture of HTTP based on the concepts of resources, links, and a uniform
interface. REST can be a somewhat confusing subject. Even the very acronym itself, which stands for
"Representation State Transfer", is a little obtuse. Luckily, there are some great resources out there.

One of the best resources out there is RESTful Web Services by Leonard Richardson and Sam Ruby.
It explains REST as well as many of the practical issues surrounding the issue of building RESTful web
services in great detail. You can find it at your local bookstore, Amazon, or online at O'Reilly's Safari
website.

For a good online (and free) introduction, Stefan Tilkov has written two excellent articles: A Brief
Introduction to REST and Addressing Doubts about REST.

And of course, there is the authoritative, but dense, thesis by Roy T. Fielding

You should familiarize yourself with the concepts of REST before continuing to read this page.

Advantages of RESTful Architectures and Implementations


Following is a discussion of some key benefits of RESTful architectures and implementations. Note that
while many of these items are benefits of the REST architectural style, many are related to HTTP, which is
a specific implementation of the REST concepts.

REST Is the Architecture of the Web

RESTful applications can be easily integrated in the web to great benefit. Your resources can be linked to
and from web pages. You can take advantage of Microformats to handle both UI and data related issues.
You can also take advantage of the existing web infrastructure and ecosystem: proxies, caches, browsers/
clients, load balancers, web standards, and more.

Increased Scalability

The web is the largest distributed system in the world. This is enabled by the inherent constraints in
RESTful architectures. For example, RESTful interactions are stateless. The server does not have to worry
about managing state between requests, as all state is kept on the client. Also, caching semantics are
built into the protocol. You can enable caching on any RESTful application without any special knowledge
since all interactions are based on the uniform interface.

Evolvability

All resources are identified by URIs. URIs provide a simple way to deal with the evolution of a system
as they can be used to partition servers and manage versioning. All one needs is a proxy to do
redirects based on the URI. Because there is no need to inspect the actual HTTP message payload, the
performance impact of this is negligible.

RESTful systems are based on hypermedia, so they provide links between different resources. Clients are
responsible for navigating the hypertext links. For instance, they browse to an order resource. They may
then browse to different items in the order via a link. If you need to direct a client to a different server or
move a server, simply change the link. Because the client knows the entry point link, it can still navigate
to the various items as your system evolves.

Document generated by Confluence on Oct 27, 2008 21:07 Page 457


Disadvantages of RESTful Architectures and Implementations
This section describes the disadvantages to the REST approach.

Not Applicable to Many Message-oriented Situations

RESTful systems are fundamentally client-server based and are ill-suited to a number of message-
oriented scenarios. Publish-subscribe scenarios are one example. As there is no mechanism inside HTTP
for asynchronous responses, you often have to set up a second HTTP server if you want to receive
asynchronous replies.

Performance

HTTP is fundamentally a text-based protocol and is not geared toward performance. While it is not slow,
there are other protocols that may be more suitable for situations that are very performance-sensitive.

Transactions

HTTP does not include the concept of transactions. It is possible to model a transaction as an HTTP
resource, but it will not be as efficient as protocols such as JMS. It is also not appropriate to use
transactions with HTTP in many cases, as it can potentially consume many resources across multiple
servers if transactions are long lived.

Notes on Building Your Application with WS-* or RESTful HTTP


WS-* represents common names for the set of standards that encompass SOAP, WSDL, WS-Addressing,
WS-Security, WS-ReliableMessaging, WS-Policy, and many others. One cannot compare WS-* and REST
directly, as WS-* is a set of technology standards and REST is an architectural style. However, you can
compare the actual pieces of software that help you build RESTful systems and traditional web services.

Go Beyond XML

SOAP/WSDL web services are XML based. To create messages that encapsulate binary data, you must
use standards such as MTOM that wrap the XML in a MIME message, which often ends up being extra
work. With HTTP, resources can be any media.

Transport Neutrality

One of the great benefits of SOAP is that it is transport neutral. If this is a requirement for your
application, RESTful services are probably not the way to go.

Reliability

The RESTful and WS-* approaches to reliability differ tremendously.


The WS-* approach is based on WS-ReliableMessaging (WS-RM). WS-RM implements a TCP-like
system of acknowledgments: messages are sent from server A to server B, and server B then sends
acknowledgments back. If server A never receives an acknowledgment for a message, it eventually
resends it. WS-ReliableMessaging implementations (not the protocol) can also ensure messages are
delivered in the correct order.

RESTful systems typically achieve reliability through idempotent operations. See the section on RESTful
reliability for more information.

Security

The RESTful and WS-* approaches to security also differ greatly. WS-* advocates a layered approach. It
creates WS-Security for encryption and authorization, it uses WS-Trust for token exchange, and it uses
WS-SecureConversation to create more efficient security tokens for encrypted communication. These

Document generated by Confluence on Oct 27, 2008 21:07 Page 458


approaches make sense if you need message-oriented, transport-neutral systems. However, many WS-*
systems make use of the underlying transport security (such as SSL) for its simplicity and performance.

RESTful systems can achieve security through both the transport layer (SSL) and a variety of message-
level mechanisms. Support for different security scenarios is arguably one of the reasons to choose WS-
* instead of REST for some specific (but rare) scenarios. See the section on RESTful security for more
information on how to build secure RESTful services.

Document generated by Confluence on Oct 27, 2008 21:07 Page 459


Using Transformers

This page last changed on Oct 06, 2008 by jackie.wheeler.

Using Transformers
[ Overview ] [ Configuring Transformers ] [ Types of Transformers ] [ Chaining Transformers ] [ Standard
Transformers Reference ] [ Transformation Best Practices ]

This page is ready for review

Transformers convert message payloads as they are transported between services.

Overview
In Mule 2.0, there are both standard and custom transformers. Standard transformers are configured
with XML that conforms to a Mule configuration schema. Custom transformers are configured using the
fully qualified class name of the transformer.

Standard Transformers

Standard transformers are easier to use than custom transformers. You don't need to know the Java
name of the transformer, and all properties are explicitly declared in a Mule configuration schema.

Here is an example of declaring the standard Append String transformer, which appends string text to the
original message payload:

<append-string-transformer name="myAppender" message=" ... that's good to know!"/>

If the original message payload was the string "foo", the transformer above would convert the string to
"foo ... that's good to know!".

For a list of the standard transformers, see Standard Transformers Reference below.

Transport-specific Transformers

Many transports and modules have their own transformers, such as the ObjectToJMSMessage for the JMS
transport. For information on transport transformers, see Available Transports and click a transport name
to see its transformers.

Custom Transformers

Custom transformers are typically user-defined transformers. Custom transformers are useful when the
transformer has not or will not be added to a Mule configuration schema, as is often the case with user-
defined transformers. They require more knowledge about the transformer, such as the transformer class
name and properties.

For example, if we were to declare the Append String transformer above as a custom transformer, it
would look like this:

<custom-transformer name="myAppender" class="org.mule.transformer.simple.StringAppendTransformer">


<spring:property name="message" value=" ... that's good to know!"/>
</custom-transformer>

All Mule transformers must implement org.mule.api.transformer.Transformer . There is an abstract


transformer implementation, AbstractTransformer , that defines methods for controlling the object types
this transformer supports and validates the expected return type, leaving the developer to implement a
single transform() method.

For more information, see Creating Custom Transformers.

Document generated by Confluence on Oct 27, 2008 21:07 Page 460


Configuring Transformers
You can configure a transformer globally or locally. You configure a local transformer right on the
endpoint. You configure a global transformer before the <model> element in your Mule configuration
properties and then can refer to the transformer in multiple places. For example, the following code
defines two global transformers, which are referenced from two different services:

<xm:xml-to-object-transformer name="XMLToExceptionBean"
returnClass="org.mule.example.errorhandler.ExceptionBean"/>
<custom-transformer name="ExceptionBeanToErrorMessage"
class="org.mule.example.errorhandler.ExceptionBeanToErrorMessage"
returnClass="org.mule.example.errorhandler.ErrorMessage"/>

...
<model name="errorhandler-test">
<service name="Error Manager">
<inbound>
<inbound-endpoint address="file://./test-data/in" transformer-refs="XMLToExceptionBean
ExceptionBeanToErrorMessage">
<file:filename-wildcard-filter pattern="*.xml" />
</inbound-endpoint>
</inbound>
...
</service>
...
<service name="Business Error Manager">
<inbound>
<inbound-endpoint address="jms://exception.queue" transformer-refs="JMSMessageToObject
XMLToExceptionBean ExceptionBeanToErrorMessage" />
</inbound>
...
</service>
</model>

This example uses the transformer-refs attribute on the endpoint to specify the transformers to use.
This is a fast way of specifying global transformers, but if you want to enter a local transformer or a mix
of local and global transformers, you must use the <transformer> element instead. For example, if only
one of the transformers were defined globally, you would refer to the global transformer and configure
the local transformer as follows:

<service name="Error Manager">


<inbound>
<inbound-endpoint address="file://./test-data/in">
<transformer ref="XMLToExceptionBean/>
<custom-transformer name="ExceptionBeanToErrorMessage"
class="org.mule.example.errorhandler.ExceptionBeanToErrorMessage"
returnClass="org.mule.example.errorhandler.ErrorMessage" />
<file:filename-wildcard-filter pattern="*.xml" />
</inbound-endpoint>
</inbound>
...
</service>

Types of Transformers
The above examples illustrate configuring inbound transformers, which are applied to the message after
it is received on the inbound endpoint and before it is passed to the service's component. You specify
inbound transformers under the <inbound-endpoint> element.

You can also specify an outbound transformer in exactly the same way except on the routers in the
<outbound> element, in which case the message is transformed after it has been processed by the
service's component but before it has been sent to the outbound endpoint specified by that router. For
example:

Document generated by Confluence on Oct 27, 2008 21:07 Page 461


<outbound>
<filtering-router transformer-refs="ErrorMessageToException">
<file:outbound-endpoint path="test-data/exceptions" outputPattern="Exception-[UUID].xml"
transformer-refs=
"ErrorMessageToExceptionBean ExceptionBeanToXML" />
</filtering-router>
...
</outbound>

Lastly, you can specify a response transformer, which converts message payloads on their way from the
service to the caller. To configure a response transformer, you use the responseTransformers-refs
attribute on the router, or you can use the <response-transformer> element. For example:

<inbound>
<vm:inbound-endpoint path="my.inbound.endpoint" responseTransformer-refs="myAppender"/>
</inbound>
<some-component/>

In this example, the response message from "some-component" is transformed using the "myAppender"
transformer before being returned to the caller.

Chaining Transformers
You can chain transformers together so that the output from one transformer becomes the input for the
next. To chain transformers, you create a space-separated list of transformers in the transformer-refs
or responseTransformer-refs attributes or by creating multiple <transformer> elements as shown
above.

For example, this chain ultimately converts from a ByteArray to InputStream:

transformer-refs="ByteArrayToString StringToObject ObjectToInputStream"

You could also configure this as follows:

<transformer ref="ByteArrayToString"/>
<transformer ref="StringToObject"/>
<transformer ref="ObjectToInputStream"/>

Standard Transformers Reference


Following are the standard transformers available with Mule. Individual transports may also have their
own transformer types, which are documented with the transports themselves. For more information, see
Available Transports. For a complete configuration reference to standard transformers, see Transformers
Configuration Reference.

XML

The XML transformers are in the org.mule.module.xml.transformer package.

Transformer Description

XmlToObject <-> ObjectToXml Converts XML to a Java object and back again
using XStream.

XSLT Transforms XML payloads using XSL.

DomToXml <-> XmlToDom Converts DOM objects to XML and back again.

JXPath Queries and extracts object graphs using XPath


expressions.

Document generated by Confluence on Oct 27, 2008 21:07 Page 462


XmlPrettyPrinter Allows you to output the XML with controlled
formatting, including trimming white space and
specifying the indent.

Scripting

The Scripting transformer transforms objects using scripting, such as JavaScript or Groovy scripts. This
transformer is in the org.mule.module.scripting.transformer package.

Encryption

The encryption transformers are in the org.mule.transformer.encryption package.

Transformer Description

Encryption <-> Decryption A pair of transformers that use a configured


EncryptionStrategy implementation to encrypt and
decrypt data.

Compression

The compression transformers are in the org.mule.transformer.compression package. They do not require
any special configuration.

Transformer Description

GZipCompressTransformer <-> A pair of transformers that compress and


GZipUncompressTransformer uncompress data.

Encoding

The encoding transformers are in the org.mule.transformer.codec package. They do not require any
special configuration.

Transformer Description

Base64Encoder <-> Base64Decoder A pair of transformers that convert to and from


Base 64 encoding.

XMLEntityEncoder <-> XMLEntityDecoder A pair of transformers that convert to and from


XML entity encoding.

Basic

The basic transformers are in the org.mule.transformer.simple package. They do not require any special
configuration. For details on these transformers, see Transformers Configuration Reference.

Transformer Description

ByteArrayToHexString <-> A pair of transformers that convert between byte


HexStringToByteArray arrays and hex strings.

ByteArrayToMuleMessage <-> A pair of transformers that convert between byte


MuleMessageToByteArray arrays and Mule messages.

Document generated by Confluence on Oct 27, 2008 21:07 Page 463


ByteArrayToObject <-> A pair of transformers that convert between
ObjectToByteArray byte arrays and objects. If the byte array is not
serialized, ByteArrayToObject returns a String
created from the bytes as the returnType on the
transformer.

ByteArrayToSerializable <-> A pair of transformers that serialize and


SerializableToByteArray deserialize objects.

ExpressionTransformer Evaluates one or more expressions on the current


message and return the results as an Array.

MessagePropertiesTransformer A configurable message transformer that allows


users to add, overwrite, and delete properties on
the current message.

ObjectArrayToString <-> A pair of transformers that convert between


StringToObjectArray object arrays and strings.

ObjectToInputStream Converts serializable objects to an input stream


but treats java.lang.String differently by
converting to bytes using the String.getBytes()
method.

ObjectToOutputHandler Converts a byte array into a String.

ObjectToString Returns human-readable output for various kinds


of objects. Useful for debugging.

StringAppendTransformer Appends a string to an existing string.

StringToObjectArray Converts a string to an object array.

Transformation Best Practices


Mule has an efficient transformation mechanism. Transformers are applied to inbound or outbound
endpoints, and the data is transformed just before it is sent from a service or just before it is received by
another service. Transformers can be concatenated, so it is simple to perform multiple transformations on
data in transit.

There is no one standard approach for how and where transformations should occur. Some maintain that
because transformation should always be applied on inbound/outbound data, transformations should be
available as part of the enterprise service bus instead of inside the service components. This approach
matches the concepts of Aspect Oriented Programming (AOP). Others conclude that it is far more efficient
to encode the transformation logic into the service components themselves. In the second case, however,
there is no distinction between code that is related to a business process and code that is generic enough
to be reused, which contradicts the philosophy of an ESB.

While there is no industry best practice, MuleSource recommends that developers examine their
transformation logic to see if it will always be used (AOP) or if it is specific to a business process. In
general, if it will always be used, you should use a transformer, and if it is specific to a single business
process, it should be part of the service component.

References:
http://msdn2.microsoft.com/en-us/library/aa480061.aspx
http://blogs.ittoolbox.com/eai/applications/archives/transformation-in-a-soa-12186

Document generated by Confluence on Oct 27, 2008 21:07 Page 464


DomToXml Transformer

This page last changed on Oct 06, 2008 by jackie.wheeler.

DOM/XML Transformers
This page is ready for review

The DomToXml transformer converts DOM objects to XML, and the XmlToDom transformer converts
XML strings to DOM objects. These transformers support the standard transformer attributes plus the
following:

Dom To Xml Transformer

Attributes of <dom-to-xml-transformer...>

Name Type Required Default Description

outputEncoding string no The encoding


to use for the
resulting XML/
Text.

Xml To Dom Transformer

Attributes of <xml-to-dom-transformer...>

Name Type Required Default Description

outputEncoding string no The encoding


to use for the
resulting XML/
Text.

Example
To use the DOM/XML transformers, you add them to your Mule XML configuration as follows:

<xm:dom-to-xml-transformer name="DomToXml"/>
<xm:xml-to-dom-transformer name="xmlToDom" returnClass="org.w3c.dom.Document" />

You can then reference them by name from endpoints:

<vm:inbound-endpoint name="testEndpoint" path="another.queue" connector-ref="vmConnector1"


transformer-refs="DomToXml" />
...
<vm:outbound-endpoint ref="xml-dom-out" transformer-refs="xmlToDom" />
...

Document generated by Confluence on Oct 27, 2008 21:07 Page 465


JXPath Transformer

This page last changed on Jul 10, 2008 by jackie.wheeler.

JXPath Transformer
The JXPath transformer evaluates an XPath expression against the current message and returns the
result. By default, a single result will be returned. If multiple values are expected, set the singleResult
property to false, which will return a list of values. This property is available for strings only (not XML).

You configure the JXPath transformer as follows:

<transformers>
<transformer name="invoice" className="org.mule.transformers.xml.JXPathExtractor">
<properties>
<property name="expression" value="/book/title"/>
<property name="singleResult" value="false"/>
</properties>
</transformer>

Document generated by Confluence on Oct 27, 2008 21:07 Page 466


Transformers Configuration Reference

This page last changed on Oct 22, 2008 by jackie.wheeler.

Transformers Configuration Reference


[ Transformer ] [ Auto Transformer ] [ Custom Transformer ] [ Message Properties Transformer ]
[ No Action Transformer ] [ Base64 Encoder Transformer ] [ Base64 Decoder Transformer ] [ Xml
Entity Encoder Transformer ] [ Xml Entity Decoder Transformer ] [ Gzip Compress Transformer ] [
Gzip Uncompress Transformer ] [ Byte Array To Hex String Transformer ] [ Hex String To Byte Array
Transformer ] [ Byte Array To Object Transformer ] [ Object To Byte Array Transformer ] [ Object To
String Transformer ] [ Byte Array To Serializable Transformer ] [ Serializable To Byte Array Transformer ]
[ Byte Array To String Transformer ] [ String To Byte Array Transformer ] [ Append String Transformer ] [
Encrypt Transformer ] [ Decrypt Transformer ] [ Expression Transformer ]

Transformer
A reference to a transformer defined elsewhere.

Attributes of <transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies the


transformer
so that other
elements can
reference it.
Required if the
transformer is
defined at the
global level.

returnClass class name no The class of


the message
generated by
the transformer.
This is used if
transformers
are auto-
selected (which
is somewhat
incomplete at the
moment).

ignoreBadInput boolean no Many transformers


only accept
certain classes.
Such transformers
are never called
with inappropriate
input (whatever
the value of this
attribute). If
a transformer
forms part of a
chain and cannot
accept the current
message class,

Document generated by Confluence on Oct 27, 2008 21:07 Page 467


then this flag
controls whether
the remaining
part of the chain
is evaluated. If
true, the next
transformer is
called. If false
the chain ends,
keeping the result
generated up to
that point.

ref name (no spaces) no The name of the


transformer to
use.

Auto Transformer
A transformer that uses the transform discovery mechanism to convert the message payload. This
transformer works much better when transforming custom object types rather than Java types, because
there is less chance for ambiguity.

Attributes of <auto-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies the


transformer
so that other
elements can
reference it.
Required if the
transformer is
defined at the
global level.

returnClass class name no The class of


the message
generated by
the transformer.
This is used if
transformers
are auto-
selected (which
is somewhat
incomplete at the
moment).

ignoreBadInput boolean no Many transformers


only accept
certain classes.
Such transformers
are never called
with inappropriate
input (whatever
the value of this
attribute). If
a transformer
forms part of a
chain and cannot

Document generated by Confluence on Oct 27, 2008 21:07 Page 468


accept the current
message class,
then this flag
controls whether
the remaining
part of the chain
is evaluated. If
true, the next
transformer is
called. If false
the chain ends,
keeping the result
generated up to
that point.

Custom Transformer
A user-implemented transformer.

Attributes of <custom-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies the


transformer
so that other
elements can
reference it.
Required if the
transformer is
defined at the
global level.

returnClass class name no The class of


the message
generated by
the transformer.
This is used if
transformers
are auto-
selected (which
is somewhat
incomplete at the
moment).

ignoreBadInput boolean no Many transformers


only accept
certain classes.
Such transformers
are never called
with inappropriate
input (whatever
the value of this
attribute). If
a transformer
forms part of a
chain and cannot
accept the current
message class,
then this flag
controls whether

Document generated by Confluence on Oct 27, 2008 21:07 Page 469


the remaining
part of the chain
is evaluated. If
true, the next
transformer is
called. If false
the chain ends,
keeping the result
generated up to
that point.

class class name no An


implementation of
the Transformer
interface.

Child Elements of <custom-transformer...>

Name Cardinality Description

spring:property 0..*

Message Properties Transformer


A transformer that can add or delete message properties.

Attributes of <message-properties-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies the


transformer
so that other
elements can
reference it.
Required if the
transformer is
defined at the
global level.

returnClass class name no The class of


the message
generated by
the transformer.
This is used if
transformers
are auto-
selected (which
is somewhat
incomplete at the
moment).

ignoreBadInput boolean no Many transformers


only accept
certain classes.
Such transformers
are never called
with inappropriate

Document generated by Confluence on Oct 27, 2008 21:07 Page 470


input (whatever
the value of this
attribute). If
a transformer
forms part of a
chain and cannot
accept the current
message class,
then this flag
controls whether
the remaining
part of the chain
is evaluated. If
true, the next
transformer is
called. If false
the chain ends,
keeping the result
generated up to
that point.

overwrite boolean no true If false, a property


is not added if
the message
already contains a
property with that
name.

Child Elements of <message-properties-transformer...>

Name Cardinality Description

delete-message-property 0..* Delete a message property.

add-message-property 0..* Add a message property.

rename-message-property 0..* Rename a message property.

add-message-properties 0..1 Add a set of message properties.

No Action Transformer
A transformer that has no effect.

Attributes of <no-action-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies the


transformer
so that other
elements can
reference it.
Required if the
transformer is
defined at the
global level.

Document generated by Confluence on Oct 27, 2008 21:07 Page 471


returnClass class name no The class of
the message
generated by
the transformer.
This is used if
transformers
are auto-
selected (which
is somewhat
incomplete at the
moment).

ignoreBadInput boolean no Many transformers


only accept
certain classes.
Such transformers
are never called
with inappropriate
input (whatever
the value of this
attribute). If
a transformer
forms part of a
chain and cannot
accept the current
message class,
then this flag
controls whether
the remaining
part of the chain
is evaluated. If
true, the next
transformer is
called. If false
the chain ends,
keeping the result
generated up to
that point.

Base64 Encoder Transformer


A transformer that base64 encodes a string or byte array message.

Attributes of <base64-encoder-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies the


transformer
so that other
elements can
reference it.
Required if the
transformer is
defined at the
global level.

returnClass class name no The class of


the message

Document generated by Confluence on Oct 27, 2008 21:07 Page 472


generated by
the transformer.
This is used if
transformers
are auto-
selected (which
is somewhat
incomplete at the
moment).

ignoreBadInput boolean no Many transformers


only accept
certain classes.
Such transformers
are never called
with inappropriate
input (whatever
the value of this
attribute). If
a transformer
forms part of a
chain and cannot
accept the current
message class,
then this flag
controls whether
the remaining
part of the chain
is evaluated. If
true, the next
transformer is
called. If false
the chain ends,
keeping the result
generated up to
that point.

Base64 Decoder Transformer


A transformer that base64 decodes a message to give an array of bytes.

Attributes of <base64-decoder-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies the


transformer
so that other
elements can
reference it.
Required if the
transformer is
defined at the
global level.

returnClass class name no The class of


the message
generated by
the transformer.
This is used if
transformers

Document generated by Confluence on Oct 27, 2008 21:07 Page 473


are auto-
selected (which
is somewhat
incomplete at the
moment).

ignoreBadInput boolean no Many transformers


only accept
certain classes.
Such transformers
are never called
with inappropriate
input (whatever
the value of this
attribute). If
a transformer
forms part of a
chain and cannot
accept the current
message class,
then this flag
controls whether
the remaining
part of the chain
is evaluated. If
true, the next
transformer is
called. If false
the chain ends,
keeping the result
generated up to
that point.

Xml Entity Encoder Transformer


A transformer that encodes a string using XML entities.

Attributes of <xml-entity-encoder-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies the


transformer
so that other
elements can
reference it.
Required if the
transformer is
defined at the
global level.

returnClass class name no The class of


the message
generated by
the transformer.
This is used if
transformers
are auto-
selected (which
is somewhat

Document generated by Confluence on Oct 27, 2008 21:07 Page 474


incomplete at the
moment).

ignoreBadInput boolean no Many transformers


only accept
certain classes.
Such transformers
are never called
with inappropriate
input (whatever
the value of this
attribute). If
a transformer
forms part of a
chain and cannot
accept the current
message class,
then this flag
controls whether
the remaining
part of the chain
is evaluated. If
true, the next
transformer is
called. If false
the chain ends,
keeping the result
generated up to
that point.

Xml Entity Decoder Transformer


A transformer that decodes a string containing XML entities.

Attributes of <xml-entity-decoder-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies the


transformer
so that other
elements can
reference it.
Required if the
transformer is
defined at the
global level.

returnClass class name no The class of


the message
generated by
the transformer.
This is used if
transformers
are auto-
selected (which
is somewhat
incomplete at the
moment).

Document generated by Confluence on Oct 27, 2008 21:07 Page 475


ignoreBadInput boolean no Many transformers
only accept
certain classes.
Such transformers
are never called
with inappropriate
input (whatever
the value of this
attribute). If
a transformer
forms part of a
chain and cannot
accept the current
message class,
then this flag
controls whether
the remaining
part of the chain
is evaluated. If
true, the next
transformer is
called. If false
the chain ends,
keeping the result
generated up to
that point.

Gzip Compress Transformer


A transformer that compresses a byte array using gzip.

Attributes of <gzip-compress-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies the


transformer
so that other
elements can
reference it.
Required if the
transformer is
defined at the
global level.

returnClass class name no The class of


the message
generated by
the transformer.
This is used if
transformers
are auto-
selected (which
is somewhat
incomplete at the
moment).

ignoreBadInput boolean no Many transformers


only accept

Document generated by Confluence on Oct 27, 2008 21:07 Page 476


certain classes.
Such transformers
are never called
with inappropriate
input (whatever
the value of this
attribute). If
a transformer
forms part of a
chain and cannot
accept the current
message class,
then this flag
controls whether
the remaining
part of the chain
is evaluated. If
true, the next
transformer is
called. If false
the chain ends,
keeping the result
generated up to
that point.

Gzip Uncompress Transformer


A transformer that uncompresses a byte array using gzip.

Attributes of <gzip-uncompress-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies the


transformer
so that other
elements can
reference it.
Required if the
transformer is
defined at the
global level.

returnClass class name no The class of


the message
generated by
the transformer.
This is used if
transformers
are auto-
selected (which
is somewhat
incomplete at the
moment).

ignoreBadInput boolean no Many transformers


only accept
certain classes.
Such transformers
are never called
with inappropriate

Document generated by Confluence on Oct 27, 2008 21:07 Page 477


input (whatever
the value of this
attribute). If
a transformer
forms part of a
chain and cannot
accept the current
message class,
then this flag
controls whether
the remaining
part of the chain
is evaluated. If
true, the next
transformer is
called. If false
the chain ends,
keeping the result
generated up to
that point.

Byte Array To Hex String Transformer


A transformer that converts a byte array to a string of hexadecimal digits.

Attributes of <byte-array-to-hex-string-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies the


transformer
so that other
elements can
reference it.
Required if the
transformer is
defined at the
global level.

returnClass class name no The class of


the message
generated by
the transformer.
This is used if
transformers
are auto-
selected (which
is somewhat
incomplete at the
moment).

ignoreBadInput boolean no Many transformers


only accept
certain classes.
Such transformers
are never called
with inappropriate
input (whatever
the value of this
attribute). If

Document generated by Confluence on Oct 27, 2008 21:07 Page 478


a transformer
forms part of a
chain and cannot
accept the current
message class,
then this flag
controls whether
the remaining
part of the chain
is evaluated. If
true, the next
transformer is
called. If false
the chain ends,
keeping the result
generated up to
that point.

Hex String To Byte Array Transformer


A transformer that converts a string of hexadecimal digits to a byte array.

Attributes of <hex-string-to-byte-array-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies the


transformer
so that other
elements can
reference it.
Required if the
transformer is
defined at the
global level.

returnClass class name no The class of


the message
generated by
the transformer.
This is used if
transformers
are auto-
selected (which
is somewhat
incomplete at the
moment).

ignoreBadInput boolean no Many transformers


only accept
certain classes.
Such transformers
are never called
with inappropriate
input (whatever
the value of this
attribute). If
a transformer
forms part of a
chain and cannot

Document generated by Confluence on Oct 27, 2008 21:07 Page 479


accept the current
message class,
then this flag
controls whether
the remaining
part of the chain
is evaluated. If
true, the next
transformer is
called. If false
the chain ends,
keeping the result
generated up to
that point.

Byte Array To Object Transformer


A transformer that converts a byte array to an object (either deserializing or converting to a string).

Attributes of <byte-array-to-object-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies the


transformer
so that other
elements can
reference it.
Required if the
transformer is
defined at the
global level.

returnClass class name no The class of


the message
generated by
the transformer.
This is used if
transformers
are auto-
selected (which
is somewhat
incomplete at the
moment).

ignoreBadInput boolean no Many transformers


only accept
certain classes.
Such transformers
are never called
with inappropriate
input (whatever
the value of this
attribute). If
a transformer
forms part of a
chain and cannot
accept the current
message class,
then this flag

Document generated by Confluence on Oct 27, 2008 21:07 Page 480


controls whether
the remaining
part of the chain
is evaluated. If
true, the next
transformer is
called. If false
the chain ends,
keeping the result
generated up to
that point.

Object To Byte Array Transformer


A transformer that serializes all objects except strings (which are converted using getBytes()).

Attributes of <object-to-byte-array-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies the


transformer
so that other
elements can
reference it.
Required if the
transformer is
defined at the
global level.

returnClass class name no The class of


the message
generated by
the transformer.
This is used if
transformers
are auto-
selected (which
is somewhat
incomplete at the
moment).

ignoreBadInput boolean no Many transformers


only accept
certain classes.
Such transformers
are never called
with inappropriate
input (whatever
the value of this
attribute). If
a transformer
forms part of a
chain and cannot
accept the current
message class,
then this flag
controls whether
the remaining
part of the chain

Document generated by Confluence on Oct 27, 2008 21:07 Page 481


is evaluated. If
true, the next
transformer is
called. If false
the chain ends,
keeping the result
generated up to
that point.

Object To String Transformer


A transformer that gives a human-readable description of various types (useful for debugging).

Attributes of <object-to-string-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies the


transformer
so that other
elements can
reference it.
Required if the
transformer is
defined at the
global level.

returnClass class name no The class of


the message
generated by
the transformer.
This is used if
transformers
are auto-
selected (which
is somewhat
incomplete at the
moment).

ignoreBadInput boolean no Many transformers


only accept
certain classes.
Such transformers
are never called
with inappropriate
input (whatever
the value of this
attribute). If
a transformer
forms part of a
chain and cannot
accept the current
message class,
then this flag
controls whether
the remaining
part of the chain
is evaluated. If
true, the next
transformer is

Document generated by Confluence on Oct 27, 2008 21:07 Page 482


called. If false
the chain ends,
keeping the result
generated up to
that point.

Unknown macro: {byteArrayToSerializable}

Byte Array To Serializable Transformer


A transformer that converts a byte array to an object (deserializing the object).

Attributes of <byte-array-to-serializable-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies the


transformer
so that other
elements can
reference it.
Required if the
transformer is
defined at the
global level.

returnClass class name no The class of


the message
generated by
the transformer.
This is used if
transformers
are auto-
selected (which
is somewhat
incomplete at the
moment).

ignoreBadInput boolean no Many transformers


only accept
certain classes.
Such transformers
are never called
with inappropriate
input (whatever
the value of this
attribute). If
a transformer
forms part of a
chain and cannot
accept the current
message class,
then this flag
controls whether
the remaining
part of the chain
is evaluated. If
true, the next
transformer is
called. If false
the chain ends,

Document generated by Confluence on Oct 27, 2008 21:07 Page 483


keeping the result
generated up to
that point.

Serializable To Byte Array Transformer


A transformer that converts an object to a byte array (serializing the object).

Attributes of <serializable-to-byte-array-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies the


transformer
so that other
elements can
reference it.
Required if the
transformer is
defined at the
global level.

returnClass class name no The class of


the message
generated by
the transformer.
This is used if
transformers
are auto-
selected (which
is somewhat
incomplete at the
moment).

ignoreBadInput boolean no Many transformers


only accept
certain classes.
Such transformers
are never called
with inappropriate
input (whatever
the value of this
attribute). If
a transformer
forms part of a
chain and cannot
accept the current
message class,
then this flag
controls whether
the remaining
part of the chain
is evaluated. If
true, the next
transformer is
called. If false
the chain ends,
keeping the result
generated up to
that point.

Document generated by Confluence on Oct 27, 2008 21:07 Page 484


Byte Array To String Transformer
A transformer that converts a byte array to a string.

Attributes of <byte-array-to-string-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies the


transformer
so that other
elements can
reference it.
Required if the
transformer is
defined at the
global level.

returnClass class name no The class of


the message
generated by
the transformer.
This is used if
transformers
are auto-
selected (which
is somewhat
incomplete at the
moment).

ignoreBadInput boolean no Many transformers


only accept
certain classes.
Such transformers
are never called
with inappropriate
input (whatever
the value of this
attribute). If
a transformer
forms part of a
chain and cannot
accept the current
message class,
then this flag
controls whether
the remaining
part of the chain
is evaluated. If
true, the next
transformer is
called. If false
the chain ends,
keeping the result
generated up to
that point.

String To Byte Array Transformer


A transformer that converts a string to a byte array.

Document generated by Confluence on Oct 27, 2008 21:07 Page 485


Attributes of <string-to-byte-array-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies the


transformer
so that other
elements can
reference it.
Required if the
transformer is
defined at the
global level.

returnClass class name no The class of


the message
generated by
the transformer.
This is used if
transformers
are auto-
selected (which
is somewhat
incomplete at the
moment).

ignoreBadInput boolean no Many transformers


only accept
certain classes.
Such transformers
are never called
with inappropriate
input (whatever
the value of this
attribute). If
a transformer
forms part of a
chain and cannot
accept the current
message class,
then this flag
controls whether
the remaining
part of the chain
is evaluated. If
true, the next
transformer is
called. If false
the chain ends,
keeping the result
generated up to
that point.

Append String Transformer


A transformer that appends a string to a string payload.

Document generated by Confluence on Oct 27, 2008 21:07 Page 486


Attributes of <append-string-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies the


transformer
so that other
elements can
reference it.
Required if the
transformer is
defined at the
global level.

returnClass class name no The class of


the message
generated by
the transformer.
This is used if
transformers
are auto-
selected (which
is somewhat
incomplete at the
moment).

ignoreBadInput boolean no Many transformers


only accept
certain classes.
Such transformers
are never called
with inappropriate
input (whatever
the value of this
attribute). If
a transformer
forms part of a
chain and cannot
accept the current
message class,
then this flag
controls whether
the remaining
part of the chain
is evaluated. If
true, the next
transformer is
called. If false
the chain ends,
keeping the result
generated up to
that point.

message string no The string to


append.

Encrypt Transformer
A transformer that encrypts a message.

Document generated by Confluence on Oct 27, 2008 21:07 Page 487


Attributes of <encrypt-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies the


transformer
so that other
elements can
reference it.
Required if the
transformer is
defined at the
global level.

returnClass class name no The class of


the message
generated by
the transformer.
This is used if
transformers
are auto-
selected (which
is somewhat
incomplete at the
moment).

ignoreBadInput boolean no Many transformers


only accept
certain classes.
Such transformers
are never called
with inappropriate
input (whatever
the value of this
attribute). If
a transformer
forms part of a
chain and cannot
accept the current
message class,
then this flag
controls whether
the remaining
part of the chain
is evaluated. If
true, the next
transformer is
called. If false
the chain ends,
keeping the result
generated up to
that point.

strategy-ref name (no spaces) no The name of


the encryption
strategy to use.
This should be
configured using
the password-
encryption-
strategy element,
inside a security-

Document generated by Confluence on Oct 27, 2008 21:07 Page 488


manager element
at the top level.

Decrypt Transformer
A transformer that decrypts a message.

Attributes of <decrypt-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies the


transformer
so that other
elements can
reference it.
Required if the
transformer is
defined at the
global level.

returnClass class name no The class of


the message
generated by
the transformer.
This is used if
transformers
are auto-
selected (which
is somewhat
incomplete at the
moment).

ignoreBadInput boolean no Many transformers


only accept
certain classes.
Such transformers
are never called
with inappropriate
input (whatever
the value of this
attribute). If
a transformer
forms part of a
chain and cannot
accept the current
message class,
then this flag
controls whether
the remaining
part of the chain
is evaluated. If
true, the next
transformer is
called. If false
the chain ends,
keeping the result
generated up to
that point.

Document generated by Confluence on Oct 27, 2008 21:07 Page 489


strategy-ref name (no spaces) no The name of
the encryption
strategy to use.
This should be
configured using
the password-
encryption-
strategy element,
inside a security-
manager element
at the top level.

Expression Transformer
A transformer that evaluates one or more expressions on the current event. Each expression equates to a
parameter in the return message. The return message for two or more expressions will be an Object[].

Attributes of <expression-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies the


transformer
so that other
elements can
reference it.
Required if the
transformer is
defined at the
global level.

returnClass class name no The class of


the message
generated by
the transformer.
This is used if
transformers
are auto-
selected (which
is somewhat
incomplete at the
moment).

ignoreBadInput boolean no Many transformers


only accept
certain classes.
Such transformers
are never called
with inappropriate
input (whatever
the value of this
attribute). If
a transformer
forms part of a
chain and cannot
accept the current
message class,
then this flag
controls whether
the remaining

Document generated by Confluence on Oct 27, 2008 21:07 Page 490


part of the chain
is evaluated. If
true, the next
transformer is
called. If false
the chain ends,
keeping the result
generated up to
that point.

returnSourceIfNull boolean no If all expressions


return null on
this transformer,
this flag will
cause the source
payload to be
returned without
modification.

Child Elements of <expression-transformer...>

Name Cardinality Description

return-argument 0..1

Document generated by Confluence on Oct 27, 2008 21:07 Page 491


XmlObject Transformers

This page last changed on Sep 25, 2008 by jackie.wheeler.

XML-Object Transformers
This page is ready for review

[ Object to XML ] [ XML to Object ] [ Testing the Transformers ]

This pair of transformers converts XML code to objects and back again.

Object to XML
The Object to XML transformer converts any object to XML using XStream. You configure this transformer
using the <object-to-xml-transformer> element. It takes the standard transformer attributes plus
one additional attribute, acceptUMOMessage, which specifies whether to serialize the whole message to
XML and not just its payload. This is useful with transports such as TCP where message headers are not
supported and would otherwise be lost.

For example:

<xml:object-to-xml-transformer name="ObjectToXml" acceptUMOMessage="true"/>

You can then reference this transformer from an endpoint:

<vm:inbound-endpoint path="another.queue" transformer-refs="ObjectToXml" />

XML to Object
The XML to Object transformer converts XML created by the Object to XML transformer in to a Java object
graph using XStream. You configure this transformer using the <xml-to-object-transformer> element.
It takes the standard transformer attributes.

For example:

<xm:xml-to-object-transformer name="XmlToObject" />

Testing the Transformers


The transformers can be tested using functional tests. For example, the following functional test uses
FunctionalTestCase, which is part of Mule's Test support, to test the Object to XML transformer.

public class MuleEndpointConfigurationTestCase extends FunctionalTestCase


{

protected String getConfigResources()


{
return "org/mule/test/integration/test-endpoints-config.xml";
}

...
public void testComponent4Endpoints() throws Exception
{
// test inbound
Service service = muleContext.getRegistry().lookupService("TestComponent4");
assertNotNull(service);
assertNotNull(service.getInboundRouter().getEndpoints());
assertEquals(1, service.getInboundRouter().getEndpoints().size());
ImmutableEndpoint endpoint = (ImmutableEndpoint)service.getInboundRouter().getEndpoints().get(0);
assertNotNull(endpoint);

Document generated by Confluence on Oct 27, 2008 21:07 Page 492


assertEquals(VMConnector.VM, endpoint.getConnector().getProtocol().toLowerCase());
assertEquals("queue4", endpoint.getEndpointURI().getAddress());
assertFalse(endpoint.getTransformers().isEmpty());
assertTrue(endpoint.getTransformers().get(0) instanceof ObjectToXml);
assertTrue(endpoint instanceof InboundEndpoint);
}
...
}

Document generated by Confluence on Oct 27, 2008 21:07 Page 493


XmlPrettyPrinter Transformer

This page last changed on Oct 06, 2008 by jackie.wheeler.

Xml Prettyprinter Transformer


Formats an XML string using the Pretty Printer functionality in org.dom4j.io.OutputFormat.

Attributes of <xml-prettyprinter-transformer...>

Name Type Required Default Description

encoding string no The encoding


format to use,
such as UTF-8.

expandEmptyElements
boolean no Whether to
expand empty
elements from
<tagName> to
<tagName></
tagName>.

indentEnabled boolean no Whether to enable


indenting of the
XML code. If true,
the indent string
and size are used.

indentString string no The string to use


as the indent,
usually an empty
space.

indentSize integer no The number of


indent strings
to use for each
indent, such as
"2" if indentString
is set to an empty
space and you
want to use two
empty spaces for
each indent.

lineSeparator string no The string to use


for new lines,
typically "\n".

newLineAfterNTags integer no If the newlines


attribute is true,
the number of
closing tags
after which a
newline separator
is inserted. For
example, setting
this to "5" will
cause a newline
to be inserted
after the output of

Document generated by Confluence on Oct 27, 2008 21:07 Page 494


five closing tags
(including single
tags).

newlines boolean no Whether newlines


should be printed.
If false, the XML is
printed all on one
line.

omitEncoding boolean no Whether the


XML declaration
line includes the
encoding of the
document. It
is common to
suppress this in
protocols such as
SOAP.

padText boolean no Whether to


ensure that text
immediately
preceded by or
followed by an
element will be
"padded" with a
single space. This
is useful when
you set trimText
to true and
want to ensure
that "the quick
<b>brown</
b> fox" does
not become "the
quick<b>brown</
b>fox".

suppressDeclaration boolean no Whether to


suppress the XML
declaration line.
It is common to
suppress this in
protocols such as
SOAP.

trimText boolean no Whether to trim


white space in the
XML.

XHTML boolean no Whether to


use the XHTML
standard, which
is like HTML but
passes an XML
parser with real,
closed tags, and
outputs CDATA
sections with
CDATA delimiters.

Document generated by Confluence on Oct 27, 2008 21:07 Page 495


XSLT Transformer

This page last changed on Oct 06, 2008 by jackie.wheeler.

Xslt Transformer
A transformer used to perform XSLT transforms on the current message payload. Transform objects are
pooled for better performance. You can set context properties on the transformer by pulling them from
the current message using Expression Evaluators.

Attributes of <xslt-transformer...>

Name Type Required Default Description

outputEncoding string no The encoding


to use for the
resulting XML/
Text.

maxIdleTransformers integer no Transformers


are pooled for
better throughput
since performing
and XSL
transformation
can be expensive.
This controls how
many instances
will remain idle in
the transformer
pool.

maxActiveTransformers
integer no The total number
of xslt transforms
that will get
pooled at any
given time.

xsl-file string no The full path to


the XSL template
file to use when
performing the
transform. This
can be a path
on the local file
system or on
the classpath.
This attribute is
not required if
the <xslt-text>
element has been
set.

uriResolver name (no spaces) no The URI resolver


to use when
validating the
XSL output. If
not set a default
one will be used
that checks for
resources on the

Document generated by Confluence on Oct 27, 2008 21:07 Page 496


local file system
and classpath.

transformerFactoryClass
name (no spaces) no he fully qualified
class name of the
javax.xml.TransformerFactory
instance to use.
If not specified
the default
JDK factory
TransformerFactory.newInstance
will be used.

Child Elements of <xslt-transformer...>

Name Cardinality Description

xslt-text 0..1 The inline xslt script definition.


This is not required if the xslt-
file attribute is set.

context-property 0..* A property that wil be made


available to the transform
context. Expression Evaluators
can be used to grab these
properties from the message at
runtime.

Example
The following example demonstrates how to configure an inline XSLT transformer pulling parameters from
the current message.

To use the XSLT transformer, you add it to your Mule XML configuration as follows:

An error occurred: null. The system administrator has been notified.

This example configures a transformer using inline XSLT expressions. It also defines two context
parameters:

An error occurred: null. The system administrator has been notified.

These parameters are pulled from the current message and made available in the XSLT context so that
they can be referenced in your XSLT statements. You can use any valid expression. In this example, the
header evaluator is used to pull a header from the current message.

Your configured XSLT transformer can be referenced by an endpoint. In the following example, the result
is written to System.out. The test data looks like this:

An error occurred: null. The system administrator has been notified.

The result written to System.out looks like this:

An error occurred: null. The system administrator has been notified.

The full configuration for this example is shown below.

Click here to expand...


An error occurred: null. The system administrator has been notified.

Document generated by Confluence on Oct 27, 2008 21:07 Page 497


Testing the Transformer
This transformer can be tested using the following functional test. Note that it uses FunctionalTestCase,
which is part of Mule's Test support.

Click here to expand...


An error occurred: null. The system administrator has been notified.

Document generated by Confluence on Oct 27, 2008 21:07 Page 498


Web Services

This page last changed on Oct 13, 2008 by jackie.wheeler.

Using Web Services


The following topics describe how to use web services with Mule.

Using Axis with Mule - Links to several topics describing Axis support in Mule.

Building a CXF Web Service - Describes how to build a CXF web service and use it in Mule.

Using the Mule Client - Describes the Mule Client, which can be used as a SOAP client.

Web Service Wrapper - Describes how to use the WebServiceWrapperComponent class to send the result
of a web service call to another endpoint.

REST Service Wrapper Component - see HTTP Transport - Proxies REST-style services as local Mule
components. For more information on REST, see Using the Mule RESTpack.

Echo Example - A simple example of exposing a Mule service as a web service using Axis.

Using .NET Web Services with Mule - Tips for using .NET web services with Mule.

Document generated by Confluence on Oct 27, 2008 21:07 Page 499


Axis

This page last changed on Oct 13, 2008 by jackie.wheeler.

Using Axis with Mule


The following topics describe how to configure Mule and Apache Axis.

• Axis Web Services and Mule - Introduction to exposing Mule services over Axis and invoking SOAP
services.
• Configuring Axis - Controlling WSDL generation, named parameters, Advanced Service
configuration, and more.
• Axis Transport - Basic configuration of the Axis transport.
• Axis SOAP Transports - Using Axis over JMS, VM, SMTP, and other Mule transports.
• Axis SOAP Styles - Configuring services for Doc/Lit, Message or RPC style invocations.

Document generated by Confluence on Oct 27, 2008 21:07 Page 500


Axis SOAP Styles

This page last changed on Oct 14, 2008 by jackie.wheeler.

Axis SOAP Styles


By default, Mule Axis support uses RPC/Encoded for SOAP messages. However, because of compatibility
issues on other platforms, it has become increasingly popular to use Document/Literal/Wrapped
style services. This page describes how to use Doc/Lit, Doc/Lit/Wrapped, and Message style services
using Axis in Mule. For an overview of the pros and cons of each style/use combination, see http://
www-128.ibm.com/developerworks/webservices/library/ws-whichwsdl/.

The client examples below show how to invoke an Axis web service hosted in Tomcat using the Mule
client. The example behaves exactly the same way if the service is hosted in Mule unless explicitly noted
otherwise. These tests were run against Tomcat 5.5.12 and Axis 1.3.1. Each test uses the Calculator
service as used in the Axis User Guide.

Document Literal Wrapped


This is the preferred approach to Document Literal style services. "Wrapped" simply means that the
parameters are wrapped in an element whose name is the name of the operation to invoke.

Client Example

This example is very similar to the Doc/Lit example, except that we set the message style to 'wrapped/
literal', and there is no need to add any server configuration, as the method name is stored in the
message.

String URL = "axis:http://localhost:8080/axis/Calculator.jws?method=add";


MuleClient client = new MuleClient();
Map props = new HashMap();
props.put("style", "wrapped");
props.put("use", "literal");
MuleMessage result = client.send(URL, new Object[]{new Integer(3), new Integer(3)}, props);
assertEquals(result.getPayload(), new Integer(6));

The SOAP request for this call looks like this:

<?xml version="1.0" encoding="UTF-8"?>


<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://
www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<add xmlns="">
<value0 xsi:type="xsd:int">3</value0>
<value1 xsi:type="xsd:int">3</value1>
</add>
</soapenv:Body>
</soapenv:Envelope>

In the next example, we can see how to change the namespace of the method as well as naming the
parameters. This is very useful when calling services from other platforms.

Doc/Lit/Wrapped with Named Parameters


If you're invoking external services, the Axis-generated names for parameters and namespaces do not
work. You can easily change these in Mule as follows:

Client Example

String URL = "axis:http://localhost:8080/axis/Calculator.jws";

Document generated by Confluence on Oct 27, 2008 21:07 Page 501


MuleClient client = new MuleClient();

SoapMethod method = new SoapMethod(new QName("http://muleumo.org/Calc", "add"));


method.addNamedParameter(new QName("Number1"), NamedParameter.XSD_INT, "in");
method.addNamedParameter(new QName("Number2"), NamedParameter.XSD_INT, "in");
method.setReturnType(NamedParameter.XSD_INT);

Map props = new HashMap();


props.put("style", "wrapped");
props.put("use", "literal");
props.put("method", method);
MuleMessage result = client.send(URL, new Object[]{new Integer(3), new Integer(3)}, props);
assertEquals(result.getPayload(), new Integer(6));

Note that we do not pass the method name in the query string of the URL. Instead, we create a
SoapMethod object and add it to the parameters passed to the client call.

The SOAP request now looks like this:

<?xml version="1.0" encoding="UTF-8"?>


<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://
www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<add xmlns="http://muleumo.org/Calc">
<Number1 xsi:type="xsd:int" xmlns="">3</Number1>
<Number2 xsi:type="xsd:int" xmlns="">3</Number2>
</add>
</soapenv:Body>
</soapenv:Envelope>

Using the Mule Configuration

Instead of hard-coding the namespaces and parameter names, you can specify them in an endpoint
configuration in the Mule configuration file and reference the endpoint from your Mule client. The
configuration file will look like this:

<axis:endpoint name="calculatorAddEndpoint"
address="http://localhost:62088/axis/Calculator?method=add"
style="WRAPPED" use="LITERAL">
<axis:soap-method method="add">
<axis:soap-parameter parameter="Number1" type="int" mode="IN"/>
<axis:soap-parameter parameter="Number2" type="int" mode="IN"/>
<axis:soap-return type="int"/>
</axis:soap-method>
</axis:endpoint>

This endpoint configuration can be used by the Mule client or on a component outbound router. The client
code is now much simpler:

MuleClient client = new MuleClient("org/mule/test/integration/providers/soap/axis/soap-client-


endpoint-config.xml");

Muleessage result = client.send("calculatorAddEndpoint", new Object[]{new Integer(3), new


Integer(3)}, null);
assertEquals(result.getPayload(), new Integer(6));

Notice the URL for the MuleClient call contains the name of the service endpoint, not the physical location
of the resource.

Document generated by Confluence on Oct 27, 2008 21:07 Page 502


Document Literal

Mule hosted Web services using Axis cannot be invoked using Doc/Lit. Use Doc/Lit/Wrapped
instead. Users can still invoke remote web services using Doc/Lit as shown in the example
below.

Client Example

For this example, we must tell the Mule client to use 'document/literal' for the message style, and we
pass this information into the call on the Mule client. This requires some configuration on the Axis server.
The biggest limitation of Doc/Lit is that operation/method name is not passed with the message.

String URL = "axis:http://localhost:8080/axis/Calculator.jws?method=add";


MuleClient client = new MuleClient();
Map props = new HashMap();
props.put("style", "document");
props.put("use", "literal");
MuleMessage result = client.send(URL, new Object[]{new Integer(3), new Integer(3)}, props);
assertEquals(result.getPayload(), new Integer(6));

The SOAP request for this call looks like this:

<?xml version="1.0" encoding="UTF-8"?>


<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://
www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<value0 xsi:type="xsd:int">3</value0>
<value1 xsi:type="xsd:int">3</value1>
</soapenv:Body>
</soapenv:Envelope>

Using Doc/Lit with Axis might appear to work even when you don't add operation info to
the Axis server configuration. This happens when there is a single parameter for the service
and the parameter name is the same as the operation/method name you want to invoke.
For more information, see Axis Operations.

RPC Encoded
Because Axis uses RPC/Encoded by default, there is no need to pass any additional configuration
information. The client call looks like this:

String URL = "axis:http://localhost:8080/axis/Calculator.jws?method=add";


MuleClient client = new MuleClient();
MuleMessage result = client.send(URL, new Object[]{new Integer(4), new Integer(3)}, null);
assertEquals(result.getPayload(), new Integer(7));

The SOAP request for this call looks like this:

<?xml version="1.0" encoding="UTF-8"?>


<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://
www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<add soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<value0 href="#id0"/>
<value1 href="#id1"/>
</add>
<multiRef id="id0" soapenc:root="0" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/
encoding/"
xsi:type="soapenc:int" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">4</multiRef>
<multiRef id="id1" soapenc:root="0" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/
encoding/"

Document generated by Confluence on Oct 27, 2008 21:07 Page 503


xsi:type="soapenc:int" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">3</multiRef>
</soapenv:Body>
</soapenv:Envelope>

Document generated by Confluence on Oct 27, 2008 21:07 Page 504


Axis SOAP Transports

This page last changed on Oct 15, 2008 by jackie.wheeler.

Axis SOAP Transports


[ SOAP Over JMS ] [ SOAP Over VM ] [ Binding to a Servlet Container ] [ Using Other Mule Transports ]

Mule transports can deliver SOAP requests between Axis clients and Axis services hosted by Mule. This
means you can easily use JMS, VM, SMTP, or even XMPP (Jabber) to send SOAP requests. This page
describes how to configure these transports.

SOAP Over JMS


First, if you do not want to use the default JMS connector, configure the connector you do want to use in
your Mule XML configuration:

<jms:activemq-connector name="jmsConnector"/>

Next, create the service. In this example, we will create a service that listens to a queue called
echoComponent. The method parameter specifies the operation to invoke. The SOAPAction property
specifies the name of the queue again, which is required if your service name and queue name are not
identical.

<model name="echoSample">
<service name="echoService">
<inbound>
<inbound-endpoint address="axis:jms://echoComponent?method=echo&param=hello" SOAPAction="jms://
echoComponent"/>
</inbound>
<echo-component/>
</service>
</model>

You can also add any other JMS endpoint options, such as transactions. See the JMS Transport
documentation for a full description.

SOAP Over VM
The VM transport also supports SOAP, which can be useful for testing or prototyping. You configure the
endpoints the same as JMS SOAP endpoints. For example:

<model name="test">
<service name="mycomponent">
<inbound>
<inbound-endpoint address="axis:vm://mycomponent"/>
</inbound>
<component>
<singleton-object class="org.mule.tck.testmodels.services.TestServiceComponent"/>
</component>
</service>

<service name="mycomponent2">
<inbound>
<axis:inbound-endpoint address="vm://mycomponent2">
<axis:soap-service interface="org.mule.api.component.simple.EchoService"/>
<axis:soap-service interface="org.mule.tck.testmodels.services.DateService"/>
</axis:inbound-endpoint>
</inbound>
<component>
<singleton-object class="org.mule.tck.testmodels.services.TestServiceComponent"/>

Document generated by Confluence on Oct 27, 2008 21:07 Page 505


</component>
</service>
</model>

Binding to a Servlet Container


If you embed Mule in a webapp, you might want to bind Axis services to the servlet container port rather
than open another port for Mule SOAP services, but you may not be able to do this because of firewall
restrictions. In this scenario, you can use the Servlet Transport and Axis instead of HTTP. To use this
transport, you must add MuleReceiverServlet to your web.xml file:

<servlet>
<servlet-name>muleServlet</servlet-name>
<servlet-class>org.mule.transport.servlet.MuleReceiverServlet</servlet-class>
<load-on-startup/>
</servlet>

<servlet-mapping>
<servlet-name>muleServlet</servlet-name>
<url-pattern>/mule/services/*</url-pattern>
</servlet-mapping>

Next, you add a servlet endpoint to your component:

<servlet:connector name="servlet" servletUrl="http://localhost:62088/services"/>


<model name="test">
<service name="mycomponent">
<inbound>
<axis:inbound-endpoint address="servlet://mycomponent"/>
</inbound>
<component class= "org.mule.tck.testmodels.services.TestServiceComponent"/>
</service>
</model>

Note that you set the host, port, and path on the connector, not the endpoint, using the servletUrl
property.

Using Other Mule Transports


You can send and receive SOAP requests using other transports simply by configuring the endpoint
according to the endpoint scheme and then prepending the axis: scheme. For client endpoints, you also
set the the method parameter.

//Client
axis:xmpp://mule1:mule@jabber.org.au/axis?method=echo&param=hello

//Server
axis:xmpp://mule1:mule@jabber.org.au/axis

Document generated by Confluence on Oct 27, 2008 21:07 Page 506


Axis Transport

This page last changed on Oct 15, 2008 by jackie.wheeler.

Axis Transport
The Axis transport allows Mule-managed components to be published as Axis services and allows
components to invoke web services using Axis client calls.

The Javadocs for the AxisConnector can be found at org.mule.transport.soap.axis.AxisConnector .

Programmatic Configuration
If you want to programmatically configure your Axis service you can implement the
org.mule.transport.soap.axis.AxisInitialisable interface. This will pass the SOAPService object to your
component where it can be manipulated.

Connector
The Axis connector consumes and provides web services via Axis. It supports all the common connector
attributes and properties as well as the following additional attributes:

Attributes of <connector...>

Name Type Required Default Description

axis-ref string no Bean reference to


the Axis server.

clientConfig string no Configuration


file to use when
building the Axis
client.

clientProvider-ref string no Bean reference to


the client provider
to use for creating
the Axis client.

doAutoTypes boolean no Use this property


to configure
whether the Axis
server should
automatically
map types. This
property only
takes effect if you
do not provide
your own Axis
server via the
axis-ref property.

serverConfig string no Configuration


file to use when
building the Axis
server.

Document generated by Confluence on Oct 27, 2008 21:07 Page 507


serverProvider-ref string no Bean reference
to the server
provider that
should be used
to create the Axis
server.

treatMapAsNamedParams
boolean no The Axis
connector
treats a Map
as a container
for named
parameters and
unpacks them
from the map.
If your exposed
service needs to
take a Map as a
parameter, set this
property to false
to prevent the
connector from
unpacking the
Map.

Child Elements of <connector...>

Name Cardinality Description

bean-type 0..*

supported-scheme 0..*

Inbound Endpoint

Attributes of <inbound-endpoint...>

Name Type Required Default Description

wsdlFile string no The location of a


WSDL document
to use for this
service if you
do not want the
WSDL document
autogenerated.

clientConfig string no

soapAction string no

SOAPAction string no

serviceNamespace string no

style styleType no Specifies the


SOAP binding

Document generated by Confluence on Oct 27, 2008 21:07 Page 508


style: RPC
(default),
DOCUMENT,
MESSAGE, or
WRAPPED.

use useType no Specifies the


SOAP binding
use: ENCODED
(default) or
LITERAL.

For example:

<service name="Calculator">
<inbound>
<axis:inbound-endpoint address="http://localhost:62088/axis" style="WRAPPED" use="LITERAL">
<axis:soap-method method="qname{add:http://muleumo.org/Calc}">
<axis:soap-parameter parameter="Number1" type="any" mode="IN" />
<axis:soap-parameter parameter="Number2" type="any" mode="IN" />
<axis:soap-return type="any" />
</axis:soap-method>
</axis:inbound-endpoint>
</inbound>
<component class="org.mule.transport.soap.axis.Calculator" />
</service>

Escape Your Credentials

When including the user name and password in the endpoint, escape any characters
that are illegal for URIs, such as the @ character. For example, if the user name is
user@myco.com, you should enter it as user%40myco.com.

Outbound Endpoint

Attributes of <outbound-endpoint...>

Name Type Required Default Description

clientConfig string no

soapAction string no

SOAPAction string no

serviceNamespace string no

style styleType no Specifies the


SOAP binding
style: RPC
(default),
DOCUMENT,
MESSAGE, or
WRAPPED.

use useType no Specifies the


SOAP binding
use: ENCODED
(default) or
LITERAL.

Document generated by Confluence on Oct 27, 2008 21:07 Page 509


Wrapper Component
The WebServiceWrapperComponent class allows you to send the result of a web service call to another
endpoint. For example:

<axis:wrapper-component address="http://localhost:65081/services/TestUMO?method=receive"
style="WRAPPED" use="LITERAL" />

Attributes of <wrapper-component...>

Name Type Required Default Description

address string no Specifies the URL


of the web service
to call.

addressFromMessageboolean no Specifies that the


URL of the web
service will be
obtained from the
message itself.

style styleType no Specifies the


SOAP binding
style: RPC
(default),
DOCUMENT,
MESSAGE, or
WRAPPED.

use useType no Specifies the


SOAP binding
use: ENCODED
(default) or
LITERAL.

Child Elements of <wrapper-component...>

Name Cardinality Description

soap-method 0..* Allows you to specify a


SOAP method and optionally
parameters and a return. The
parameter mode can be IN, OUT,
or INOUT.

Document generated by Confluence on Oct 27, 2008 21:07 Page 510


Axis Web Services and Mule

This page last changed on Oct 13, 2008 by dan.diephouse@mulesource.com.

Axis Web Services and Mule


[ Exposing Web Services ] [ Invoking Web Services ] [ Axis Without a Servlet Container ] [ Configuring
the Axis Server ] [ SOAP Over Other Transports ]

Exposing Web Services


You can expose service components as Axis services and invoke them from Mule. To expose a service
component as an Axis service, you simply import the Axis namespace and then set the component's
inbound endpoint to an Axis URL. Note that web services expect methods to be exposed through
interfaces implemented by their respective components. Otherwise, you will receive configuration errors
when Mule starts.

<service name="echoService">
<inbound>
<axis:inbound-endpoint address="http://localhost:81/services"/>
</inbound>
<echo-component/>
</service>

When Mule starts, the service will be available on http://localhost:81/services/echoService. The Echo
component class (org.mule.components.simple.EchoComponent) implements the EchoService interface,
which has a single method called echo that accepts a single parameter string.

Note: Mule 2.0 supports Axis 1.4.

Invoking Web Services


You can invoke web services from Mule programmatically using the Mule Client or as part of the event
flow of a Mule service. This section describes these approaches in detail.

Invoking Services Using the Mule Client

To invoke the Echo service using the Mule Client, use the following code:

TestEchoService.java

public static void main(String[] args)


{
MuleClient client = new MuleClient();
MuleMessage result = client.send
("axis:http://localhost:81/services/echoService?method=echo",
"Hello!", null);
System.out.println("Message Echoed is: " + result.getPayload());
client.close();
}

Invoking Web Services from a Mule Service

To invoke the Echo service from a service, you add an outbound endpoint to your service configuration.
The following example shows a service that receives an event on vm://test.component, does some work
on the event, and then invokes the Echo service.

<service name="test">
<inbound>
<vm:inbound-endpoint path="test.component" synchronous="true"/>
</inbound>

Document generated by Confluence on Oct 27, 2008 21:07 Page 511


<component implementation="com.foo.TestComponent"/>
<outbound>
<outbound-pass-through-router>
<axis:outbound-endpoint address="http://localhost:81/services/echoService?method=echo"/>
</outbound-pass-through-router>
</outbound>
</service>

The org.foo.TestComponent class looks like this:

org.foo.TestComponent

public class TestComponent implements Callable


{
public Object onCall(MuleEventContext context) throws Exception
{
Object payload = context.getMessage().getPayload();

//Do some work on the payload and return a string that will be
//used by the outbound endpoint to invoke the echo service
//...

return payload.toString();
}
}

If the Web service you are invoking takes more than one parameter, you can return an array of
parameters in your component.

When an event is published to vm://test.component, the onCall method is called with the current event.
After the onCall method executes, Mule invokes the outbound endpoint for TestComponent with what is
returned from onCall.

Note that the vm://test.component endpoint has a parameter synchronous=true. This tells Mule to
invoke requests from that endpoint in a single thread, making it a request/response style request. Thus
the result of invoking the Echo service (by invoking TestComponent) will be returned to the callee who
dispatched the event on vm://test.component.

When the TestEchoService is run, you will see the following output:

Message Echoed is: Hello!

Note the following:

• There is no need for a servlet container, because Mule is the container (see below).
• You don't need to specify a deployment WSDD for your service. You simply specify an endpoint for
the service, and the rest is done for you.
• The MuleClient call will work just as well if the service you are invoking is hosted by an Axis instance
running on Tomcat or any other servlet engine.
• The Axis JAR and associated JARs that ship with the Mule distribution must be on your classpath.

Exposing Services

All service operations are exposed through interfaces implemented by your component.
Therefore, your component must implement at least one service interface, which is
generally good practice anyway.

Axis Without a Servlet Container


When you use Axis with Mule, there is no need for a separate servlet container. When you create an Axis
endpoint, Mule takes the following actions:

• Creates an Axis component in Mule, which is analogous to the AxisServlet. There is only one Axis
component per Mule instance.
• Creates an HTTP connector for the endpoint address and registers it as a receiver for the Axis
component.

Document generated by Confluence on Oct 27, 2008 21:07 Page 512


Cannot resolve external resource into attachment.

Most web services are a lot more complex than the first example, so the following sections will tell you
how to configure the Axis instance and your services in more detail.

Configuring the Axis Server


In the previous example, a default Axis connector is created when the Axis endpoint is processed by
Mule. The Axis connector uses a default server configuration file called mule-axis-server-config.wsdd.
You can override this configuration by setting the serverConfig property on the connector to a different
configuration file, which will allow you to add additional handlers, global configuration, and more.

<axis:connector name="axisConnector" serverConfig="./axis/axis-server-config.wsdd"/>

If you use a custom server configuration, you must add the following handlers in the global configuration:

<requestFlow>
<handler
type="java:org.mule.transport.soap.axis.extensions.MuleSoapHeadersHandler"/>
</requestFlow>
<responseFlow>
<handler
type="java:org.mule.transport.soap.axis.extensions.MuleSoapHeadersHandler"/>
</responseFlow>

If you are configuring Mule from a container such as Spring, you can set the Axis server as a bean
property (axisServer) on the connector and the serverConfig property is ignored.

You can list the Axis services in the same way you list services when Axis is hosted in a servlet container.
To list services, simply point your browser at the host and port of the axis endpoint:

http://localhost:81/

To view Axis version information, go to:

http://localhost:81/Version?method=getVersion

To view the WSDL for the service, go to:

http://localhost:81/Version?wsdl

Note that the Axis JWS feature is not supported by Mule.

SOAP Over Other Transports


You can configure Axis to send/receive soap requests over other transports such as JMS and SMTP. For
more information, see Axis Soap Transports.

For more information about customizing Axis behavior, naming parameters, message style options, and
more, see Configuring Axis.

Document generated by Confluence on Oct 27, 2008 21:07 Page 513


Configuring Axis

This page last changed on Oct 20, 2008 by jackie.wheeler.

Configuring Axis
Table of Contents

Click here to expand...

• Configuring Axis
• ° Controlling Exposed Methods
° Map as Parameter
° Setting SOAP Document Style
° Customizing the SOAP Action Format
° Setting Named Parameters
° Controlling Namespaces
° Controlling WSDL Generation
° Type Mappings
° Service Initialization Callback

Controlling Exposed Methods


To restrict the exposure of a service's methods add additional soap-service elements. These allow you
to specify interfaces that the service implements and that should be exposed.

<axis:inbound-endpoint address="http://localhost:38009/mule/services">
<axis:soap-service interface="org.mule.api.component.simple.EchoService"/>
<axis:soap-service interface="org.mule.tck.testmodels.services.DateService"/>
</axis:inbound-endpoint>

You can also specify one or more methods to expose in a comma-separated list, using the
allowedMethods attribute.

<service name="myService">
<inbound>
<axis:inbound-endpoint address="http://localhost:38009/mule/services"
allowedMethods="echo,getDate" />
</inbound>
<component class="com.foo.TestComponent" />
</service>

Map as Parameter
The AxisConnector treats a Map as container for named parameters, which eventually will be unpacked.
This becomes a problem if your exposed service needs to take a Map as a parameter, because the actual
Map will never reach the service intact.

To configure the connector not to unpack Maps so that they can be passed as parameters, use the
treatMapAsNamedParams attribute:

<axis:connector name="axisConnector" treatMapAsNamedParams="false"/>

Setting SOAP Document Style


To control the style and use of a service, the style and use properties can be set on Axis endpoints. For
example, to make your inbound endpoint Document/Literal/Wrapped, do the following:

<axis:inbound-endpoint address="http://localhost:38009/mule/services"

Document generated by Confluence on Oct 27, 2008 21:07 Page 514


style="WRAPPED"
use="LITERAL"/>

The style attribute can be 'RPC' (default), 'DOCUMENT', 'MESSAGE', or 'WRAPPED'. The use attribute can
be either 'ENCODED' (default) or 'LITERAL'.

For more information about service styles and Mule, see Axis SOAP Styles. Also see the Axis web site for
further reference.

Customizing the SOAP Action Format


By default, Mule uses the Axis endpoint as the SOAP Action when making WS calls. This approach works
for Axis clients but might not work with .NET clients. The SOAP Action can be different for different SOAP
implementations, so you must be able to customize how the SOAP Action is formatted. You can set the
soapAction attribute on the outbound endpoint making the SOAP request:

<axis:outbound-endpoint
address="http://localhost:38011/mule/echoService?method=echo"
soapAction="http://localhost:38011/${method}"
synchronous="true" />

The above example sets the SOAP Action on the request to http://localhost:38011/echo. If you are
using the Mule client, you can set the SOAP Action as a property when making the call.

The SOAP Action can be a static value, or you can use template variables such as the method variable
used above. The set of variables that can be used are listed below.

Variable Description Example

method The service method name being echo


invoked

methodNamespace The service method name being echo


invoked

address The full SOAP endpoint http://localhost:38011/


mule/echoService?
method=echo

scheme The request scheme being used http

host The hostname from the SOAP localhost


endpoint

port The port from the SOAP 38011


endpoint

path The path info from the SOAP /mule/echoService


endpoint

hostInfo The scheme, host and port http://localhost:38011


combined

serviceName The name of the service being echoService


invoked

Any other properties on the event or the endpoint can be referenced by name in the soapAction
expression.

Document generated by Confluence on Oct 27, 2008 21:07 Page 515


Setting Named Parameters
Some web service clients require that all method parameters of a call should be named. You can do this
in Mule in two ways.

In the Mule XML configuration, you can set the SOAP method parameters for a service on the endpoint
using the soap-method element.

<axis:outbound-endpoint address="http://localhost:38011/mule/echoService?method=echo"
synchronous="true">
<axis:soap-method method="echo">
<axis:soap-parameter parameter="string1" type="string" mode="IN"/>
<axis:soap-parameter parameter="string2" type="string" mode="IN"/>
<axis:soap-return type="java"/>
</axis:soap-method>
</axis:endpoint>

Within the soap-method element, you can define soap-parameter elements, which control that
parameter's mode, name, and type. The parameter attribute is the name of the parameter. The type
attribute is an XSD string such as int, long, map, etc. The attribute mode can be in, out, or inout. The
return type is also an XSD type string. The soap-return element controls the type of the parameter the
method returns.

Controlling Namespaces
Namespaces for elements can be controlled at the method and parameter level. To declare a namespace
on the method with a prefix of 'foo' and a URI of 'http://mycompany.com/foo', you would use the
following code:

<axis:outbound-endpoint address="http://localhost:38011/mule/echoService?method=echo"
synchronous="true">
<axis:soap-method method="qname{foo:http://mycompany.com/foo}">
<axis:soap-parameter parameter="in0" type="string" mode="IN"/>
<axis:soap-parameter parameter="out" type="ns1:Test" mode="OUT"/>
<axis:soap-return type="org.mule.tck.external.applications.Test"/>
</axis:soap-method>
</axis:endpoint>

The syntax for the qname is:

qname{[MULE:prefix]:[MULE:localname]:[MULE:namespace]}

You can supply just a localname, a localname and namespace, or a prefix, localname, and namespace.

The qname syntax can be used with <soap-parameter> elements as well. For example:

<axis:soap-parameter parameter="qname{foo1:echo1:http://mycompany.com/foo1}" type="string"


mode="OUT"/>

To set the method parameter name using the Mule client, you create a SoapMethod object and set it on
the properties when making the call. The example below shows how to do this.

MuleClient client = new MuleClient();


Map props = new HashMap();
//create the soap method passing in the method name and return type
SoapMethod soapMethod = new SoapMethod("echo", NamedParameter.XSD_STRING);
//add one or more parameters
soapMethod.addNamedParameter("value", NamedParameter.XSD_STRING, ParameterMode.IN);
//set the soap method as a property and pass the properties
//when making the call
props.put(MuleProperties.MULE_SOAP_METHOD, soapMethod);

MuleMessage result = client.send("axis:http://localhost:38011/mule/echoService?method=echo",


"Hello", props);

Document generated by Confluence on Oct 27, 2008 21:07 Page 516


Note that you can use the qname notation for setting method and parameter names using the Mule client.

Controlling WSDL Generation


The service namespace (also called the target namespace) for your service can be controlled by setting
the serviceNamespace property on the inbound endpoint:

<axis:inbound-endpoint address="http://localhost/services" serviceNamespace="http://foo.namespace"/


>

You can also set the wsdlFile property to the location of a WSDL document to use for this service if you
do not want an auto-generated WSDL document.

<axis:inbound-endpoint address="http://localhost/services" wsdlFile="foo.wsdl"/>

Optionally, you can control the values used in Axis WSDL generation by setting WSDL-specific Axis
options. The options you can set are:

Option Name Description

wsdlPortType Sets the wsdl:portType name attribute. the Axis


default is $Proxy0

wsdlServiceElement Sets the wsdl:service name attribute. the Axis


default is $Proxy0Service

wsdlTargetNamespace Sets the wsdl:definitions targetNamespace


attribute. The Axis default is http:// plus
package name of the service class in reverse.

wsdlServicePort Sets the wsdl:port name attribute of the


wsdl:service element. The default is the name
of the Mule component exposed by this service
endpoint.

wsdlInputSchema

wsdlSoapActionMode

extraClasses

To change the wsdlServiceElement name attribute to MyService in the generated WSDL for a service,
use the following:

<axis:inbound-endpoint address="http://localhost:38009/mule/services">
<properties>
<spring:entry key="axisOptions">
<spring:map>
<spring:entry key="wsdlServiceElement" value="MyService"/>
</spring:map>
</spring:entry>
</properties>
</axis:inbound-endpoint>

Type Mappings
Note that as of Axis 1.2-RC3, it is no longer necessary to configure type mappings, as bean serialization
is handled automatically by Axis. If you are using an older version of Axis, you might need to configure
type mappings.

Document generated by Confluence on Oct 27, 2008 21:07 Page 517


Mule enables default type mappings for object serialization between SOAP calls. This means that
serialization and deserialization of call parameters and return objects is mostly handled automatically by
Axis. This works for most Java types including primitives, Numbers, Strings, Arrays and Collections. It
also works for JavaBeans whose attributes comprise these types. However, it does not work where you
have a bean that has another bean as an attribute; Axis will complain that it doesn't know how to handle
the bean attribute.

Mule handles this by allowing you to specify a list of beanTypes that Axis needs to understand to manage
your service. For example, assume you have a PersonService service that will get a Person object when
passed the person's name. The Person object contains an Address object. The configuration will look like
this:

<axis:inbound-endpoint address="http://localhost:38009/mule/services">
<property key="beanTypes">
<spring:list>
<spring:value>org.foo.Address</spring:value>
</spring:list>
</property>
</axis:inbound-endpoint>

It is important to note that only custom types should be listed. If any standard types are
present, like java.util.ArrayList, Axis may produce serialization errors.

For convenience, the beanTypes property can be set on an Axis connector configuration so that all
services that use the connector will have the types registered in the TypeRegistry for the service.

<axis:connector name="axisConnector">
<spring:property name="beanTypes">
<spring:list>
<spring:value>org.foo.Address</spring:value>
</spring:list>
</spring:property>
</axis:connector>

By default, an Axis connector is created if one doesn't exist already when the Axis endpoint is processed.
For more information about configuring Connectors and Providers, see Configuring Endpoints.

Service Initialization Callback


If you need further control over the Axis service created by Mule, it is possible for your component to
implement AxisInitialisable.

AxisInitialisable.java

public interface AxisInitialisable


{
public void initialise(SOAPService service) throws InitialisationException;
}

This gets called when the service is initialized and allows you to customize the service configuration from
your Mule component.

Document generated by Confluence on Oct 27, 2008 21:07 Page 518


Using .NET Web Services with Mule

This page last changed on Sep 07, 2008 by jackie.wheeler.

Using .NET Web Services with Mule


This page is ready for review

Following are tips for using Mule to communicate with .NET web services.

Calling A .NET Web Service from Mule


The request and parameters used to access a .NET web service have to be sent as SOAP messages. The
following cookbook entry provides an example (based on Mule 1.x):

Calling a .NET web service using Axis

Authentication and Other Security Features


There are three ways to secure a web service:

• Via an HTTP web server


• Via authentication tokens in the SOAP header
• Via WS-Security

Via an HTTP Web Server

If you are running Mule on a Web App, you can configure the web server to use security by setting
security configuration in web.xml and in the server's configuration file.

Alternatively, to secure a web service running on Mule (where Mule is the server), you can set the
HttpBasicAuthenticationFilter on the web service component. Any call made to the web service would
have to pass through the filter that delegates the authentication to Acegi.

For more information, see Configuring Security.

Another alternative would be to use HTTPS where certificates are used for authentication.

Using Authentication Tokens in SOAP Headers

You can send authentication tokens through SOAP headers as long as there is an authentication provider
established that is able to understand the headers and perform the authentication.

Using WS-Security

If you are using CXF, you can configure a client and service to use WS-SecurityFor details, see Enabling
WS-Security.

Passing Authentication Information to a Web Service

There are three methods for passing authentication information to a web service configured on Mule:

• Pass them in the URL, such as http://name:password@localhost:8080/MyService


• Set the authentication items as properties when using the Mule client
• Create headers containing the authentication items and send them as properties when using the
Mule client

Document generated by Confluence on Oct 27, 2008 21:07 Page 519


Web Service Wrapper

This page last changed on Oct 15, 2008 by jackie.wheeler.

Using the Web Service Wrapper


The WebServiceWrapperComponent class allows you to send the result of a web service call to another
endpoint. The web service call is performed within WebServiceWrapperComponent, providing the following
advantages:

• You can set any type of router on inbound and outbound.


• Unlike the chaining router, it can send more than one HTTP request at a time
• The URL for the web service call can be changed at run-time by sending the URL with the message

Configuring the Web Service Wrapper


To use the web service wrapper, you specify the <wrapper-component> configuration element. The
following table describes the attributes you can set for this element. These attributes are described in
more detail in the examples that follow.

Attribute Description Required?

address Specifies the URL of the web Yes, unless


service to call addressFromMessage is set to
true

addressFromMessage (default is Specifies that the URL of the Not required if address is set
false) web service will be obtained
from the message itself

wrapperProperties The SOAP document style, No


expressed as a map of two
properties: style, which can
be set to RPC (the default),
Document, Message, or Wrapped,
and use, which can be Encoded
or Literal.

<soap-method> A SOAP method to call (see No


Configuring SOAP Methods
below)

The web service wrapper is generic and can be used with any type of web service stack supported by
Mule, including Axis and CXF. The examples below show synchronous use cases, but the web service
wrapper can also support an asynchronous use case like the loan broker example.

Example Configuration Using the CXF Transport

Consider the following example. The web service wrapper is configured as a Mule component, accepting
messages from a VM endpoint. A call must be made to a web service on the URL cxf:http://
localhost:65081/services/TestUMO?method=onReceive and the result must be sent to the outbound
endpoint vm://testout.

The inbound and outbound endpoints are configured in the usual way. The address is set as an attribute
on the component, specifying the web service URL that you want to call.

<cxf:connector name="cxf" defaultFrontend="simple" />


<model name="Sample">
<service name="WebServiceSample">
<inbound>

Document generated by Confluence on Oct 27, 2008 21:07 Page 520


<vm:inbound-endpoint path="testin" />
</inbound>
<cxf:wrapper-component address="http://localhost:65081/services/TestUMO?method=onReceive"/>
<outbound>
<outbound-pass-through-router>
<outbound-endpoint address="vm://testout"/>
</outbound-pass-through-router>
</outbound>
</service>

Example Configuration Using the addressFromMessage Property

The "address" property is ideal to use when the web service URL for the web service is known at
configuration time. However, if this URL is either not known or else needs to be changed at run-time,
the "address" property can be omitted and the "adddressFromMessage" property can be set to true. The
following example shows this configuration:

<service name = "WebServiceSample2">


<inbound>
<vm:inbound-endpoint path = "testin2"/>
</inbound>
<cxf:wrapper-component addressFromMessage = "true"/>
</service>

The URL must be set on the message with the property name "ws.service.url".

Configuring SOAP Methods

CXF endpoints are fairly easy to configure, whereas Axis needs some further configuration to set SOAP
methods. You can set a SOAP method using the <soap-method> element as shown below:

<service name = "WebServiceSample3">


<inbound>
<vm:inbound-endpoint path = "queue.in" connector-ref = "VMQueue"/>
</inbound>
<axis:wrapper-component address = "http://localhost:62088/axis/Calculator?method=add" style =
"WRAPPED" use = "LITERAL">
<axis:soap-method method = "qname{add:http://muleumo.org/Calc}">
<axis:soap-parameter parameter = "Number1" type = "int" mode = "IN"/>
<axis:soap-parameter parameter = "Number2" type = "int" mode = "IN"/>
<axis:soap-return type = "int"/>
</axis:soap-method>
</axis:wrapper-component>
<outbound>
<outbound-pass-through-router>
<vm:outbound-endpoint path = "queue.out" connector-ref = "VMQueue"/>
</outbound-pass-through-router>
</outbound>
</service>

Document generated by Confluence on Oct 27, 2008 21:07 Page 521


Working with Services

This page last changed on Aug 13, 2008 by jackie.wheeler.

Working with Services


A service component is a class, web service, or other application that contains the business logic you
want to plug in to the Mule framework. For example, one service component could add information to
an invoice from a customer database, and another service component could be the order fulfillment
application that processes that invoice. You can use any existing application for a service component, or
create a new one.

Your service component does not need to contain any Mule-specific code. Instead, you configure
a service, which wraps the service component with the Mule-specific configuration. The service
configuration points to the service component, as well as routers, filters, and transformers to use when
carrying messages to and from the service component. It also specifies the endpoint on which this service
will receive messages and the outbound endpoint where messages will go next. Services are the primary
Mule artifact used to implement integration solutions.

Service Components
A service component can be a POJO, servlet, web service, and much more. Typically, you create a custom
service component, but you can also use one of the several standard components included with Mule. For
more information, see Configuring Components.

Service Configuration
Most configuration happens at the service level. Services can be configured using globally defined
endpoints, transformers, and filters, or these can be defined inline. For more information, see Configuring
the Service.

Service Behavior
When a service receives a message on an inbound endpoint, the service model (default is SEDA)
determines the service's threading and queuing behavior, while the messaging pattern defines the
inbound and outbound message exchange patterns that will be used.

Advanced Configuration
You can further configure the service with security (configured on endpoints), transactions, and error
handling.

Document generated by Confluence on Oct 27, 2008 21:07 Page 522


Configuring Components

This page last changed on Oct 13, 2008 by jackie.wheeler.

Configuring Components
[ Simple Components ] [ Java Components ] [ Other Components ] [ Interceptors ]

Service components contain the business logic for working with the messages passed through Mule. A
service component can be any type of object, including a Spring bean, POJO, script, web service, or REST
call.

Because they are highly specific to your implementation, you will typically create your own custom
components, or simply use an existing POJO. Mule also ships with some standard components you can
use or extend as needed. This page describes how to configure the different types of components.

For detailed information on the elements you configure for components, see Component Configuration
Reference.

Simple Components
There are several simple components included with Mule that are useful for testing or bypassing
component execution.

Configuration Element Description

<log-component/> Logs component invocations, outputting the


received message as a string. This component
does not return a response.

<echo-component/> Extends the log component to log and echo the


incoming message. The message is transformed
before being returned, so transformations on
inbound endpoints will be applied.

<null-component/> Throws an exception when invoked. This is


useful for testing use cases that use a forwarding
consumer inbound router.

<passthrough-component> Similar to the echo component but does not


log. This component is useful when defining
services that consist of inbound and outbound
endpoints/routers but don't have a component
implementation. Note that explicitly configuring
this component has exactly the same result as
configuring a service with no component.

<bridge-component/> Identical to the pass-through component but


preserves the Mule 1.4 terminology.

<test:component/> Configures the Mule FunctionalTestComponent,


which allows more complex testing scenarios to
be created. For more information, see Functional
Testing.

Document generated by Confluence on Oct 27, 2008 21:07 Page 523


Java Components
Java components specify a Java class to be used as the service component or configure a reference to an
implementation in a container such as Spring. They also configure the way in which Mule should manage
the Java service component's life-cycle, invoke it, and (if pooled) manage the pool of instances.

Java components can be configured quickly and easily by simply specifying the service component
implementation class name on the <component> or <pooled-component> element. The <pooled-
component> element allows you to establish a pooling profile for the service (see Tuning Performance). In
both cases, the PrototypeObjectFactory will be used by default and a new object instance will be created
for each request or (for pooled components) for each new object in the pool.

<component class="org.my.ServiceComponentImpl"/>
...
<pooled-component class="org.my.ServiceComponentImpl"/>

For further configuration options and information on the default settings that are applied, see Configuring
Java Components.

Other Components
These are several other components available that allow you to use different technologies such as web
services for your service components. These components are often included as part of transports or
modules.

Configuration Description

<http:rest-service-component/> Proxies a remote call to a REST-style web service.

<cxf:wrapper-component/> Proxies a remote call to a web service using CXF.

<axis:wrapper-component/> Proxies a remote call to a web service using Axis.

<script:component/> Configures a JSR-223 script for the service


component.

Interceptors
Mule interceptors are useful for attaching behaviors to multiple service components. The interceptor
pattern is often referred to as practical AOP (Aspect Oriented Programming), as it allows the developer
to intercept processing on an object and potentially alter the processing and outcome. (See also Spring
AOP). Interceptors are very useful for attaching behavior such as profiling and permission and security
checks to your service components.

Interceptor Types

Mule has two types of interceptors:

• EnvelopeInterceptor : Envelope filter that will execute before and after the component is invoked.
Good for logging and profiling.
• Interceptor : Intercepts the message and then forwards it for processing to the next element. An
interceptor can stop further processing by not forwarding control to the next interceptor, as with a
permissions checker interceptor.

Interceptor Event Flow

The following shows an example interceptor stack and the event flow.

Document generated by Confluence on Oct 27, 2008 21:07 Page 524


Writing Interceptors

If you want to intercept a message flow to a component on the inbound message flow, you should
implement the Interceptor interface. It has a single method:

MuleMessage intercept(Invocation invocation) throws MuleException;

The invocation parameter contains the current message and the Service object of the target
component. Developers can extract the current MuleMessage from the message and manipulate it as
needed. The intercept method must return a MuleMessage that will be passed on to the component (or
to the next interceptor in the chain).

The EnvelopeInterceptor works in the same way, except that it exposes two methods that get invoked
before and after the event processing:

MuleMessage before(Invocation invocation) throws MuleException;

MuleMessage after(Invocation invocation) throws MuleException;

Configuring Interceptors

Interceptors can be configured on your components as follows:

<service name="MyService">
<component class="org.my.ComponentImpl">
<custom-interceptor class="org.my.CustomInterceptor"/>
<logging-interceptor/>
<interceptor-stack ref="testInterceptorStack"/>
<timer-interceptor/>
</component>
</service>

You can also define interceptor stacks, which are one or more interceptors that can be referenced using a
logical name. To use an interceptor stack, you must first configure it in the global section of the Mule XML
configiration file (above the <model> element):

Document generated by Confluence on Oct 27, 2008 21:07 Page 525


<interceptor-stack name="default">
<custom-interceptor class="org.my.CustomInterceptor"/>
<logging-interceptor/>
</interceptor-stack>

You can configure multiple <interceptor> elements on your components, and you can mix using built-in
interceptors, custom interceptors, and references to interceptor stacks.

Document generated by Confluence on Oct 27, 2008 21:07 Page 526


Configuring Java Components

This page last changed on Oct 07, 2008 by ross.

Configuring Java Components


[ Object Factories ] [ Entry Point Resolvers ] [ Lifecycle Adapter Factory ] [ Bindings ] [ Configuring a
Pooled Java Component ]

Java is the default component type in Mule. Mule provides two JavaComponent implementations:
DefaultJavaComponent , which you configure with the component element, and PooledJavaComponent ,
which adds pooling functionality and which you configure with the pooled-component element. These two
implementations provide the following functionality and configuration options:

• An ObjectFactory is used to obtain the Java service component implementation.


• EntryPointResolvers can be configured to define how Mule services should invoke the component
methods when processing a message.
• A custom LifecycleAdaptor can be configured to customize the way in which the component
implementation is initialized and disposed.
• Bindings can be configured to bind component interface methods to endpoints. These endpoints are
then invoked synchronously when the method is called.

When you specify the class directly on the component or pooled-component element, the
PrototypeObjectFactory is used by default, and a new instance is created for each invocation, or a new
pooled component is created in the case of the PooledJavaComponent.

Example:

<component class="org.my.CustomComponent"/>
..
<pooled-component class="org.my.CustomComponent"/>

Alternatively, you can specify the implementation using an object factory.

Example:

<component>
<prototype-object class="org.my.CustomComponent"/>
</component>
..
<pooled-component>
<singleton-object class="org.my.CustomComponent"/>
</pooled-component>
..
<component>
<spring-object bean="myCustomComponentBean"/>
</component>

All other component configuration elements are configured as children of the component or pooled-
component element.

Note: In Mule 2.0, Java component pooling is used only if the <pooled-component> element is used. In
previous versions of Mule, pooling was the default.

Object Factories
Object factories manage both object creation in the case of a Mule instantiated instance or object look-up
from another container such as Spring via a single API.
The following object factories are included with Mule and can be configured using Mule's core schema.

<prototype-object class=..."/> PrototypeObjectFactory

Document generated by Confluence on Oct 27, 2008 21:07 Page 527


<singleton-object class=..."/> SingletonObjectFactory

<spring-object bean=..."/> SpringBeanLookup

Object factories also allow you to set properties, which are injected when a new object instance is
created.

Example:

<pooled-component>
<singleton-object class="org.my.SingletonObject">
<property key="myKey" value="theValue"/>
<property key="myKey2" value="theValue2"/>
</singleton-object>
</pooled-component>

For a real-world example of using <spring-object/>, see Using Spring Beans as Service Components.

You can easily implement additional object factories to integrate with other containers or simply to create
object instances in a different way. For more information about creating custom object factories, see
Extending Mule.

Note: Object factories replace ContainerContexts in previous versions of Mule.

Entry Point Resolvers


You can configure entry point resolvers that determine how your component is invoked when a message
is received by the service. See Developing Service Components for a more detailed description of their
functionality.

To configure entry point resolvers, you can either configure an entry point resolver set or configure a
single entry point resolver independently. When using an entry point resolver set, the order in which the
resolvers are configured is the order of of precedence they are given in run-time.

Example:

<component class="org.my.PrototypeObjectWithMyLifecycle">
<entry-point-resolver-set>
<array-entry-point-resolver/>
<callable-entry-point-resolver/>
</entry-point-resolver-set>
</component>

<component class="org.my.PrototypeObjectWithMyLifecycle">
<reflection-entry-point-resolver/>
</component>

You can also configure entry point resolvers (single or sets) on models to apply them to all services
defined in that model. You use the same configuration syntax as above but on the <model> element
instead of <component>.

Lifecycle Adapter Factory


You can configure your Java component to use a custom lifecycle adaptor. If you do not configure a
custom implementation, the default implementation will be used, which allows the optional propagation of
Mule's lifecycle to your component depending on the Mule lifecycle interfaces are implemented.

Example:

<component class="org.my.PrototypeObjectWithMyLifecycle">
<custom-lifecycle-adapter-factory class="org.my.MyLifecycleMuleAdapterFactory"/>
</component>

See Developing Service Components for more information about lifecycles.

Document generated by Confluence on Oct 27, 2008 21:07 Page 528


Bindings
Components can use bindings to call an external service during execution. The bindings used with a Java
component bind a Java interface, or single interface method, to an outbound endpoint. The external
service to be called should implement the same interface, and the component should encapsulate a
reference to that interface, which is initialized during the bootstrap stage by the Mule configuration
builder. The reference will be initialized using a reflective proxy class.

Binding can be used on Java components and script components. For more information see Component
Bindings.

Configuring a Pooled Java Component


A pooled Java component will maintain a pool of object instances that will be reused, with a single
instance being used by one thread at any one time. The configuration of component pooling is
independent of the object factory, allowing you to use whichever object factory you need.

You configure the pool using the nested pooling-profile element as shown below:

<pooled-component class="org.my.PrototypeObject">
<pooling-profile exhaustedAction="WHEN_EXHAUSTED_FAIL" initialisationPolicy="INITIALISE_ALL"
maxActive="1" maxIdle="2" maxWait="3" />
</pooled-component>

For more information about pooling and reference documentation for pooling configuration options, see
Tuning Performance.

Document generated by Confluence on Oct 27, 2008 21:07 Page 529


Configuring the Service

This page last changed on Oct 21, 2008 by jackie.wheeler.

Configuring the Service


[ Inbound ] [ Component ] [ Outbound ] [ Async Reply ] [ Exception Strategy ] [ Service Bridge ] [
Service Model ] [ Service Messaging Pattern ]

You configure services using a <service> element within a <model> element. Each <service> element
represents and configures a Mule service, providing a unique name that identifies it and optionally
an initial state that determines whether the service and its endpoints are started when Mule starts
(supported values are started, stopped, or paused).

<mule>
<model>
<service name="GreeterUMO">
...
</service>

<service name="GreeterUMO2" initialState="stopped" >


...
</service>
</model>
</mule>

Each service can be configured with the following optional elements:

• <description>: Describes the service


• <inbound>: Configures the inbound routers, their endpoints, and inbound transformers
• component: Configures the service component
• <outbound>: Configures the outbound routers, their endpoints, and outbound transformers
• <async-reply>: Configures an async reply router, which is used for asynchronous request-response
messaging
• <exception-strategy>: Configures the exception strategy for the service

If you configure more than one of these elements, note that you must configure them in the order shown
above. For detailed information on the <service> elements and attributes, see Service Configuration
Reference.

Following is a sample service configuration showing these elements:

<service name="GreeterUMO">
<description>Adds some text to the string before passing it on</description>
<inbound>
<stdio:inbound-endpoint system="IN">
<transformer ref="StdinToNameString"/>
</stdio:inbound-endpoint>
</inbound>
<component class="org.mule.example.hello.Greeter" />
<outbound>
<filtering-router>
<vm:outbound-endpoint path="chitchatter" />
<payload-type-filter expectedType="org.mule.example.hello.NameString" />
</filtering-router>
</outbound>
<default-service-exception-strategy>
<vm:outbound-endpoint path="systemErrorHandler" />
</default-service-exception-strategy>
</service>

The following sections describe these elements in more detail.

Document generated by Confluence on Oct 27, 2008 21:07 Page 530


Inbound
This element is used to configure inbound endpoints and inbound routers. Endpoints are used to receive
incoming messages, and inbound routers determine how these messages are routed. Inbound endpoints
and routers are configured separately within the <inbound> element.

Inbound Endpoints

Inbound endpoints are used to receive incoming messages. An endpoint is simply a set of instructions
indicating which transport and path/address to receive messages from, as well as any transformers,
filters, or security that should be applied when receiving the messages. You can configure multiple
inbound endpoints, each receiving message from different transports. For more information, see
Configuring Endpoints and Available Transports.

Inbound Routers

Inbound routers control and manipulate messages received by a service before passing them to the
service component. Typically, an inbound router is used to filter incoming messages, aggregate a set of
incoming messages, or re-sequence messages when they are received. Inbound routers are also used to
register multiple inbound endpoints for a service. You can chain inbound routers together, so that each
router must be matched before the message can be passed to the component. You can also configure a
catch-all strategy that is invoked if none of the routers accept the current message.

Inbound routers are different from outbound routers in that the endpoint is already known (as the
message has already been received), so the purpose of the router is to control how messages are given
to the component.

If no inbound routers are configured, by default an InboundPassThroughRouter is used to simply pass the
incoming message to the component.

Matching Only the First Router

By default, a message must match and be processed by all inbound routers in a service before it is
passed to the service component. If you want to configure the service so that the message is processed
only by the first router whose conditions it matches, you set the matchAll attribute on the <inbound>
element to false.

This behavior is new in Mule 2.0. Previously, the message was processed only by the first
matching router by default.

For more information about the inbound routers that can be used, see Mule Inbound Routers .

Inbound Example

<inbound>
<stdio:inbound-endpoint system="IN" />
<catch-all-strategy>
<jms:outbound-endpoint queue="failure.queue"/>
</catch-all-strategy>
<selective-consumer-router>
<mulexml:jxpath-filter pattern="(msg/header/resultcode)='success'"/>
</selective-consumer-router>
</inbound>

This example uses a selective consumer router that will accept a message if a 'resultcode' element has a
value of 'success'. If the message matches this filter's criteria, the message is passed to the component.
If the message does not match, the catch-all strategy is invoked, which sends the message via its
configured endpoint, in this case a JMS queue called 'failure.queue'.

Document generated by Confluence on Oct 27, 2008 21:07 Page 531


Component
The <component> element configures the service component that will be invoked after the inbound
message is processed by the inbound routers. If no component is configured, the service acts as a bridge
and simply passes messages through to the outbound router.

The following component implementations are currently available and distributed with Mule:

• A number of standard components


• <component/>: for Java components
• <pooled-component/>: for using pooled Java components
• <script:component/>: for script-based components
• <test:component/>: for testing your services (see Writing Functional Tests)

Further information about these component types and their configuration, see Configuring Components.
You can also implement new component types in your Mule modules and use them within your
configuration. In Mule 2.0, it is now easier to implement and use new non-Java component types and
configure them with their own custom component element.

Outbound
The <outbound> element configures outbound routers and their endpoints. Because outbound routers
are used to determine which endpoints to use for dispatching messages after the component has finished
processing them, outbound endpoints are configured on the outbound routers, not directly on the
<outbound> element. Outbound routers allow the developer to define multiple routing constraints for any
given message. You can specify a catch-all strategy to invoke if none of the routers accept the current
message. For more information, see Configuring Endpoints and Available Transports.

Matching All Routers

By default, a message is processed only by the first outbound router whose conditions it matches. If
you want the message to be processed by all the outbound routers, you can set the matchAll attribute
to true. For example, assume you always want to send a confirmation of a deposit back to the original
depositor. Also assume that if the deposit was above $100,000, you want to send a notification message
to the 'high net worth client manager' for possible follow-up. In this case, you would set the matchAll
attribute on the <outbound> definition as follows:

<outbound matchAll="true">
<filtering-router>
<endpoint address="jms://deposit.queue"/>
</filtering-router>
<filtering-router>
<jms:outbound-endpoint queue="large.deposit.queue"/>
<mulexml:jxpath-filter expression="deposit/amount >= 100000"/>
</filtering-router>
</outbound>

In this example, the message will always match the first router because there is no filter on it.
Additionally, the message will match the second router if the deposit amount is >= $100000, in which
case both routers will have been invoked.

For more information about the outbound routers you can use, see Mule Outbound Routers .

Outbound Example

<outbound>
<catch-all-strategy>
<jms:outbound-endpoint queue="default.queue"/>
</catch-all-strategy>
<filtering-router>
<smtp:outbound-endpoint to="exceptions@muleumo.org" subject="Exception!"
from="mule@mycompany.com!">
<transformer ref="ExceptionToEmail"/>

Document generated by Confluence on Oct 27, 2008 21:07 Page 532


</smtp:outbound-endpoint>
<payload-type-filter expectedType="java.lang.Exception"/>
</filtering-router>
<filtering-router>
<vm:endpoint path="my.component"/>
<and-filter>
<payload-type-filter expectedType="java.lang.String"/>
<regex-filter pattern="the quick brown (.*)"/>
</and-filter>
</filtering-router>
</outbound>

Async Reply
This element is used to configure the endpoints and routers that will be used to receive the response in
asynchronous request-response scenarios where you must consolidate responses from a remote endpoint
before the current service responds via its inbound endpoint. The classic example of this approach is
where a request is made and then multiple tasks are executed in parallel. Each task must finish executing
and the results processed before a response can be sent back to the requester. For an illustration of
asynchronous request-response, click here. For more information about the available Async Reply routers,
see Asynchronous Reply Routers . For information on configuring endpoints, see Configuring Endpoints.

Async Reply routers can be used to join forked tasks in a request-response call. In fact, you would
only use an async reply router with services that use synchronous calls (as there is no response
when dispatching a message asynchronously). Mule provides aggregator routers that can be used in
conjunction with a message splitter or recipient list router to aggregate messages before returning a
response. For more information on these routers, see Using Message Routers.

<async-reply>
<jms:inbound-endpoint queue="bank.quotes"/>
<custom-async-reply-router
class="org.mule.samples.loanbroker.routers.BankQuotesResponseAggregator"/>
</async-reply>

The endpoint specifies the address where responses should be sent to be processed. The router is
responsible for aggregating bank quotes into a single quote for the customer. Consider the inbound
configuration and the async-reply router in the LoanBroker configuration:

<service name="LoanBroker">
<inbound>
<vm:inbound-endpoint path="Loan.Requests"/>
</inbound>
<component class="org.mule.samples.loanbroker.SyncLoanBroker">
<outbound>
<static-recipient-list-router>
<reply-to address="jms://Loan.Quotes"/>
<message-property-filter expression="recipients!=null"/>
</static-recipient-list-router>
</outbound-router>
<async-reply>
<jms:inbound-endpoint queue="Loan.Quotes"/>
<custom-async-reply-router
class="org.mule.samples.loanbroker.routers.BankQuotesResponseAggregator"/>
</async-reply>
</mule-descriptor>

This configuration specifies that the Loan Broker will receive requests from vm://Loan.Requests and will
dispatch multiple requests to different banks via the outbound router. The bank endpoints are defined
in a List called 'recipients', which is a property on the outbound message. The important setting on
the outbound router is the <reply-to> endpoint, which tells Mule to route all responses to the jms://
Loan.Quotes endpoint, which is the endpoint on which the async-reply router is listening. When all
responses are received, the BankQuotesResponseAggregator selects the cheapest quotes and returns it.
Mule then handles returning this to the requester. The <reply-to> endpoint is applied to the next service
invoked. For example, if service1 dispatches to service2, and service1 has an outbound router with a
reply-to endpoint, service2 will send the results of its invocation to the reply-to endpoint.

Document generated by Confluence on Oct 27, 2008 21:07 Page 533


Response Transformers

If you want to transform a response message without doing any other work on the response, you set the
transformers attribute on the response router without any other routing configuration.

<response-router transformers="OrderConfirmationToXml XmlToWebPage"/>

ReplyTo

All outbound routers can have a reply-to endpoint endpoint that defines where the message should be
routed after the recipient of the message has finished processing it. The <reply-to> endpoint is applied
to the next component invoked. For example, if component1 dispatches to component2, and component1
has an outbound router with a reply-to endpoint, component2 will send the results of its invocation to
the reply-to endpoint. The <reply-to> endpoint can be any valid Mule endpoint URI and is passed along
with the message to the next component if the underlying transport supports reply-to messages. For
information on which transports support reply-to, see Available Transports.

<outbound>
<custom-router class="org.foo.ConcreteMessageSplitter">
<vm:endpoint path="component1"/>
<vm:endpoint path="vm://component2"/>
<vm:endpoint path="vm://component3"/>
<reply-to address="vm://component4"/>
</custom-router>
</outbound>

Time-outs

The Async Reply router timeout determines how long Mule should wait for replies before returning the
result. The default value is determined by the value of the default synchronous event timeout that has
been configured for the Mule instance. (For more information, see Configuration Options.) You can also
specify an independent timeout value for asynchronous replies for a given service using the optional
timeout attribute on the async-reply element.

The optional failOnTimeout attribute determines whether to throw an exception if the router times out
before all expected messages have been received. If set to false (the default), the current messages are
returned for processing.

Exception Strategy
Exception strategies are used to handle exception conditions when an error occurs during the processing
of a message. You can configure exception strategies on services. If no exception strategy is configured,
the DefaultServiceExceptionStrategy is used.

For more information on exception strategies, see Error Handling.

Service Bridge
Service component configuration is optional in Mule 2.x. The default and implicit component used is
PassThroughComponent . This component automatically bridges inbound messages to the outbound
phase and simply passes messages to the outbound routers. This approach is useful for bridging
endpoints if you want to pass a message from one transport to another.

As of Mule 2.0, you no longer need to configure an explicit BridgeComponent.

Example: Reading a file and send it's contents onto a Jms Topic.

<service name="FileToJmsBridge">

<inbound>

Document generated by Confluence on Oct 27, 2008 21:07 Page 534


<file:inbound-endpoint path="/data/in">
<file:filename-wildcard-filter pattern="*.txt"/>
</inbound-endpoint>
</inbound>

<!-- No need to configure a component here -->

<outbound>
<outbound-pass-through-router">
<jms:outbound-endpoint topic="receivedFiles"/>
</outbound-pass-through-router>
</outbound>

</service>

Service Model
By default, Mule uses the staged event-driven architecture (SEDA) model. SEDA is an architecture
model where applications consist of a network of event-driven stages connected by explicit queues.
This architecture allows services to be well-conditioned to load, preventing resources from being
overcommitted when demand exceeds service capacity. As a result, SEDA provides an efficient event-
based queuing model that maximizes performance and throughput.

See Models for more information about alternative models and information about how you can implement
your own.

Service Messaging Pattern


The messaging pattern determines the message exchange pattern that is to to be used on inbound
and outbound endpoints and allows endpoints to be configured as synchronous request/response or
asynchronous in-only as well as other patterns.

The messaging pattern is configured on endpoints, allowing multiple patterns to be used with the same
service. For more information, see Messaging Patterns.

Document generated by Confluence on Oct 27, 2008 21:07 Page 535


MEPs

This page last changed on Aug 05, 2008 by jackie.wheeler.

This document is in progress and forms part of a proposal of how messaging exchanges in
Mule should work. Not unnecessarily how they work now. See Mule Messaging Styles for
information on how Mule message exchanges work as of Mule 2.0.

Table of Contents

Click here to expand...

• Message Exchange Patterns in Mule


• ° Focus on Services
° WSDL MEPs
° Extended MEPs (WSDL 2.0)

• Mule MEPs
• ° Notation
° In-Only
° - Example Configuration
- Example Code
° In-Out
° - Example Configuration
- Example Code
° In-Out (async)
° - Example Configuration
- Example Code
° In-Optional-Out
° - Example Configuration
- Example Code
° In-Only, Out-Only
° - Example Configuration
- Example Code
° In-Only, Optional-Out
° - Example Configuration
- Example Code
° In-Out, Out-Only
° - Example Configuration
- Example Code
° In-Optional-Out, Out-Optional-In
° - Example Configuration
- Example Code
° In-Out, Out-In
° - Example Configuration
- Example Code
° In-Optional-Out, Out-Only
° - Example Configuration
- Example Code
• Advanced Patterns
• ° In-Optional-Out, Out-Only (Async Reply Router)
° - Example Configuration
- Example Code
° In-Out, Out-Only (Async Reply Router)
° - Example Configuration
- Example Code
° Orchestration using Component Bindings
° - Example Configuration
- Example Code
• What Next?
• ° Possible MuleClient Changes
° Simplifying the client

Document generated by Confluence on Oct 27, 2008 21:07 Page 536


Message Exchange Patterns in Mule
Message Exchange Patterns (MEPs) as defined as part of the WSDL specifications and provide a set of
well-defined interaction patterns between client and server. When talking about ESBs or EAI there are
typically a number of services that collaborate and the definition of which service is the client and which
is the server becomes blurred. This document describes a way of describing Mule interactions (messaging
styles) using the well-known MEPs.

Focus on Services
Web Services MEPs talk about client and server. Clients make requests to a server and (may) get a result,
whilst the server will receive data from a client (and sometimes may push data to a client). On the other
hand, Mule like other SOA-centric platforms focus on services. This means the world is viewed in terms of
data coming into and sent out of a service. The service could be viewed as a client or a server depending
on whether data flowing inbound or outbound. Thus, it makes a lot of sense to model service interactions
on the inbound and outbound separately.

The way to think about this is that we are defining MEPs between two parties, it doesn't matter if it's a
client or server, a service or legacy application that initiates or is the recipient of a request. And a request
is just an event, something that was triggered by a local or external process. By defining MEPs on the
inbound and outbound we can go on to define a set of combined MEPs (in and out) for Mule.

The diagram above shows a party (Application or Mule) that initiates a request. This gets receive by a
service inbound endpoint. Next the component is invoked and the result is routed via the outbound router
to another party (Application or Mule).

WSDL MEPs
Before we go any further lets introduce the MEPs defined in the WSDL 1.1 and WSDL 2.0 specifications.

Pattern Description

In-only This is equivalent to one-way or asynchronous. A


standard one-way messaging exchange where the
consumer sends a message to the provider that
provides only a status response.

Robust-In-Only This pattern is for guaranteed one-way message


exchanges. The consumer initiates with a
message. The provider can responds with status
or a fault. Note Guaranteed only means that the
consumer knows if the message got delivered.
Don't confuse this with reliable.

In-Out This is equivalent to request-response. A standard


two-way message exchange where the consumer
initiates with a message, the provider responds
with a message or fault.

Document generated by Confluence on Oct 27, 2008 21:07 Page 537


In-Optional-Out A standard two-way message exchange where the
provider's response is optional.

Extended MEPs (WSDL 2.0)

Pattern Description

Out-Only The provider (server) initiates the message to the


client

Robust-Out-Only The provider initiates the message to the client


and the client must respond with either a status
or a fault.

Out-In The provider initiates a call and the client must


respond.

Out-Optional-In The provider initiates the call and the client can
choose to respond.

Mule MEPs
The following sections will introduce each exchange pattern in Mule based on the convention defined
above. Each pattern will either have an inbound MEP, outbound MEP or both. It is possible to have
multiple inbound and outbound MEPS for a single service, this will be discussed later on.
For the sake of clarity each pattern is described in terms of what interactions will occur for each scenario.
For those familiar with Mule, I will provide examples of the equivalent configuration in Mule. The plan for
this document is to come up with a simpler configuration for these MEPs in Mule.

Notation
Each pattern below is presented with a diagram that depicts the message flow for the pattern using the
diagram notation above. Each pattern also has a description and further information below it. Then there
is an XML configuration for each. Note that all components are written using Groovy just so that the
components are transparent for the user. Finally, there is a code example for each which shows how a
test-case is written to test each pattern.

In-Only

Document generated by Confluence on Oct 27, 2008 21:07 Page 538


Description Receives a message from another party. No result
is expected and any result returned from the
service will be ignored.

Error Handling If an error occurs it is handled by the


ExceptionStrategy configured on either the
service or the model. An error endpoint can be
used to route errors and the party that initiated
the call can listen on the error endpoint.

Mule Config The Mule service must have an asynchronous


inbound endpoint and no outbound routers
configured.

Example Configuration

Click here to expand...


An error occurred: null. The system administrator has been notified.

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...


An error occurred: null. The system administrator has been notified.

In-Out

Description Receives a message from another party and


the result of the service invocation is returned.
If the service returns null a message with a
NullPayload payload is returned.

Error Handling A response message is always


sent back. Clients can check the
MuleMessage.getExceptionPayload() property
to get all information about the service error. If
an exception originates from the callee side, the
exception will be thrown and can be caught by the
callee.

Document generated by Confluence on Oct 27, 2008 21:07 Page 539


Mule Config The Mule service must have an synchronous
inbound endpoint and no outbound routers
configured.

Example Configuration

Click here to expand...


An error occurred: null. The system administrator has been notified.

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...


An error occurred: null. The system administrator has been notified.

In-Out (async)

Description Receives a message from another party and the


result of the service invocation is returned via
a back channel. This measn that an inbound
and response communication channel is used.
If the service returns null a message with a
NullPayload payload is returned.

Error Handling A response message is always


sent back. Clients can check the
MuleMessage.getExceptionPayload() property
to get all information about the service error. If
an exception originates from the callee side, the
exception will be thrown and can be caught by the
callee.

Mule Config The Mule service must have an asynchronous


inbound endpoint and no outbound routers
configured. Additionally the callee must
configure a MULE_REPLY_TO header or a reply
to destination understood by the transport being
used i.e. For JMS JMSReplyTo property on the
javax.jms.Message.

Document generated by Confluence on Oct 27, 2008 21:07 Page 540


Example Configuration

Click here to expand...


An error occurred: null. The system administrator has been notified.

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...


An error occurred: null. The system administrator has been notified.

In-Optional-Out

Description Receives a message from another party and the


result of the service invocation is returned. If the
service returns null and there was no error while
processing the request, nothing is returned to the
callee.

Error Handling If an error occurs while the service is


processing the request a response message
is always sent back. Clients can check the
MuleMessage.getExceptionPayload() property
to get all information about the service error. If
an exception originates from the callee side, the
exception will be thrown and can be caught by the
callee.

Mule Config The Mule service must have an synchronous


inbound endpoint and no outbound routers
configured.

Example Configuration

Click here to expand...


An error occurred: null. The system administrator has been notified.

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Document generated by Confluence on Oct 27, 2008 21:07 Page 541


Click here to expand...
An error occurred: null. The system administrator has been notified.

In-Only, Out-Only

Description Receives a message from another party but will


not return a result. The service component must
always return a result.

Error Handling If an error occurs it is handled by the


ExceptionStrategy configured on either the
service or the model. An error endpoint can be
used to route errors and the party that initiated
the call can listen on the error endpoint.

Mule Config The Mule service must have an asynchronous


inbound endpoint and at least one outbound
routers configured.

Example Configuration

Click here to expand...


An error occurred: null. The system administrator has been notified.

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...


An error occurred: null. The system administrator has been notified.

In-Only, Optional-Out

Description Receives a message from another party but will


not return a result. If the service component does

Document generated by Confluence on Oct 27, 2008 21:07 Page 542


return a result then a the result will be sent on
otherwise nothing further happens.

Error Handling If an error occurs it is handled by the


ExceptionStrategy configured on either the
service or the model. An error endpoint can be
used to route errors and the party that initiated
the call can listen on the error endpoint.

Mule Config The Mule service must have an asynchronous


inbound endpoint and at least one outbound
routers configured.

Example Configuration

Click here to expand...


An error occurred: null. The system administrator has been notified.

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...


An error occurred: null. The system administrator has been notified.

In-Out, Out-Only

Description Receives a message from another party and


returns a result from the service. Additionally
the same result will be router via the service
outbound routers.

Error Handling If an error occurs it is handled by the


ExceptionStrategy configured on either the
service or the model. An error endpoint can be
used to route errors and the party that initiated
the call can listen on the error endpoint. The
exception and context information will be attached
to the return message, however the message will
not be routed by the outbound endpoint.

Mule Config The Mule service must have a synchronous


inbound endpoint and at least one outbound
routers configured.

Example Configuration

Click here to expand...

Document generated by Confluence on Oct 27, 2008 21:07 Page 543


An error occurred: null. The system administrator has been notified.

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...


An error occurred: null. The system administrator has been notified.

In-Optional-Out, Out-Optional-In

Description Receives a message from another party. The


service processes the message and then it gets
routed via the outbound router. The outbound
router will wait for a result from the call and will
return the result to the originating party if one
is received. This pattern is analogous to using
Remote Sync on a Mule endpoint. If no result is
returned from the outbound call, null is returned.

Error Handling If an error occurs it is handled by the


ExceptionStrategy configured on either the
service or the model. An error endpoint can be
used to route errors and the party that initiated
the call can listen on the error endpoint. The
exception and context information will be attached
to the return message. If there was no result a
NullPayload message will be returned with the
exception information attached.

Mule Config The Mule service must have a synchronous


inbound endpoint and an outbound router
configured with an endpoint with 'remoteSync' set
to true.

Example Configuration

Click here to expand...


An error occurred: null. The system administrator has been notified.

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...


An error occurred: null. The system administrator has been notified.

Document generated by Confluence on Oct 27, 2008 21:07 Page 544


In-Out, Out-In

Description Receives a message from another party. The


service processes the message and then it gets
routed via the outbound router. The outbound
router will wait for a result from the call and will
return the result to the originating party if one
is received. This pattern is analogous to using
Remote Sync on a Mule endpoint. If a result is not
returned from the outbound call an error will be
thrown.

Error Handling If an error occurs it is handled by the


ExceptionStrategy configured on either the
service or the model. An error endpoint can be
used to route errors and the party that initiated
the call can listen on the error endpoint. The
exception and context information will be attached
to the return message if there is a result.

Mule Config The Mule service must have a synchronous


inbound endpoint and an outbound router
configured with an endpoint with 'remoteSync' set
to true.

Example Configuration

Click here to expand...


An error occurred: null. The system administrator has been notified.

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...


An error occurred: null. The system administrator has been notified.

Document generated by Confluence on Oct 27, 2008 21:07 Page 545


In-Optional-Out, Out-Only

Description Receives a message from another party. The


service processes the message and then it gets
routed via the outbound router. If a result is
returned from the component it is returned back
to the calling party.

Error Handling If an error occurs it is handled by the


ExceptionStrategy configured on either the
service or the model. An error endpoint can be
used to route errors and the party that initiated
the call can listen on the error endpoint. The
exception and context information will be attached
to the return message if there is a result.

Mule Config The Mule service must have a synchronous


inbound endpoint and an outbound router
configured with an endpoint.

Example Configuration

Click here to expand...


An error occurred: null. The system administrator has been notified.

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...


An error occurred: null. The system administrator has been notified.

Document generated by Confluence on Oct 27, 2008 21:07 Page 546


Advanced Patterns
In-Optional-Out, Out-Only (Async Reply Router)

Description Receives a message from another party and


processes the message. Then the message is sent
to another service (or application) for processing.
A Reply-To endpoint is attached to the message
and this is used by the second service to return
a result. Note that if the external service is not a
Mule instance the protocol being used will ahve
to ahve the notion of a back channel or reply-to
destination, i.e. JMS, WS-Addressing, Socket-bsed
protocols.
Since the response is optional, the <async-reply>
router timeout should be reduced since, it will
block for the whole time if no reply is given.
This MEP combination should ONLY be used in
low message volume scenarios. In high volume
scenarios the pattern MEPs#In-Out, Out-Only
(Async Reply Router) should be used and a
response always returned, even if it is an empty
or acknowledgment message.

Error Handling A response message is always sent back


if an error occurs. Clients can check the
MuleMessage.getExceptionPayload() property
to get all information about the service error. If
an exception originates from the callee side, the
exception will be thrown and can be caught by the
callee.

Mule Config The Mule service must have an synchronous


inbound endpoint, at least outbound routers
configured with a reply-to endpoint and an
Async Reply router to listen on the reply to
endpoint. Only the inbound endpoint needs to be
synchronous al others can be asynchronous.

Example Configuration

Click here to expand...


An error occurred: null. The system administrator has been notified.

Document generated by Confluence on Oct 27, 2008 21:07 Page 547


Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...


An error occurred: null. The system administrator has been notified.

In-Out, Out-Only (Async Reply Router)

Description Receives a message from another party and


processes the message. Then the message is sent
to another service (or application) for processing.
A Reply-To endpoint is attached to the message
and this is used by the second service to return
a result. Note that if the external service is not a
Mule instance the protocol being used will need
to have the notion of a back channel or reply-
to destination, i.e. JMS, WS-Addressing, Socket-
based protocols.

Error Handling A response message is always


sent back. Clients can check the
MuleMessage.getExceptionPayload() property
to get all information about the service error. If
an exception originates from the callee side, the
exception will be thrown and can be caught by the
callee.

Mule Config The Mule service must have an synchronous


inbound endpoint, at least outbound routers
configured with a reply-to endpoint and an
Async Reply router to listen on the reply to
endpoint. Only the inbound endpoint needs to be
synchronous al others can be asynchronous.

Example Configuration

Click here to expand...


An error occurred: null. The system administrator has been notified.

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...

Document generated by Confluence on Oct 27, 2008 21:07 Page 548


An error occurred: null. The system administrator has been notified.

Orchestration using Component Bindings

TODO

Example Configuration

Click here to expand...


An error occurred: null. The system administrator has been notified.

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...


An error occurred: null. The system administrator has been notified.

What Next?
Mule can model every MEP combination that makes sense. What is difficult in Mule right now it to know
how to do this. The logical next step would be to change the way endpoints are configured. Instead,
of having the synchronous and remoteSync attributes on the endpoint, users could set an exchange
attribute that would define one of the options above. There are some obvious benefits:

• This method removes the complexity of the current configuration options


• Using well defined exchange patterns explicitly will have readability of Mule configurations
• Mule can provide much better validation over the correct MEP combinations that can be used with
different transports.

For example, depending on the transport being used developers could define endpoints such as:

<jms:inbound-endpoint queue="my.queue" exchange="In-Only"/>

<http:inbound-endpoint host="localhost" port="8080" path="/mule" exchange="In-Out"/>

Obviously, there would be a similar method for defining outbound endpoints:

<jms:outbound-endpoint queue="my.queue" exchange="Out-Only"/>

<http:inbound-endpoint host="localhost" port="8080" path="/mule" exchange="Out-In"/>

Document generated by Confluence on Oct 27, 2008 21:07 Page 549


Possible MuleClient Changes
The Mule client is a common way for users to interact with Mule services. The MuleClient provides a
number of interfaces for sending or requesting information from an endpoint. These methods such as
MuleClient.send, MuleClient.dispatch, MuleClient.request determine how the request is made.
For example, using the send() methods causes a synchronous request and returns a result. Whilst
dispatch() causes an asynchronous request and does not return a result. So right now the MuleClient is
partly responsible (from the client-side) for how a MEP works in Mule.

Simplifying the client


If Mule can have a MEP defined on the inbound and outbound, it become redundant to have these
additional methods on the MuleClient. Instead, we could have a single exchange interface that will honour
the request based on the MEPs configured on the endpoints involved.

The Mule client code may look something like this:

MuleClient2 client = new MuleClient2();


MuleExchange exchange = client.invoke("jms://topic:in", "some data", null);

MuleMessage result = exchange.getNextResultMessage();


assertNotNull(result);
assertEquals("some data received", result.getPayload());
assertEquals(1, exchange.getresultsSize());
//Get message history
assertEquals("some data", exchange.getSourceMessage().getPayload());

The MuleExchange object here provides an interface for all messages generated from the invocation.

If we wanted to configure the MuleExchange we might do the following:

MuleClient2 client = new MuleClient2();


MuleExchange exchange = client.createExchange();
exchange.setEnableHistory(false);
client.invoke(exchange, "jms://topic:in", "some data", null);

MuleMessage result = exchange.getNextResultMessage();


assertNotNull(result);
assertEquals("some data received", result.getPayload());
assertEquals(1, exchange.getresultsSize());
//Message History disabled
assertNull(exchange.getSourceMessage());

Document generated by Confluence on Oct 27, 2008 21:07 Page 550


Mule Messaging Styles

This page last changed on Sep 18, 2008 by jackie.wheeler.

Mule Messaging Styles


[ Overview ] [ Asynchronous ] [ Request Response ] [ Synchronous ] [ Remote Synchronous ] [ Async
Request Response ]

Overview
Mule can send messages asynchronously (each stage of the message is on a different thread) or
synchronously (after the message is received by the component, it uses a single thread throughout the
rest of its lifecycle and supports request-response). You can set the synchronous property on the model,
on the endpoint, and implicitly within the transport.

By default, Mule uses SEDA, which uses asynchronous staged queues. One thread is used for the inbound
message, another thread is used for processing the message in the service component, and another
thread is used for the outbound message. You can configure the message so that the inbound message
is on one thread and the remaining stages are on a second thread, or so that all stages are on a single
thread.

Mule also supports the request-response messaging style. In this case, there is no outbound router, so
the message is sent back to the same endpoint as the inbound endpoint, providing a reply back to the
sender.

You can use a mix of synchronous and asynchronous messaging styles throughout Mule. You can also
use a mix of styles for a single service component. For example, a service component can have multiple
outbound routers that route to different endpoints depending on filter criteria, and you might want the
message to be sent synchronously in some cases and asynchronously in others.

The rest of this page describes the various messaging styles in more detail and how to configure them. It
includes reference to the message exchange patterns (MEPs) that each message style supports. For more
information on MEPs and Mule, see MEPs.

Asynchronous

Description Receives a message and puts it on a SEDA queue.


The callee thread returns and the message is
processed by the SEDA thread pool. Nothing gets
returned from the result of the call.

Error Handling If an error occurs it is handled by the Mule server.


An error endpoint can be used to route errors and
the client that initiated the call can listen on the
error queue in a separate thread, other have a
specific error handling client.

Document generated by Confluence on Oct 27, 2008 21:07 Page 551


Mule Config The Mule service must have an asynchronous
inbound endpoint.

Equivalent MEPs In-only

Discussion Points • We have no way of supporting Robust In-


only MEP outside of web services (where in
Mule you would use Request/Response) and
define the MEP in the service contract.

Example Configuration

Click here to expand...


An error occurred: null. The system administrator has been notified.

Request Response

Description Receives a message and the component returns a


message. If the component call returns null, then
a MuleMessage with a NullPayload is returned.
If the call method is void the request message is
returned.

Mule Config The Mule service must have a synchronous


inbound endpoint and no outbound endpoint
configured.

Error Handling A response message is always


sent back. Clients can check the
MuleMessage.getExceptionPayload() to get
all information about the server-side error. If
an exception originates from the client call, the
exception will be thrown.

Equivalent MEPs In-Out, In-Optional-Out

Discussion Points • In-Optional-Out returns the request message


if there is no result from the call. This is
confusing.

Example Configuration

Click here to expand...


An error occurred: null. The system administrator has been notified.

Document generated by Confluence on Oct 27, 2008 21:07 Page 552


Synchronous

Description Receives a message and the component processes


before sending it out on another endpoint. The
synchronous call must be used if transactions
are being used on the inbound endpoint. The
odd behaviour right now is that a Synchronous
call always returns a result, even if there is an
outbound endpoint.

Mule Config The Mule service must have a synchronous


inbound endpoint and an outbound endpoint
configured.

Error Handling A response message is always


sent back. Clients can check the
MuleMessage.getExceptionPayload() to get
all information about the server-side error. If
an exception originates from the client call, the
exception will be thrown.

Equivalent MEPs In-Only, In-Optional-Out, In-Out

Discussion Points • Mule will aways return the result the


component returned back to the callee as
well as sending it out via the outbound
endpoint. This causes some confusion.

Example Configuration

Click here to expand...


An error occurred: null. The system administrator has been notified.

Remote Synchronous

Description Receives a message and the component processes


before sending it out on another endpoint.
The request happens in the same thread. Mule
blocks on at the outbound endpoint to wait for
a response from the remote application. Some
protocols do not support a reply channel and Mule
will ignore the remoteSync if this is the case.

Document generated by Confluence on Oct 27, 2008 21:07 Page 553


Mule Config The Mule service must have a synchronous
inbound endpoint and an outbound endpoint
configured. The inbound endpoint or the outbound
endpoint should have 'remoteSync' configured to
true.

Error Handling A response message is always


sent back. Clients can check the
MuleMessage.getExceptionPayload() to get
all information about the server-side error. If
an exception originates from the client call, the
exception will be thrown.

Equivalent MEPs In-Out, In-Optional-Out

Discussion Points • Need to clean up configuration semantics of


remoteSync
• RemoteSync validation is silent

Example Configuration

Click here to expand...


An error occurred: null. The system administrator has been notified.

Async Request Response

Description This pattern enables Request Response messaging


and allows the back-end process to be forked to
invoke other services and return a result based
on the results of multiple service invocations. The
Async Reply Router is used to listen on a Reply To
endpoint for results.

Mule Config A <async-reply> element can be used to listen


on a reply endpoint. There must also be at least
one outbound endpoint and the inbound endpoint
must be synchronous.

Error Handling A response message is always


sent back. Clients can check the
MuleMessage.getExceptionPayload() to get
all information about the server-side error. If
an exception originates from the client call, the
exception will be thrown.

Equivalent MEPs In-Out, In-Optional-Out

Discussion Points None

Document generated by Confluence on Oct 27, 2008 21:07 Page 554


Example Configuration

Click here to expand...


An error occurred: null. The system administrator has been notified.

Document generated by Confluence on Oct 27, 2008 21:07 Page 555


Using Message Routers

This page last changed on Oct 21, 2008 by jackie.wheeler.

Using Message Routers


[ Quick Reference ] [ Mule Inbound Routers ] [ Mule Outbound Routers ] [ Asynchronous Reply Routers ]
[ Catch-all Strategies ] [ Filters ]

Message routers are used to control how events are sent and received by components in the system.
Mule defines inbound routers that apply to events as they are received and outbound routers that are
invoked when an event is being dispatched.

Mule provides flexible message routing support for your components. Routing features are based on the
enterprise routing requirements described in EIP.

For information on how your Java or Script components can orchestrate messages, see Component
Bindings.

Quick Reference

Inbound Routers Outbound Routers Async-Reply Routers Catch All Strategies

No Router Pass-through Single Forwarding

Selective Consumer Filtering Collection Custom Fowarding

Idempotent Receiver Static Recipient List Custom Logging

Idempotent Secure Multicasting Custom


Hash Receiver

Collection Aggregator Chaining

Message Chunking List Message Splitter


Aggregator

Custom Correlation Filtering Xml Message


Aggregator Splitter

Forwarding Message Chunking


Router

WireTap Exception Based Router

Custom Endpoint Template

Custom

Mule Inbound Routers


When a message is received via an endpoint, the inbound router controls how and if this message gets
routed into the service. The following sections describe the Mule inbound routers and how to configure
them. For more detailed information on inbound router configuration elements and attributes, see the
Inbound Router Configuration Reference.

All inbound routers are configured on a service within the <inbound> element.

Document generated by Confluence on Oct 27, 2008 21:07 Page 556


No Router

If no router is defined on the inbound all events received via the endpoints will be processed by the
service component.

<inbound>
<jms:inbound-endpoint queue="foo.bar"/>
<vm:inbound-endpoint path="foo.bar.local"/>
</inbound>

Selective Consumer

A selective consumer is an inbound router that can apply one or more filters to the incoming message. If
the filters match, the message is forwarded to the component. Otherwise, the message is forwarded to
the catch-all strategy on the router. If no catch-all is configured, the message is ignored and a warning is
logged.

Configuration for this router is as follows:

<inbound>
<selective-consumer-router>
<mulexml:jxpath-filter expression="msg/header/resultcode = 'success'"/>
</selective-consumer-router>
<forwarding-catch-all-strategy>
<jms:endpoint topic="error.topic"/>
</forwarding-catch-all-strategy>
</inbound>

For information on using filters with this router, see Using Filters. Note that by default the filter is applied
to the message after the inbound transformers are applied. If you need to execute filters on the message
without applying any transformation, you can set the transformFirst property on this router to control
whether transformations are applied.

<inbound>
<forwarding-catch-all-strategy>
<jms:endpoint topic="error.topic"/>
</forwarding-catch-all-strategy>
<selective-consumer-router transformFirst="false">
<mulexml:jxpath-filter expression="msg/header/resultcode = 'success'"/>
</selective-consumer-router>
</inbound>

Idempotent Receiver

An idempotent receiver ensures that only unique messages are received by a service by checking the
unique ID of the incoming message. The ID can be generated from the message using an expression
defined in the idExpression attribute. By default, the expression used is ${message:id}, which
means the underlying endpoint must support unique message IDs for this to work. Otherwise, a
UniqueIdNotSupportedException is thrown.

There is a simple idempotent receiver implementation provided at


org.mule.routers.inbound.IdempotentReceiver . The default implementation uses a simple file-based
mechanism for storing message IDs, but you can extend this class to store the IDs in a database instead.

Configuration for this router is as follows:

<inbound>
<idempotent-receiver-router idExpression="#[message:id]-#[header:foo]">
<simple-text-file-store directory="./idempotent"/>
</idempotent-receiver-router>
</inbound>

Document generated by Confluence on Oct 27, 2008 21:07 Page 557


The optional idExpression attribute determines what should be used as the unique message ID. If this
attribute is not used, #[message:id] is used by default.

The nested element shown above configures the location where the received message IDs are stored.
In this example, they are stored to disk so that the router can remember state between restarts. If the
directory attribute is not specified, the default value used is ${mule.working.dir}/objectstore where
mule.working.dir is the working directory configured for the Mule instance. For more information, see
Configuration Options.

If no store is configured, the InMemoryObjectStore is used by default.

Idempotent Secure Hash Receiver

This router ensures that only unique messages are received by a service by calculating the hash of the
message itself using a message digest algorithm. This approach provides a value with an infinitesimally
small chance of a collision and can be used to filter message duplicates. Note that the hash is calculated
over the entire byte array representing the message, so any leading or trailing spaces or extraneous
bytes (like padding) can produce different hash values for the same semantic message content.
Therefore, you should ensure that messages do not contain extraneous bytes. This router is useful when
the message does not support unique identifiers.

Configuration for this router is as follows:

<inbound>
<secure-hash-idempotent-receiver-router messageDigestAlgorithm="SHA26">
<simple-text-file-store directory="./idempotent"/>
</secure-hash-idempotent-receiver-router>
</inbound>

Idempotent Secure Hash Receiver also uses object stores, which are configured the same way as the
Idempotent Receiver. The optional messageDigestAlgorithm attribute determines the hashing algorithm
that will be used. If this attribute is not specified, the default algorithm SHA-256 is used.

Collection Aggregator

Some outbound routers assign a correlation ID to messages when they are dispatched. The Collection
Aggregator groups incoming messages with matching correlation IDs into a MuleMessageCollection.
MuleMessageCollection extends MuleMessage and provides additional methods for working with a
collection of messages. You can specify the timeout attribute to determine how long the router waits in
milliseconds for messages to complete the group. The size of the message group is determined by the
correlationGroupSize attribute.

The aggregator is based on the Selective Consumer, so you can also apply filters to the messages.

Configuration for this router is as follows:

<inbound>
<collection-aggregator-router timeout="6000">
<payload-type-filter expectedType="org.foo.some.Object"/>
</collection-aggregator-router>
</inbound>

Message Chunking Aggregator

This aggregator combines messages that have the same correlation ID into a single message. Correlation
IDs are set on messages when they are dispatched by certain outbound routers such as the Recipient
List and List Message Splitter routers. These messages can be aggregated back together again using this
router.

This aggregator is based on the Selective Consumer, so filters can also be applied to messages.

Configuration for this router is as follows:

Document generated by Confluence on Oct 27, 2008 21:07 Page 558


<inbound>
<message-chunking-aggregator-router>
<message-info-mapping correlationId="##" />
<payload-type-filter expectedType="org.foo.some.Object"/>
</message-chunking-aggregator-router>
</inbound>

The optional message-info-mapping element allows you to identify the correlation ID in the message
using an expression. If this element is not specified, MuleMessage.getCorrelationId() is used.

Custom Correlation Aggregator

This router is used to configure a custom message aggregator. Mule provides an abstract implementation
that has a template method that performs the message aggregation. A common use of the aggregator
router is to combine the results of multiple requests such as "ask this set of vendors for the best price of
X".

The aggregator is based on the Selective Consumer, so you can also apply filters to messages.

Configuration for this router is as follows:

<inbound>
<custom-collection-aggregator-router class="org.mule.CustomAgregator">
<payload-type-filter expectedType="org.foo.some.Object"/>
</custom-collection-aggregator-router>
</inbound>

There is an AbstractEventAggregator that provides a thread-safe implementation for custom aggregators,


which you can can use to write a custom aggregator router. For example, the Loan Broker examples
included in the Mule distribution use a custom BankQuotesInboundAggregator router to aggregate bank
quotes.

Correlation Resequencer

The Correlation Resequencer Router will hold back a group of messages and resequence them using the
messages correlation sequence property. A java.util.Comparator is used to sort the events. This router
is based on the Selective Consumer, which means that filters can be applied to the incoming events.

<inbound>
<correlation-resequencer-router>
<mulexml:jxpath-filter expression="msg/header/resultcode = 'success'"/>
</correlation-resequencer-router>
</inbound>

Forwarding Router

This router allows messages to be forwarded to an outbound router without first being processed by a
component. It essentially acts as a bridge between an inbound and an outbound endpoint. This is useful
in situations where the developer does not need to execute any logic on the inbound event but does
need to forward it on to a component residing on another destination (such as a remote Mule node or
application) over the network.

Configuration for this router is as follows:

<service name="FileReader">
<inbound>
<file:inbound-endpoint path="/temp/myfiles/in"/>
<forwarding-consumer-router/>
</inbound>
<echo-component/>
<outbound>
<tcp:outbound-endpoint host="192.168.0.6" port="12345">

Document generated by Confluence on Oct 27, 2008 21:07 Page 559


<object-to-byte-array-transformer/>
</tcp:outbound-endpoint>
</outbound>
</service>

When a file becomes available on the local file system, an event is triggered that creates the
message, which is then automatically forwarded via TCP to 192.168.0.6. Notice that there is an
outboundTransformer configured. This will be used to transform the event's payload before it is
dispatched over TCP. There is an echo component configured, but when the forwarding consumer is used,
the component invocation is skipped, and the message is forwarded directly the the outbound router(s).

Configuring the service as a bridge is recommended for most forwarding scenarios. However, if you need
to selectively forward only some events while others are processed by the component, you will need to
use this router.

The Forwarding Consumer router extends the Selective Consumer, so you can configure filters on this
router.

Wiretap Router

See Using the WireTap Inbound Router.

Custom Inbound Router

You can configure custom inbound routers by specifying the custom router class on the <custom-
inbound-router> element and by using Spring properties. Optionally, you can also configure an
outbound endpoint in case this is needed for implementing a custom wiretap router for example.

Configuration for this router is as follows:

<inbound>
<custom-inbound-router class="org.my.CustomInboundRouter">
<mulexml:jxpath-filter expression="msg/header/resultcode = 'success'"/>
<spring:properties>
<spring:property key="key1" value="value1"/>
<spring:property key="key2" value="value2"/>
</spring:properties>
<vm:outbound-endpoint path="out"/>
</custom-inbound-router>
</inbound>

Mule Outbound Routers


After a message has been processed by a component, you use outbound routers to determine where to
send the message next. The following sections describe each Mule outbound router and how to configure
them. Outbound routers can be more complex to configure, as they allow different routing paths that
can be selected depending on the logic defined in one or more filters. For more detailed information
on outbound router configuration elements and attributes, see the Outbound Router Configuration
Reference.

Pass-through Router

This router always matches and simply sends or dispatches message via the one endpoint it has
configured.

Configuration for this router is as follows:

2.0:

<outbound>
<outbound-pass-through-router>

Document generated by Confluence on Oct 27, 2008 21:07 Page 560


<smtp:outbound-endpoint to="ross@muleumo.org"/>
</outbound-pass-through-router>
</outbound>

2.1:

<outbound>
<pass-through-router>
<smtp:outbound-endpoint to="ross@muleumo.org"/>
</pass-through-router>
</outbound>

Filtering Router

This router uses filters to route only those messages that meet specific criteria to the endpoint configured
on the router. All Mule outbound routers, except the pass-through router described above, extend
FilteringOutboundRouter, so you can always apply a filter to an outbound router.

Configuration for this router is as follows:

<outbound>
<forwarding-catch-all-strategy>
<jms:outbound-endpoint queue="error.queue"/>
</forwarding-catch-all-strategy>
<filtering-router>
<smtp:outbound-endpoint to="ross@muleumo.org"/>
<payload-type-filter expectedType="java.lang.Exception"/>
</filtering-router>
<filtering-router>
<jms:outbound-endpoint queue="string.queue"/>
<and-filter>
<payload-type-filter expectedType="java.lang.String"/>
<regex-filter pattern="the quick brown (.*)"/>
</and-filter>
</filtering-router>
</outbound>

The filter is applied to the message first, and then the transformers are applied. If you need to transform
the message before the filter is applied, you can set a transformer on this router that will be applied to
the message before the filter is applied.

<outbound>
<filtering-router>
<smtp:outbound-endpoint to="ross@muleumo.org"/>
<payload-type-filter expectedType="java.lang.Exception"/>
<transformer ref="aTransformer"/>
</filtering-router>
</outbound>

Recipient List Router

The recipient list router can be used to send the same message to multiple endpoints over a single
endpoint, or to implement routing-slip behavior where the next destination for the message is determined
from message properties or the payload. Mule provides an abstract recipient list implementation
org.mule.routing.outbound.AbstractRecipientList , which provides a thread-safe base for specialized
implementations.

Mule also provides a static recipient list router that takes a configured list of endpoints from the current
message or from a statically declared list on the endpoint.

Configuration for this router is as follows:

<outbound>
<static-recipient-list-router>

Document generated by Confluence on Oct 27, 2008 21:07 Page 561


<payload-type-filter expectedType="javax.jms.Message"/>
<recipients>
<spring:value>jms://orders.queue</spring:value>
<spring:value>jms://tracking.queue</spring:value>
</recipients>
</static-recipient-list-router>
</outbound>

Multicasting Router

The Multicasting router can be used to send the same message over multiple endpoints. When using
this router, be sure to configure the correct transformers on the endpoints to handle the message source
type.

Configuration for this router is as follows:

<outbound>
<multicasting-router>
<jms:endpoint queue="test.queue" transformer-refs="StringToJmsMessage"/>
<http:endpoint host="10.192.111.11" transformer-refs="StringToHttpClientRequest"/>
<tcp:endpoint host="10.192.111.12" transformer-refs="StringToByteArray"/>
<payload-type-filter expectedType="java.lang.String"/>
</multicasting-router>
</outbound>

Chaining Router

The Chaining router can be used to send the message through multiple endpoints using the result of the
first invocation as the input for the next. For example, this can be useful where you want to send the
results of a synchronous request-response invocation such as a Web service call to a JMS queue. Endpoint
transformers can be used to transform the message to the format the next endpoint requires.

Configuration for this router is as follows:

<outbound>
<chaining-router>
<axis:outbound-endpoint address="http://localhost:8081/services/xyz?method=getSomething"/>
<jms:outbound-endpoint queue="something.queue">
<transformer ref="SomethingToJmsMessage"/>
</jms:outbound-endpoint>
</chaining-router>
</outbound>

List Message Splitter

A message splitter can be used to break down an outgoing message into parts and dispatch those parts
over different endpoints configured on the router. The List Message Splitter accepts a list of objects that
will be routed to different endpoints. The actual endpoint used for each object in the list is determined by
a filter configured on the endpoint itself. If the endpoint's filter accepts the object, the endpoint will be
used to route the object.

By default the AbstractMessageSplitter sets a correlation ID and correlation sequence on the outbound
events so that inbound routers such as the Collection Aggregator or Correlation Resequencer are able to
resequence or combine the split messages.

The router configuration below expects the message payload to be a java.util.List and will route
objects in the list that are of type com.foo.Order, com.foo.Item, and com.foo.Customer. The router will
allow any number and combination of these objects.

Configuration for this router is as follows:

<outbound>

Document generated by Confluence on Oct 27, 2008 21:07 Page 562


<list-message-splitter-router">
<jms:outbound-endpoint queue="order.queue">
<payload-type-filter expectedType="com.foo.Order"/>
</jms:outbound-endpoint>
<jms:outbound-endpoint queue="item.queue">
<payload-type-filter expectedType="com.foo.Item"/>
</jms:outbound-endpoint>
<jms:outbound-endpoint queue="customer.queue">
<payload-type-filter expectedType="com.foo.Customer"/>
</jms:outbound-endpoint>
<payload-type-filter expectedType="java.util.List"/>
</list-message-splitter-router>
</outbound>

Note that there is also a filter on the router itself that ensures that the message payload received is
of type java.util.List. If there are objects in the list that do not match any of the endpoint filters,
a warning is written to the log and processing continues. To route any non-matching object types to
another endpoint, add the endpoint at the end of the list without a filter.

Filtering XML Message Splitter

This router is similar to the List Message Splitter but operates on XML documents. Supported payload
types are:

• org.dom4j.Document objects
• byte[]
• java.lang.String

If no match is found, it is ignored and logged at the WARN level.

The router splits the payload into nodes based on the splitExpression property. The actual endpoint
used for each object in the list is determined by a filter configured on the endpoint itself. If the endpoint's
filter accepts the object, the endpoint will be used to route the object. Each part returned is actually
returned as a new DOM4J document.

The router can optionally perform a validation against an external XML schema document. To perform the
validation, set externalSchemaLocation to the XSD file in your classpath. Setting this property overrides
whatever schema document you declare in the XML header.

Configuration for this router is as follows:

<outbound>
<mulexml:message-splitter splitExpression="root/nodes" validateSchema="true"
externalSchemaLocation="/com/example/TheSchema.xsd">
<vm:outbound-endpoint path="order">
<payload-type-filter expectedType="com.foo.Order"/>
</vm:outbound-endpoint>
<vm:outbound-endpoint path="item">
<payload-type-filter expectedType="com.foo.Item"/>
</vm:outbound-endpoint>
<vm:outbound-endpoint path="customer">
<payload-type-filter expectedType="com.foo.Customer"/>
</vm:outbound-endpoint>
<payload-type-filter expectedType="org.dom4j.Document"/>
</mulexml:message-splitter>
</outbound>

Message Chunking Outbound Router

This routing pattern allows you to split a single message into a number of fixed-length messages that
will all be routed to the same endpoint. It will split the message up into a number of smaller chunks
according to the messageSize attribute that you configure for the router. If you do not configure a
messageSize, or if it has a value of zero, the message will not be split up and the entire message will be
routed to the destination endpoint as is. The router splits up the message by first converting it to a byte

Document generated by Confluence on Oct 27, 2008 21:07 Page 563


array and then splitting this array into chunks. If the message cannot be converted into a byte array, a
RoutingException is raised.

A message chunking router is useful if you have bandwidth problems (or size limitations) when using
a particular transport. If you want to be able to route different segments of the original message to
different endpoints, consider using the List Message Splitter or Filtering Xml Message Splitter router
instead.

To put the chunked items back together again, you can use the Message Chunking Aggregator as the
inbound router on the next service.

Sample Configuration

<service name="chunkingService">
<inbound>
<vm:inbound-endpoint path="fromClient"/>
</inbound>
<outbound>
<message-chunking-router messageSize="4">
<vm:outbound-endpoint path="toClient"/>
</message-chunking-router>
</outbound>
</service>

In the example above, any data received on the vm fromClient endpoint is chunked into messages four
bytes long before being sent along the vm toClient endpoint. If we sent "The quick brown fox jumped
over the lazy dog" to this service, anything listening on the vm toClient endpoint would receive the
following messages (the spaces have been replaced with underscores for better legibility):

Message # Contents

1 The_

2 quic

3 k_br

4 own_

5 fox_

6 jump

7 ed_o

8 ver_

9 the_

10 lazy

11 _dog

Exception Based Router

The Exception Based router can be used to send a message over an endpoint by selecting the first
endpoint that can connect to the transport. This can be useful for setting up retries. When the first
endpoint fails, the second will be invoked, and if that fails, it will try the next endpoint. Note that this
router overrides the endpoint mode to synchronous while looking for a successful send and will resort to
using the endpoint's mode for the last item in the list.

Configuration for this router is as follows:

Document generated by Confluence on Oct 27, 2008 21:07 Page 564


<outbound>
<exception-based-router>
<tcp:endpoint host="10.192.111.10" port="10001" />
<tcp:endpoint host="10.192.111.11" port="10001" />
<tcp:endpoint host="10.192.111.12" port="10001" />
</exception-based-router>
</outbound>

Endpoint Template Router

The endpoint template router allows endpoints to be altered at runtime based on properties set on the
current event or fallback values set on the endpoint properties. Templated values are expressed using
square braces around a property name, such as:

axis:http://localhost:8082/MyService?method=[SOAP_METHOD]

Configuration for this router is as follows:

<outbound>
<endpoint-template-router address="foobar://server:1234/path/path/path?
param1=[header1]&param2=[header2]"/>
</outbound>

The header1 and header2 parameters are substituted with the actual values from the current message.
The parameters can be used only in the query string, as the square brackets are not valid characters for
the authority and path URI components.

Custom Outbound Router

You can configure custom outbound routers by specifying the custom router class on the <custom-
outbound-router> element and by using Spring properties.

Configuration for this router is as follows:

<outbound>
<custom-outbound-router class="org.my.CustomOutboundRouter" transformers-ref="Transformer1">
<tcp:endpoint host="10.192.111.10" port="10001" />
<tcp:endpoint host="10.192.111.11" port="10001" />
<mulexml:jxpath-filter expression="msg/header/resultcode = 'success'"/>
<spring:properties>
<spring:property key="key1" value="value1"/>
<spring:property key="key2" value="value2"/>
</spring:properties>
</custom-outbound-router>
</outbound>

Asynchronous Reply Routers


Asynchronous reply routers are used in request/response scenarios where message traffic is triggered
by a request and the traffic needs to be consolidated before a response is given. The classic example of
this is where a request is made and tasks are executed in parallel. Each task must finish executing and
the results processed before a response can be sent back. For detailed information on the elements you
configure for asynchronous reply routers, see Asynchronous Reply Router Configuration Reference.

Asynchronous reply routers are configured as follows:

<async-reply failOnTimeout="false" timeout="2000">


<inbound-endpoint ref="replyEndpoint"/>
<collection-async-reply-router/>
</async-reply>

Document generated by Confluence on Oct 27, 2008 21:07 Page 565


The timeout attribute determines how long to wait for replies to be received. The failOnTimeout
attribute determines if an exception should be thrown or if, in the case of the collection reply router, the
messages received so far should be returned to the service.

Single Asynchronous Reply

The Single Asynchronous Reply router configures a single response router. This router returns the first
message it receives on a reply endpoint and discards the rest.

<single-async-reply-router/>

Collection Asynchronous Reply

The Collection Asynchronous Reply router configures a collection response router. This router returns a
MuleMessageCollection message type that contains all messages received for the current correlation.

<collection-async-reply-router/>

Custom Asynchronous Reply

The Custom Asynchronous Reply router allows you to configure a custom asynchronous reply router. To
configure the custom router, set the class attribute to the custom router class.

<custom-async-reply-router class="org.mule.CustomAsyncReplyRouter"/>

Catch-all Strategies
You can configure a catch-all strategy that will be invoked if no routing path can be found for the current
message. An inbound or outbound endpoint can be associated with a catch-all strategy so that any
orphaned messages can be caught and routed to a common location. For detailed information on the
elements you configure for catch-all strategies, see Catch All Strategy Configuration Reference.

For example:

<service name="dataService">
<inbound-endpoint address="vm://in2" connector-ref="vmQueue">
<string-to-byte-array-transformer/>
</inbound-endpoint>

<selective-consumer-router>
<payload-type-filter expectedType="java.lang.Integer"/>
</selective-consumer-router>

<custom-forwarding-catch-all-strategy
class="org.mule.test.usecases.routing.InboundTransformingForwardingCatchAllStrategy">
<outbound-endpoint address="vm://catchall" connector-ref="vmQueue">
<string-to-byte-array-transformer/>
</outbound-endpoint>
</custom-forwarding-catch-all-strategy>
</inbound>
...
<outbound>
<filtering-router transformer-refs="TestCompressionTransformer">
<outbound-endpoint address="test://appleQ2" name="TestApple-Out" />
<payload-type-filter expectedType="java.lang.String" />
</filtering-router>
<custom-catch-all-strategy class="org.mule.tck.testmodels.mule.TestCatchAllStrategy" />
</outbound>
...
</service>

Document generated by Confluence on Oct 27, 2008 21:07 Page 566


Following are descriptions of the different catch-all strategies you can use.

Forwarding

This catch-all strategy is used to forward the event to an endpoint that is configured if no outbound
routers match.

<forwarding-catch-all-strategy>
<jms:outbound-endpoint queue="error.queue"/>
</forwarding-catch-all-strategy>

Custom Forwarding

This catch-all strategy is the same as the default forwarding catch-all strategy, but it allows you to specify
a custom implementation to use by configuring the class attribute. You can also configure additional
optional properties.

<custom-forwarding-catch-all-strategy class="org.my.CustomForwardingCatchAllStrategy">
<jms:outbound-endpoint queue="error.queue"/>
<spring:property key="myProperty" value="myValue"/>
</forwarding-catch-all-strategy>

Logging

This catch-all strategy does nothing with the message and simply logs a warning indicating that the
message was not dispatched because there was no routing path defined.

<logging-catch-all-strategy/>

Custom

This catch-all strategy allows you to use a custom class to perform whatever behavior you require. To
implement a custom catch-all strategy that forwards the message to an endpoint, you should used the
custom forwarding catch-all strategy instead.

<custom-catch-all-strategy/>

Filters
Filters provide the logic used to invoke a particular router. Filters can be combined using the logic filters
AndFilter, OrFilter, and NotFilter. Not all routers need to use filters, but all routers support them. See
Using Filters for complete information.

Document generated by Confluence on Oct 27, 2008 21:07 Page 567


Component Bindings

This page last changed on Oct 07, 2008 by jackie.wheeler.

Component Bindings
[ Java Component Binding Configuration ] [ Script Component Bindings ]

Components can use bindings to call an external service during execution. The bindings used with a Java
component bind a Java interface, or single interface method, to an outbound endpoint. The external
service to be called should implement the same interface, and the component should encapsulate a
reference to that interface, which is initialized during the bootstrap stage by the Mule configuration
builder. The reference will be initialized using a reflective proxy class.

Cannot resolve external resource into attachment.

With component bindings, you can configure multiple interfaces or a single interface with an endpoint
bound to one or more Mule endpoints.

Note that Mule currently supports component bindings for Java components (the default components in
Mule) and script components, such as Groovy or JRuby. This page describes how to configure each.

Java Component Binding Configuration


Bindings can be used by components to call out to an external service. The bound interface is added to
the component as a field with the usual bean getter and setter methods. In the binding configuration for
the component, you can bind this interface along with a method in the interface to a Mule endpoint. When
that method is called, the call parameters are sent over the Mule endpoint to another service, which
may be local or remote. A result may be returned from the service and passed back to the component
using the return argument of the method. This model is very similar to traditional RPC calls. Here is an
example:

public class InvokerComponent


{
private HelloInterface hello;

public String invoke(String s)


{
return "Received: " + hello.sayHello(s, "English");
}
public void setHello(HelloInterface hello)
{
this.hello = hello;
}
public HelloInterface getHello()
{
return hello;
}
}

In this example, the component InvokerComponent has a field hello, which is of type HelloInterface,
with getter and setter methods for the field. The invoke method will be called on the service and calls the
hello.sayHello() method. This call will result in another service call.

The HelloInterface is very simple with a single method sayHello.

public interface HelloInterface


{
public String sayHello(String to, String language);
}

Now, you simply configure your component to bind the sayHello method to the endpoint that will invoke
another service.

Document generated by Confluence on Oct 27, 2008 21:07 Page 568


<service name="InvokerComponent">
<inbound>
<jms:inbound-endpoint queue="Invoker.in"/>
</inbound>

<component class="org.mule.examples.bindings.InvokerComponent">
<binding interface="org.mule.examples.bindings.HelloInterface" method="sayHello">
<axis:outbound-endpoint use="LITERAL" style="WRAPPED"
address="http://myhost.com:81/services/HelloWeb?method=helloMethod" synchronous="true"/>
</binding>
</component>

<outbound>
<pass-through-router>
<jms:outbound-endpoint queue="Invoker.out"/>
</pass-through-router>
</outbound>
</service>

Note that the call to the external web service is synchronous, because you want a result returned and
need to block until the call is finished.

Handling Data Types

One powerful feature is that you can handle data conversion when making a call and receiving a result
using the normal transformer configuration on the endpoint. In the above example, assume the web
service was expecting an org.mule.examples.bindings.WebHelloRequest object and returned an
org.mule.examples.bindings.WebHelloResponse object. You don't want your component to know about
these external data types, so you can configure transformers to do the conversion when the call is made:

<component class="org.mule.examples.bindings.InvokerComponent">
<binding interface="org.mule.examples.bindings.HelloInterface" method="sayHello">
<axis:outbound-endpoint use="LITERAL" style="WRAPPED"
address="http://myhost.com:81/services/HelloWeb?method=helloMethod" synchronous="true">
<transformers>
<custom-transformer class="org.mule.examples.bindings.StringsToWebRequest"/>
</transformers>
<response-transformers>
<custom-transformer class="org.mule.examples.bindings.WebResponseToString"/>
</response-transformers>
</axis:outbound-endpoint>
</binding>
</component>

Exceptions

If the remote service call triggers an exception of fault, this exception will get serialized back to the local
service call and thrown. If your service wants to handle this exception, you must add the exception (or
java.lang.Exception) to the bound method signature and use a try catch block as usual.

Script Component Bindings


Similar to the Java component bindings, script bindings enable the same behavior for you scripting
components. When using a scripting component, the binding is bound to the scripting context and is
accessible by using the binding interface class name.

<service name="ScriptService">
<inbound>
<vm:inbound-endpoint ref="inboundEndpoint"/>
</inbound>
<script:component>
<script:script engine="groovy">
return "Total: " + AdditionService.add(1,2)
</script:script>

Document generated by Confluence on Oct 27, 2008 21:07 Page 569


<script:java-interface-binding interface="org.mule.tck.services.AdditionService" method="add">
<vm:outbound-endpoint path="addition.service" synchronous="true"/>
</script:java-interface-binding>
</script:component>
<outbound>
<pass-through-router>
<vm:outbound-endpoint ref="receivedEndpoint"/>
</pass-through-router>
</outbound>
</service>

The implementation for the component is contained within the <script:script> element:

return "Total: " + AdditionService.add(1,2)

We refer to the binding interface using the short class name AdditionService and invoke the add
method, which will call a local addition service.

Document generated by Confluence on Oct 27, 2008 21:07 Page 570


Using the WireTap Inbound Router

This page last changed on Oct 15, 2008 by jackie.wheeler.

Using the WireTap Inbound Router


The WireTap inbound router allows you to route certain messages to a different endpoint as well as to the
component.

To copy all messages to a specific component, you configure an outbound endpoint on the WireTap
router:

<inbound>
<vm:inbound endpoint path="FromUser"/>
<wire-tap-router>
<vm:outbound-endpoint path="tapped.channel"/>
</wire-tap-router>
</inbound>

In the following scenario, no component is specified, so all data from the inbound VM channel is copied
to the outbound endpoint using implicit bridging. However, let's assume you want to forward some of
the data to another component called WireTapReceiver based on a filter. For the sake of illustration, this
component simply prepends the message with "INTERCEPTED:" before sending it to the FromTapper VM
channel. The code for the WireTapReceiver component is as follows:

public class WireTapReceiver {

public String handleInterceptedData (String aMessage) {


//Just Prepend the message with a label
return "\nINTERCEPTED: "+aMessage;
}
}

Following is the configuration of the Mule services:

<model name="default">
<service name="StdComp">
<inbound>
<vm:inbound-endpoint path="In"/>
<wire-tap-router>
<vm:outbound-endpoint path="ToTapper"/>
</wire-tap-router>
</inbound>
<outbound>
<outbound-pass-through-router>
<vm:outbound-endpoint path="ToClient"/>
</outbound-pass-through-router>
</outbound>
</service>
<service name="wiretapper">
<inbound>
<vm:inbound-endpoint path="ToTapper"/>
</inbound>
<component class="org.myclass.WireTapReceiver"/>
<outbound>

Document generated by Confluence on Oct 27, 2008 21:07 Page 571


<outbound-pass-through-router>
<vm:outbound-endpoint path="FromTapper"/>
</outbound-pass-through-router>
</outbound>
</service>
</model>

Note: Mule uses a separate dispatcher thread for the wiretap endpoint.

Using Filters
The WireTap router is useful both with and without filtering. If filtered, it can be used to record or take
note of particular events or to copy events that require additional processing to a different component. If
filters aren't used, you can make a backup copy of all events received by a component. The behavior here
is similar to that of an interceptor, but interceptors can alter the message flow by preventing the message
from reaching the component. WireTap routers cannot alter message flow but just copy on demand.

In the previous example, the StdComp service receives events from the In endpoint, and the router
passes the event to the component and copies it to the vm://ToTapper endpoint. The WireTapper
component listens on this channel and forwards the message, after processing, to the FromTapper
endpoint.

The WireTap router is based on the SelectiveConsumer router, so it can take any filters supported by
SelectiveConsumer. In this example, only messages that match the filter expression are copied to the
vm://ToTapper endpoint.

<wire-tap-router>
<wildcard-filter pattern="the quick brown*"/>
<vm:outbound-endpoint path="tapped.channel"/>
</wire-tap-router>

Multiple WireTapping
You can have multiple WireTap routers for the same service:

<inbound>
<endpoint address="vm://In"/>
<wire-tap-router>
<wildcard-filter pattern="the quick brown*"/>
<vm:outbound-endpoint path="ToTapper"/>
</wire-tap-router>
<wire-tap-router>
<wildcard-filter pattern="the slow green*"/>
<vm:outbound-endpoint path="ToOtherTapper"/>
</wire-tap-router>
</inbound>

In this example, input is passed to the component and also copied to one of two destinations depending
on the filter.

Method Invocation
You can invoke your service with a specific method. For example, if your inbound endpoint is not vm://
In but axis\:http://localhost\:8080/services, or if your component StdComp is a customized
component with a method foo(), you can invoke the web service and its method foo() via the following
endpoint:

http\://localhost\:8080/services/StdComp?method=foo&param=bar

When this event is wire-tapped to the receiving component, Mule might fail with an exception if the
receiving component does not have the method foo(). To avoid this problem and to ensure that the
desired method is invoked, you overwrite the method of the message by specifying ?method=methodName
?method= so that the onCall() will be called instead. For example:

Document generated by Confluence on Oct 27, 2008 21:07 Page 572


<wire-tap-router>
<outbound-endpoint addres="vm://inboundEndpoint3?connector=vm2"/>
</wire-tap-router>
...
<service name="serviceComponent3">
<inbound>
<inbound-endpoint address="vm://inboundEndpoint3?connector=vm2&amp;method=" synchronous="false"/>
</inbound>
<component class="org.mule.components.simple.LogComponent"/>
</service>

Additional Features
The WireTap router supports the following additional features:

• Transactions are supported, so the forwarding of events can either start or join a transaction
provided that the endpoint supports transactions.
• Reply-To can be used to route replies from this endpoint.

Document generated by Confluence on Oct 27, 2008 21:07 Page 573


XML Configuration

This page last changed on Oct 14, 2008 by jackie.wheeler.

XML Configuration
[ XML Schema ] [ Namespaces ] [ Spring ] [ Property Placeholders ] [ Global Configuration Settings ]

As explained in the overview, the most common way to configure Mule is via Spring XML files that use
custom Mule namespaces.

XML Schema
The configuration files are based on XML schemas, which are specified in the header:

<?xml version="1.0" encoding="UTF-8"?>


<mule xmlns="http://www.mulesource.org/schema/mule/core/2.0"
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xmlns:jms="http://www.mulesource.org/schema/mule/jms/2.0"
xmlns:file="http://www.mulesource.org/schema/mule/file/2.0"
xsi:schemaLocation="
http://www.mulesource.org/schema/mule/core/2.0 http://www.mulesource.org/schema/mule/core/2.0/
mule.xsd
http://www.mulesource.org/schema/mule/jms/2.0 http://www.mulesource.org/schema/mule/jms/2.0/mule-
jms.xsd
http://www.mulesource.org/schema/mule/file/2.0 http://www.mulesource.org/schema/mule/file/2.0/mule-
file.xsd">

Be sure to specify all the necessary schema files. This can be time-consuming when setting up the
configuration file, but importing schemas provides the following time-saving benefits:

• Auto-completion and context-specific help in your favorite IDE


• Design-time configuration validation
• Typed properties

Namespaces
Each Mule module or transport has its own XML schema. When you import a schema, it has its own
namespace. For example, the following lines from the above header:

xmlns:jms="http://www.mulesource.org/schema/mule/jms/2.0"
xsi:schemaLocation="http://www.mulesource.org/schema/mule/jms/2.0 http://www.mulesource.org/schema/
mule/jms/2.0/mule-jms.xsd"

will bind the mule-jms.xsd schema to the jms namespace. Therefore, any XML element starting with
<jms: will assume the element comes from the mule-jms.xsd schema.

Default Namespace

Typically, you set the Mule core schema as the default namespace for your configuration file. This means
that any XML element without a prefix will come from the Mule core schema (mule.xsd). To set the
default namespace schema, specify xmlns immediately followed by the URL of the Mule schema, without
the colon and namespace prefix you set in the previous example (e.g., xmlns instead of xmlns:jms):

<mule xmlns="http://www.mulesource.org/schema/mule/core/2.0"
xsi:schemaLocation="http://www.mulesource.org/schema/mule/core/2.0 http://www.mulesource.org/
schema/mule/core/2.0/mule.xsd">
...config...
</mule>

Document generated by Confluence on Oct 27, 2008 21:07 Page 574


Spring
Although your configuration files appear to be Mule-specific, they are really just Spring configuration files
with Mule-specific extensions
This approach allows you to use anything Spring offers within your Mule configuration, such as beans,
factory beans, resource loaders, EJBs, JNDI, AOP, even integration with other software such as Hivemind,
jBPM, Gigaspaces, JBoss Rules, etc.

To use the standard Spring elements, you import the standard Spring namespaces:

xmlns:spring="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/
schema/beans/spring-beans-2.0.xsd"
...
<spring:bean id="myBean" class="com.acme.CoolBean">
<spring:property name="sessionFactory">
<spring:ref local="mySessionFactory" />
</spring:property>
<spring:property name="configuration">
<spring:value>my-config.xml</spring:value>
</spring:property>
</spring:bean>

For complete information on Spring configuration, see the Spring Framework reference documentation.

Property Placeholders
You can use Ant-style property placeholders in your Mule configuration. For example:

<smtp:outbound-endpoint user="${smtp.username}" password="${smtp.password}"/>

The values for these placeholders can be made available in a variety of ways, as described in this section.

Global Properties

You can use the <global-property> element to set a placeholder value from within your Mule
configuration, such as from within another Mule configuration file:

<global-property name="smtp.username" value="JSmith"/>


<global-property name="smtp.password" value="ChangeMe"/>

Properties File

To load properties from a file, you can use the standard Spring element
<context:property-placeholder>:

xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd"

<context:property-placeholder location="smtp.properties" placeholderPrefix="#{"/>

where the contents of smtp.properties is:

smtp.username=JSmith
smtp.password=ChangeMe

The placeholderPrefix value can be anything other than "${", which is what Mule uses to parse its own
properties. We recommend you set the value to "#{". Note that you do not have to change anything in
your Spring configuration or properties file to match this value; it simply differentiates Spring properties
from Mule properties. If you do not set the placeholderPrefix attribute, it creates a conflict with Mule,
and you will see a "Could not resolve placeholder" error.

To load multiple properties files, separate them with commas:

Document generated by Confluence on Oct 27, 2008 21:07 Page 575


<context:property-placeholder location="email.properties,http.properties,system.properties"
placeholderPrefix="#{"/>

System Properties

The placeholder value can come from a JDK system property. If you start Mule from the command line,
you would specify the properties as follows:

mule -M-Dsmtp.username=JSmith -M-Dsmtp.password=ChangeMe -config my-config.xml

or edit the system properties in conf/wrapper.conf.

If you start Mule programmatically, you would specify the properties as follows:

System.getProperties().put("smtp.username", "JSmith");
System.getProperties().put("smtp.password", "ChangeMe");
MuleContext muleContext = new DefaultMuleContextFactory().createMuleContext(new
SpringXmlConfigurationBuilder("my-config.xml"));
muleContext.start();

Environment Variables

There is no standard way in Java to access environment variables. However, this link has some options
you might find useful.

Global Configuration Settings


You can configure global configuration settings such as the default transaction timeout and default
threading profile in the <configuration> element. For example:

<mule>
...
<configuration defaultTransactionTimeout="31337">
<default-component-threading-profile poolExhaustedAction="RUN"/>
...
</configuration>

For a list of the available global configuration settings, see Global Settings Configuration Reference.

Document generated by Confluence on Oct 27, 2008 21:07 Page 576


Escape URI Credentials

This page last changed on Oct 09, 2008 by jackie.wheeler.

Escape Your Credentials

When including the user name and password in the endpoint, escape any characters
that are illegal for URIs, such as the @ character. For example, if the user name is
user@myco.com, you should enter it as user%40myco.com.

Document generated by Confluence on Oct 27, 2008 21:07 Page 577


PGP Security

This page last changed on Sep 12, 2008 by jackie.wheeler.

PGP Security
This page is under construction

This extension adds PGP security on endpoint communication.


With PGP you can achieve end-to-end security communication with signed and encrypted messages
between parties.

Requirements
You need to add these libraries to Mule classpath:

• Cryptix OpenPGP
• Cryptix JCE

Install Policy files

If you are running JDK 1.4+ that comes with the


Sun JCE by default, or JDK 1.2/1.3 if you have installed Sun JCE 1.2
manually, you have to install the Unlimited Strength Jurisdiction Policy files,
which can be downloaded from the following URL (note that they are listed
entirely at the bottom of the page, in the Other Dowloads section):

http://java.sun.com/j2se/1.4/download.html
http://java.sun.com/j2se/1.5.0/download.jsp

These files have to be installed in $JAVA_HOME$/jre/lib/security

The default distribution of the JCE allows as Sun calls it 'strong, but limited strength
cryptography'. This basically means that you cannot use RSA keys bigger than 2048 bits,
and no symmetric ciphers that use more than 128 bits. ElGamal is not allowed at all, thus
DH/DSS cannot be used for encryption.

Useful PGP links

How PGP works (intro documentation)


GnuPG (freeware implementation)
enigmail (extension for Thunderbird)

Configuring PGP filter


Using a spring context, we have to define a manager for accessing public and private keys.

securityContext.xml

<beans>
<bean id="pgpKeyManager" class="org.mule.extras.pgp.PGPKeyRingImpl"
init-method="initialise">
<property name="publicKeyRingFileName">
<value>pubring.gpg</value>
</property>
<property name="secretKeyRingFileName">
<value>secring.gpg</value>
</property>
<property name="secretAliasId">
<value>0x6168F39C</value>
</property>

Document generated by Confluence on Oct 27, 2008 21:07 Page 578


<property name="secretPassphrase">
<value>TestingPassphrase</value>
</property>
</bean>

<bean id="fakeCredentialAccessor"
class="org.mule.extras.pgp.FakeCredentialAccessor" />

</beans>

Also we need to know who is the sender of a message.


For this example we simply fake the sender using the org.mule.extras.pgp.FakeCredentialAccessor
class (from pgp test src, which returns a fixed user name)

PGP stores keys in files called keyrings


There is a public keyring storing public keys of your trusted parties and a private keyring
storing your secret key.
In a keyring, keys are referenced by an alias ID (also named key Id).
Your secret keyring is encrypted on your disk using a passphrase.

Our goal is to define a sample echo application that reads signed (and encrypted) files from a directory (/
temp/signedAndEncryptedFiles/in)
and write the decrypted content into /temp/decryptedFiles/out

Then comes Mule configuration...

<mule-configuration id="Test_Mule_Properties" version="1.0">

<!-- Spring context -->


<container-context
className="org.mule.extras.spring.SpringContainerContext">
<properties>
<property name="configFile" value="securityContext.xml"/>
</properties>
</container-context>

<!-- Security manager -->


<security-manager>
<security-provider name="PgpProvider"
className="org.mule.extras.pgp.PGPSecurityProvider">
<properties>
<container-property name="keyManager" reference="pgpKeyManager"/>
</properties>
</security-provider>

<encryption-strategy name="KBE"
className="org.mule.extras.pgp.KeyBasedEncryptionStrategy">
<properties>
<container-property name="keyManager" reference="pgpKeyManager" />
</properties>
</encryption-strategy>
</security-manager>

<model name="echoTest">
<mule-descriptor name="echo" containerManaged="false"
implementation="org.mule.extras.pgp.EchoMsg">

<inbound-router>

<endpoint address="file:///temp/signedAndEncryptedFiles/in">
<security-filter
className="org.mule.extras.pgp.filters.PGPSecurityFilter">
<properties>
<property name="strategyName" value="KBE"/>
<property name="signRequired" value="true"/>
<container-property name="credentialsAccessor"

Document generated by Confluence on Oct 27, 2008 21:07 Page 579


reference="fakeCredentialAccessor"/>
<container-property name="keyManager"
reference="pgpKeyManager" />
</properties>
</security-filter>
</endpoint>

</inbound-router>

<outbound-router>
<router
className="org.mule.routing.outbound.OutboundPassThroughRouter">

<endpoint address="file:///temp/decryptedFiles/out" >


<security-filter
className="org.mule.extras.pgp.filters.PGPSecurityFilter">
<properties>
<property name="strategyName" value="KBE"/>
<property name="authenticate" value="false"/>
<container-property name="credentialsAccessor"
reference="fakeCredentialAccessor"/>
<container-property name="keyManager"
reference="pgpKeyManager" />
</properties>
</security-filter>
</endpoint>

</router>
</outbound-router>
</mule-descriptor>
</model>
</mule-configuration>

The property signRequired in the inbound security filter controls if we accept unsigned message or not.

the property authenticate in the outbound security filter controls if we want to encrypt messages for the
receiver

..and they said "free email account"...but I read "free persistent message queue"...
– Alessandro Riva

Document generated by Confluence on Oct 27, 2008 21:07 Page 580


Jaas Security

This page last changed on Sep 12, 2008 by jackie.wheeler.

This page is under construction

The JaasSimpleAuthenticationProvider is a security provider which provides a way to interact with the
Jaas Authentication Service.

Configuration:

The security provider for Jaas can be configured in a couple of different ways. First of all, it allows you
to configure jaas either by passing to the provider a jaas configuration file, which will be discussed
below, or by passing the required attributes directly to the JaasSimpleAuthenticationProvider. These two
configuration methods are described below.

Option 1: Using the Jaas Configuration File

The Jaas Configuration File

Usually, JAAS authentication is performed in a pluggable fashion, so applications can remain independent
from underlying authentication technologies.

com.ss.jaasTest{

com.ss.jaas.loginmodule.DefaultLoginModule required

credentials="anon:anon;Marie:Marie;"

};

The above example was saved in a file called jaas.conf. This file contains just one entry called
com.ss.jaasTest, which is where the application we want to protect can be found. The entry specifies the
LoginModule that will be used to authenticate the the user. As a login module, you can either use Mule's
DefaultLoginModule, one of the LoginModules that come with Sun, or else create your own. In this case,
we have opted for Mule's DefaultLoginModule.

The "required" flag that follows the LoginModule specifies that the LoginModule must succeed in order for
the authentication to be considered successful. There are other flags apart from this. These are:

Required - The LoginModule is required to succeed. If it succeeds or fails, authentication still continues
to proceed down the LoginModule list.

Requisite - The LoginModule is required to succeed. If it succeeds, authentication continues down the
LoginModule list. If it fails, control immediately returns to the application.

Sufficient - The LoginModule is not required to succeed. If it does succeed, control immediately returns
to the application (authentication does not proceed down the LoginModule list). If it fails, authentication
continues down the LoginModule list.

Optional - The LoginModule is not required to succeed. If it succeeds or fails, authentication still
continues to proceed down the LoginModule list.

The entry also specifies the credentials, in which we put a string of authorised users together with their
passwords. The credentials are put here only when the DefaultLoginModule is going to be used as the
method in which the user names and passwords are obtained may vary from one LoginModule to another.

The Format of the credentials string must adhere to the following format if the DefaultLoginModule is
going to be used:

<username>:<password>;

The Mule XML configuration

<security-provider name="JaasProvider"
className="com.ss.jaas.provider.JaasSimpleAuthenticationProvider">
<properties>

Document generated by Confluence on Oct 27, 2008 21:07 Page 581


<property name="loginContextName" value="com.ss.jaasTest"/>
<property name="loginConfig" value="jaas.conf"/>
</properties>
</security-provider>

Note that in the above, the loginContextName contains the same name of the entry in the jaas
configuration file discussed above. This will be used for creating the login context as well as to find the
complete URL of the jaas.conf file.

Option 2: Using passing the credentials directly to the Provider

The second option for the configuration of the JaasSimpleAuthenticationProvider is to pass the
configuration details which would otherwise be found in the jaas configuration file directly to the provider.

<security-provider name="JaasProvider"
className="com.ss.jaas.provider.JaasSimpleAuthenticationProvider">
<properties>
<property name="loginContextName" value="com.ss.jaasTest"/>
<property name="credentials" value="anon:anon;Marie.Rizzo:dragon;" />
</properties>
</security-provider>

In the above configuration, you can note that we removed the property "loginConfig" and we don't need
to pass any jaas configuration file. All we need to do is to pass the credentials to the provider (using the
same format specified above). Since no LoginModule is specified, the DefaultLoginModule will be used.

However, the JaasSimpleAuthenticationProvider also permits you to enter, using this configuration, your
own LoginModule.

Option 3: Passing a non- default Login Module

<security-provider
name="JaasProvider"className="com.ss.jaas.provider.JaasSimpleAuthenticationProvider">
<properties>
<property name="loginContextName" value="com.ss.jaasTest"/>
<property name="loginModule" value="com.sun.security.auth.module.NTLoginModule"/>
</properties>
</security-provider>

In the above configuration, we have added a further property for the loginModule where you can add the
LoginModule you wish to use to authenticate the user. Since the NTLoginModule does not require you to
input a list of accepted usernames and passwords, the property for the "credentials" was removed.

Configuring the security filter on an Endpoint:

As a security-filter, the MuleEncryptionEndpointSecurityFilter can be used.

<mule-descriptor name="SendStringUMO" implementation="com.ss.jaasTest.SendString">


<inbound-router>
<endpoint address="vm://localhost/test">
<security-filter className="org.mule.impl.security.filters.MuleEncryptionEndpointSecurityFilter">
<properties>
<property name="strategyName" value="PBE"/>
</properties>
</security-filter>
</endpoint>
</inbound-router>
</mule-descriptor>

Document generated by Confluence on Oct 27, 2008 21:07 Page 582


Setting up LDAP Provider for Acegi

This page last changed on Jan 30, 2008 by ross.

In the Mule Security page, we discuss about how you can configure an in-memory DAO provider. In this
documentation, we will talk about how you can configure an Acegi's LDAP provider, which can be:

• Used by Mule, as its security provider via AcegiProviderAdapter


• Used by Acegi/Spring to perform Component Authorization
• etc.

Declaring the Beans

Basically, you will need to setup two beans in Spring, an InitialDirContextFactory and an
LdapAuthenticationProvider. The InitialDirContextFactory is the access point for obtaining an
LDAP context where the LdapAuthenticationProvider provides integration with the LDAP server. As an
example:

<bean id="initialDirContextFactory" class="org.acegisecurity.ldap.DefaultInitialDirContextFactory">


<constructor-arg value="ldap://localhost:389/dc=com,dc=foobar" />
<property name="managerDn">
<value>cn=root,dc=com,dc=foobar</value>
</property>
<property name="managerPassword">
<value>secret</value>
</property>
</bean>

<bean id="authenticationProvider"
class="org.acegisecurity.providers.ldap.LdapAuthenticationProvider">
<constructor-arg>
<bean class="org.acegisecurity.providers.ldap.authenticator.BindAuthenticator">
<constructor-arg>
<ref local="initialDirContextFactory" />
</constructor-arg>
<property name="userDnPatterns">
<list>
<value>uid={0},ou=people</value>
</list>
</property>
</bean>
</constructor-arg>
<constructor-arg>
<bean class="org.acegisecurity.providers.ldap.populator.DefaultLdapAuthoritiesPopulator">
<constructor-arg>
<ref local="initialDirContextFactory" />
</constructor-arg>
<constructor-arg>
<value>ou=groups</value>
</constructor-arg>
<property name="groupRoleAttribute">
<value>cn</value>
</property>
<property name="searchSubtree">
<value>true</value>
</property>
<property name="rolePrefix">
<value>ROLE_</value>
</property>
<property name="convertToUpperCase">
<value>true</value>
</property>
</bean>
</constructor-arg>
</bean>

Document generated by Confluence on Oct 27, 2008 21:07 Page 583


Configuring Mule Security Provider

The AcegiProviderAdapter delegates to an AuthenticationProvider such as the


LdapAuthenticationProvider.

<security-manager>
<security-provider name="acegi-ldap" className="org.mule.extras.acegi.AcegiProviderAdapter">
<properties>
<container-property name="delegate" reference="authenticationProvider" />
</properties>
</security-provider>
</security-manager>

With the above configuration, you can achieve endpoint-level security and other security features in Mule
which require one or more security providers.

Configuring MethodSecurityInterceptor

The configuration for component authorization is similar with the one that we have discussed in this page.
The one worth mentioning is the configuration of ObjectDefinitionSource, e.g.

<property name="objectDefinitionSource">
<value>org.mule.components.simple.EchoService.*=ROLE_MANAGERS</value>
</property>

The roles are looked up by the DefaultLdapAuthoritiesPopulator which you configured in previous
section. By default, a role is prefixed with ROLE_ and its value is extracted (and turned uppercase) from
the LDAP attribute defined by the groupRoleAttribute.

Document generated by Confluence on Oct 27, 2008 21:07 Page 584


Component Authorization Using Acegi

This page last changed on Jan 30, 2008 by ross.

This section describes how you can configure method level authorization on your components so that
users with different roles can only invoke certain service methods.

Securing Services Components


To secure MethodInvocations, developers need to add a properly configured MethodSecurityInterceptor
into the application context. The beans requiring security are chained into the interceptor. This chaining
is accomplished using Spring's ProxyFactoryBean or BeanNameAutoProxyCreator. Alternatively,
Acegi Security provides a MethodDefinitionSourceAdvisor which may be used with Spring's
DefaultAdvisorAutoProxyCreator to automatically chain the security interceptor in front of any beans
defined against the MethodSecurityInterceptor.

Apart from the daoAuthenticationProvider and inMemoryDaoImpl beans configured above, the following
beans must be configured:

• MethodSecurityInterceptor
• AuthenticationManager
• AccessDecisionManager
• AutoProxyCreator
• RoleVoter

The MethodSecurityInterceptor

The MethodSecurityInterceptor is configured with a reference to an:

• AuthenticationManager
• AccessDecisionManager

The following is a Security Interceptor for intercepting calls made to the methods of a component called
myComponent. myComponent has an interface (myComponentIfc) that defines two methods: delete and
writeSomething. Roles are set on these methods as seen below in the property objectDefinitionSource.

<bean id="myComponentSecurity"
class='org.acegisecurity.intercept.method.aopalliance.MethodSecurityInterceptor'>
<property name="authenticationManager">
<ref bean="authenticationManager"/>
</property>
<property name="accessDecisionManager">
<ref bean="accessDecisionManager"/>
</property>
<property name="objectDefinitionSource">
<value>
com.foo.myComponentIfc.delete=ROLE_ADMIN
com.foo.myComponentIfc.writeSomething=ROLE_ANONYMOUS
</value>
</property>
</bean>

The AuthenticationManager

An AuthenticationManager is responsible for passing requests through a chain of AuthenticationProviders.

<bean id="authenticationManager" class='org.acegisecurity.providers.ProviderManager'>


<property name= "providers">
<list>
<ref local="daoAuthenticationProvider"/>
</list>
</property>
</bean>

Document generated by Confluence on Oct 27, 2008 21:07 Page 585


The AccessDecisionManager

This bean specifies that a user can access the protected methods if they have any one of the roles
specified in the objectDefinitionSource.

<bean id="accessDecisionManager" class='org.acegisecurity.vote.AffirmativeBased'>


<property name="decisionVoters">
<list>
<ref bean="roleVoter"/>
</list>
</property>
</bean>

The AutoProxyCreator

This bean defines a proxy for the protected bean. When an application asks Spring for a myComponent
bean it will get this proxy instead.

<bean id="autoProxyCreator"
class='org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator'>
<property name='interceptorNames'>
<list>
<value>myComponentSecurity</value>
</list>
</property>
<property name='beanNames'>
<list>
<value>myComponent</value>
</list>
</property>
<property name='proxyTargetClass' value="true"/>
</bean>

When using BeanNameAutoProxyCreator to create the required proxy for security, the configuration
must contain the property proxyTargetClass set to true. Otherwise, the method passed to
MethodSecurityInterceptor.invoke is the proxy's caller, not the proxy's target.

The RoleVoter

The RoleVoter class will vote if any ConfigAttribute begins with ROLE_. The RoleVoter is case sensitive on
comparisons as well as the ROLE_ prefix.

• It will vote to grant access if there is a GrantedAuthority which returns a String representation (via
the getAuthority() method) exactly equal to one or more ConfigAttributes starting with ROLE_.
• If there is no exact match of any ConfigAttribute starting with ROLE_, the RoleVoter will vote to
deny access.
• If no ConfigAttribute begins with ROLE_, the voter will abstain.

<bean id="roleVoter" class="org.acegisecurity.vote.RoleVoter"/>

Setting Security Properties on the Security Provider


We can put any additional properties we may wish to add to the Security Provider in the
securityProperties map. For instance this map can be used to change Acegi's default security strategy into
one of the following...

MODE_THREADLOCAL which allows the authentication to be set on the current thread (this is the defualt
strategy used by Acegi).
MODE_INHERITABLETHREADLOCAL which allows authentication to be inherited from the parent thread
MODE_GLOBAL which allows the authentication to be set on all threads

Document generated by Confluence on Oct 27, 2008 21:07 Page 586


Securing Components in Asynchronous Systems

The use of Acegi's security strategies is particularly useful when using an asynchronous system since we
have to add a property on the Security Provider in order for the authentication to be set on more than
one thread.

In this case we would use the MODE_GLOBAL as seen in the example below.

<security-provider name="memory-dao" className="org.mule.extras.acegi.AcegiProviderAdapter">


<properties>
<container-property name="delegate" reference="daoAuthenticationProvider"/>
<map name="securityProperties">
<property name="securityMode" value="MODE_GLOBAL"/>
</map>
</properties>
</security-provider>

Document generated by Confluence on Oct 27, 2008 21:07 Page 587


Architecture Guide

This page last changed on Apr 15, 2008 by tcarlson.

Many of Mule's features are documented here using the same terms as the popular Enterprise Integration
Patterns book. The book describes the problems Mule aims to solve and documents many of the patterns
used in the Mule framework. EIP documentation in this guide and other Mule guides will be in the form of
-

EIP - (pattern name) (book pattern no.) (the pattern url on the EIP site)

(pattern image) (short description)

"Quote from the website/book"

Introduction
This document aims to give an insight to the architecture of Mule. Mule's ultimate goal is to provide
a unified method of interacting with data from disparate sources without encumbering the developer
with the details about how the data is sent or received or the protocols involved. The result is an ESB
(Enterprise Service Bus) server that is highly-scalable, light-weight, fast and simple to pick up and
start using. Mule was architected with the ESB model in mind and its primary focus is to simply and
speed up the process of developing distributed service networks. However, as the name suggests, the
ESB model is usually associated with large integration projects where there are an array of disparate
enterprise applications. Mule makes Enterprise level service architectures possible for smaller projects
where resources, development cost and TTM need to be kept to a minimum.

Architecture Overview
The primary goal is to enable integration between applications using standards, open protocols and well-
defined patterns. To achieve this goal, Mule defines a set of components that can be used to perform
most of the hard work necessary to get disparate applications and services talking together.
Cannot resolve external resource into attachment.
This diagram shows a simple end-to-end topology of how Mule components fit together.

Application

The Application can be of any type, such as a web application, back office system, application server or
another Mule instance.

Channel

Can be any method of communicating data between two points. Channels are used in Mule to wire UMO
components together as well as to wire different Mule nodes together across a local network or the
internet.

EIP - Message Channel (60) http://www.eaipatterns.com/MessageChannel.html

Cannot resolve external resource into attachment. Mule doesn't implement or mandate any particular
channels though Mule does provide many channel options known as Transport providers.

"When an application has information to communicate, it doesn't just fling the information into the
messaging system, it adds the information to a particular Message Channel. An application receiving
information doesn't just pick it up at random from the messaging system; it retrieves the information
from a particular Message Channel."

Document generated by Confluence on Oct 27, 2008 21:07 Page 588


Message Receiver

A Message Receiver is used to read or receive data from the Application. In Mule a Receiver is just one
element of a Transport provider and Mule provides many transports such as JMS, SOAP, HTTP, TCP, XMPP,
SMTP, file, etc.

Much of the 'magic' in Mule is it's ability to communicate to disparate systems without your business
logic (UMO components) ever needing to know about system location, format of the data, the delivery
mechanism or protocols involved. Likewise when the UMO component has done its work, it need not
worry about where the data is going next or in what format the data is expected.

EIP - Message Endpoint (95) http://www.eaipatterns.com/TransactionalClient.html

Cannot resolve external resource into attachment. Mule manages all delivery of data to and from
endpoints transparently.

"Message Endpoint code is custom to both the application and the messaging system's client API. The
rest of the application knows little about message formats, messaging channels, or any of the other
details of communicating with other applications via messaging. It just knows that it has a request or
piece of data to send to another application, or is expecting those from another application. It is the
messaging endpoint code that takes that command or data, makes it into a message, and sends it on
a particular messaging channel. It is the endpoint that receives a message, extracts the contents, and
gives them to the application in a meaningful way."

Inbound Router

Inbound routers are used to control how and which events are received by a component subscribing on
a channel. Inbound routers can be used to filter, split aggregate and re-sequence events before they are
received by the UMO component.

There is more information on Message Routers further on in this guide.

Connector

The connector understands how to send and receive data over a particular channel. A Message receiver is
coupled with a connector to register interest in data coming from a source understood by the connector.
There is more information on connectors further on in this guide.

Transformers

Transformers are used to transform message or event payloads to and from different types. Mule does
not define a standard message format (though Mule may support standard business process definition
message types in future) Transformation provided out of the box is Type transformation, such as JMS
Message to Object and standard XML transformers. Data transformation is very subjective to the
application and Mule provides a simple yet powerful transformation framework.
There is more information on transformers further on in this guide.

Endpoint

An endpoint is really a configuration wrapper that binds a connector, endpoint URI, transformers, filters
and transactional information to provide a Channel Adapter. The provider also stores transactional
information for the provider instance. See the MULEUSER:Mule Endpointschapter that goes into more
detail about endpoints.

EIP - Channel Adapter (127) http://www.eaipatterns.com/ChannelAdapter.html

Cannot resolve external resource into attachment. A provider is equivalent to a Channel Adapter.

Document generated by Confluence on Oct 27, 2008 21:07 Page 589


"The adapter acts as a messaging client to the messaging system and invokes application functions
via an application-supplied interface. Likewise, the Channel Adapter can listen to Application-internal
events and invoke the messaging system in response to these events."

Outbound Router
Outbound routers are used to publish messages/events to different providers depending on different
aspects of events or other rules defined in configuration.

There is more information on MEssage Routers further on in this guide.

Mule Manager
Core to Mule is the MuleManager. It manages the configuration of all core services for the Model and the
components it manages. Below is an overview of the core components that comprise a Mule manager.
Cannot resolve external resource into attachment.
The following sections go in to more detail for each of these elements in Mule.

The Model
The model encapsulates and manages the runtime behavior of a Mule Server instance. It is responsible
for maintaining the UMO's instances and their configuration. The Model has 3 control mechanisms to
determine how Mule interacts with it's UMO components -

Entry Point Resolver


Defined by the org.mule.umo.model.UMOEntryPointResolver interface, an entry point resolver is
used to determine what method to invoke on an UMO component when an event is received for its
consumption. There is a DynamicEntryPointResolver that is used if no other is configured on the model
(see the Configuration Guide for more information). The DynamicEntryPointResolver provides entry point
resolution for common usage, the steps it takes are -

1. Checks to see if the component implements the Callable life cycle interface, in which case, the
onCall(UMOEventContext) method will be used to receive the event.
2. If the component has a transformer configured for it, the return type for the transformer will
be matched against methods on the component to see if there is a method that accepts the
transformer return type. If so this event will be used. Note if there is more than one match, an
exception will be thrown.
3. If there is a method on the component that accepts an org.mule.umo.UMOEventContext . If so this
event will be used. Note if there is more than one match, an exception will be thrown.
4. The last check determines if there are any methods on the component that accept a java.util.Event .
If so this event will be used. Note if there is more than one match, an exception will be thrown.
5. If none of the above find a match an exception will be thrown and the component registration will
fail.

Of course there are many scenarios where the DynamicEntryPointResolver is suitable. For
example, if you are migrating from another framework you may want to restrict (such
as org.mule.model.CallableEntryPointResolver that only accepts components that extend
org.mule.umo.lifecycle.Callable ) or change the way the entry point is resolved. To implement a custom
Entry Point Resolver the org.mule.model.EntryPointResolver must be implemented.

Lifecycle Adapter
Defined by the org.mule.umo.lifecycle.UMOLifecycleAdapter interface, the lifecycle adapter is responsible
for mapping the mule component lifecycle to the underlying component. The DefaultLifecycleAdapter
simply delegates life cycle events to the component where the component implements zero or more UMO
lifecycle interfaces.

Document generated by Confluence on Oct 27, 2008 21:07 Page 590


Clearly this isn't suitable for existing components that you want to be managed by Mule, as they will most
likely have their own lifecycle methods that will still need to be invoked in the Mule framework. Luckily,
the org.mule.umo.lifecycle.LifecycleAdapter is very simple to implement.

Lifecycle adapters are configured using an implementation of


org.mule.umo.lifecycle.UMOLifecycleAdapterFactory. The factory is declared in the configuration of the
model. A default is provided DefaultLifecycleAdapterFactory.

Component Pool Factory


The Component Pool factory property of the model defines the factory to use when creating a component
pool for a given UMO Component. The pool is used to pool UMOComponents and this extension
point allows developers to use their own pooling mechanism if needed. Mule ships with two Pooling
implementations -

• commons-pool - this uses Jakarta commons-pool to manage the pooling of UMOComponents.


• pico-pool - this is a Pico extras component that manages object pooling using picoContainer.

Developers wishing to roll their own pooling implementation need to implement


org.mule.umo.model.UMOPoolFactory, org.mule.until.ObjectPool and org.mule.util.ObjectFactory.

Transport Providers
A transport provider is a Mule plug-in that enables Mule components to send and receive information over
a particular protocol, repository messaging or other technology. The following describes the architecture
of a transport provider. Cannot resolve external resource into attachment.

Connectors
The connector provides the implementation for connecting to the external system. The connector is
responsible for sending data to the external receiver and managing the listener on the connector to
receive data from the external system. For example, the Http connector creates a Http Connection and
sends the payload over the connection and will return a UMOEvent with the return status (if running
synchronously). Receivers for the Http connector are simply objects that get notified when something is
received on the Http server port.

A connector has two objects responsible sending and receiving events -

• MessageReceiver - Used to listen on an endpoint to the underlying technology. The receiver is


usually quite dumb with all configuration performed in the connector and the receiver is just a
listening thread.
• MessageDispatcher - Is used to dispatch events to the underlying technology. Message Dispatchers
are poolable threads that can be used to dispatch events or perform a 'receive' on the underlying
technology to retrieve an available event if there is one. The UMOMessageDespatcher interface
defines 3 important methods -
° dispatch() - sends data to the external system asynchronously.
° send() - sends data to the external system synchronously and returns any response from the

external system as a UMOEvent.


° recieve() - will request an event from the underlying technology and returns the result. This

method has a timeout parameter.

Connectors are responsible for managing sessions for the underlying technology, i.e. the JmsConnector
provides a JMS Session for the Connectors' Message Receiver and one also for the Message Dispatcher to
publish or send events over Jms.

Endpoints Address
An endpoint address defines any form of destination or source of data and is always expressed as URI.
Examples of endpoints could be -

Document generated by Confluence on Oct 27, 2008 21:07 Page 591


transport Description Example

POP3/SMTP usually username password and pop3://


a hostname user:password@mail.mycompany.com

JMS A name of a topic or queue jms://topic:myTopic

HTTP A host and possibly a port, path http://mycompany.com/mule


and query string

File The path of a directory or file file:///tmp/data/in

VM The name of another UMO vm://MyUMO


component runnig in the same
VM

SOAP The location of UMO component axis:http://mycompany.com/


exposed as a service or a mule/services/MyUMO
service location to invoke

Endpoint addresses are always expressed as valid URIs with the protocol of the connector then resource
specific information.

Mule Transport providers have pluggable endpoint builders that allow developers to customize the way an
endpoint is read by Mule.

Endpoint Resolution

This section describes the process Mule uses to resolve an endpointUri. For this example we will use the
following URI 'jms://topic:myTopic?durable=true'. This a JMS URI to a durable topic.

1. The ConnectorFactory is invoked with the URI.


2. It will look in META-INF/services/org/mule/providers for a service descriptor that matches 'jms'.
3. From this a ConnectorServiceDescriptor object is created.
4. You can specify on the Endpoint URI whether to create a new Connector for the URI or use an
existing connection. When there is no instruction an existing connection will be looked up based on
protocol.
5. The ConnectorServiceDescriptor contains the Endpoint builder to use and the Endpoint is passed into
the endpoint builder.
6. It is then up to the endpoint builder to decompose the URI into its component parts according to the
URI specification.

Message Receivers
Message receivers or message listeners are responsible for receiving data from the external system.
It is the responsibility of the connector to manage the registering and unregistering of receivers. The
complexity of the message receiver will vary depending on the external system being used. For example,
the message receiver for the JMS provider simply implements the javax.jms.MessageListener and the JMS
connector registers the listener with its JMS connection. However, the Http message receiver implements
an Http server that listens on a specified port for incoming requests.

Message Adapters
Message adapters are required to read disparate data objects in the format they are received from
the external application in a common way. The UMOMessageAdapter interface specifies a small set of
methods needed to read the payload and properties of any Java object. Message Adapters are specific to
a connector; when a connector is written a Message Adapter is also needed to read or translate data from
a particular data type used by the connector into either a byte array or string.

Document generated by Confluence on Oct 27, 2008 21:07 Page 592


Transactions
Transactions are managed at the Provider; Transactions are begun or committed when a Message
Receiver receives a message or a Message Dispatcher sends the message. Central to Mule's transaction
Management is the TransactionCoordinator, which is responsible maintaining transaction state. For more
information about transactions in Mule see the Transaction Management chapter of the User Guide.

In order for Mule to treat all transactions the same way there is a small API that transacted enabled
providers must define -

• org.mule.umo.UMOTransaction - A wrapper around the underlying transaction. Some systems do


not explicitly define a transaction object, instead, transaction demarcation may be achieved by
calling methods on a connection or session. The UMOTransaction API defines a set of methods that
can be used to interrogate any transactional resource.
• org.mule.umo.UMOTransactionFactory - A factory used to create an implementation of
UMOTransaction.

Container Contexts
The component resolver is the gateway to using an external container framework to manage the
instantiation and configuration of UMO components or their dependent objects. Mule doesn't provide
it's own component container as there is a wealth of very good IoC containers that are tried and tested.
Instead Mule provides some default Component Resolvers for popular containers -

• Spring Component Resolver - see the Spring Framework. For more information about Mule / Spring
integration see the MULEUSER:Spring chapter of the user guide.
• Pico Component Resolver - see the PicoContainer.

To use a component from an external container as your UMO component simply configure the desired
ComponentResolver on the model and when defining the mule-descriptor in the configuration file , set the
implementation attribute to the component key (or class in the case of picocontainer) in the container.

If the configuration does not specify a Component Resolver the MuleComponentResolver is used.
This implementation expects a class name to instantiate instead of a component key to resolve the
component with. It behaves in the same way as real implementations except it does not support looking
up components from a container.

To implement a custom ComponentResolver two interfaces need to be implemented -

• org.mule.umo.model.UMOComponentResolver - This does the actual resolving of components from


the container.
• org.mule.umo.model.UMOContainerContext - This is responsible for creating and initializing the
container. The Component Resolver will query the external framework through this context.

UMO Components
Central to the architecture of Mule are single autonomous components that can interact without being
bounded by the source, transport or delivery of data. These components are called UMO Components
and can be arranged to work with one another in various ways. These components can be configured
to accept data a number of different sources and can send data back to these sources. Cannot resolve
external resource into attachment.
The 'UMO Impl' specified above actually refers to an Object. This object can be anything, a JavaBean
or component from another framework. This is your client code that actually does something with the
events received. Mule does not place any restrictions on your object except that if configured by the Mule
directly, it must have a default constructor (if configured via Spring or Pico, Mule imposes no conventions
on the objects it manages).
Obviously, with this sort of flexibility, Mule needs to know a bit more about your object. It is the job of the
outer two layers shown to control how events are utilized by your Object.

Document generated by Confluence on Oct 27, 2008 21:07 Page 593


Component Lifecycle
The lifecycle adapter is used by the Model to fire lifecycle methods on your object (if any). Custom
lifecycles can be introduced on a per-model basis allowing different models to management the lifecycle
of their components in different ways.

Mule defines a default lifecycle for the components it manages. The components can participate in none,
any or all of these lifecycle events by implementing the required lifecycle interfaces. The lifecycle is as
follows - Cannot resolve external resource into attachment.
Components managed by Mule do not need to follow the Mule defined lifecycle. Using the
DefaultLifecycleAdapter a component can implement any of the lifecycle interfaces -

• org.mule.umo.lifecycle.Initialisable - Will add an initialise() method to the component.


• org.mule.umo.lifecycle.Startable - Will add a start() method to the component where your
component can execute any code to put itself in a state ready to receive events.
• org.mule.umo.lifecycle.Callable - Will add an onCall(UMOEventContext eventContext) method to the
component. This method will be called when an event is received for the component.
• org.mule.umo.lifecycle.Stoppable - Will add stop() method to the component where your component
can put itself in a stoped state. Note that the component should be in such a state that it can be
started again.
• org.mule.umo.lifecycle.Disposable - Will add a dispose() method to the component where it can do
any final tidying up before it is disposed.

These lifecycle interfaces also apply to Connectors, Agenets and Interceptors. For example the
LifecycleInterceptor implements the Startable, Stoppable and Disposable interfaces to manage it's
lifecycle.

Transformers
Transformers are used to convert source data to an object type required by the UMO Component.
Transformers can be configured on Endpoints that receive data to ensure that the expected object
type is always received by an UMO Component. Transformers configured on an Outbound endpoint
ensure that the endpoint receives the the correct object type before dispatching the event. Multiple
transformers can be chained together to allow for finer grained transformer implementations that
are easier to reuse. To configure an Endpoint to use more than one transformer, just specify a space
separated list of transformers in the config file or programmatically chain the transformers together using
the setTransformer() method on the transformer.
For example an inbound transformer may look like -

Cannot resolve external resource into attachment.


And an outbound transformer might look like -
Cannot resolve external resource into attachment.
All Mule transformers must implement org.mule.transformer.UMOTransformer. There is an abstract
transformer implementation that defines methods for controlling the object types this transformer
supports and validates the expected return type, leaving the developer to implement a single
doTransform() method.

Entrypoint Resolvers
Also (not shown on this digram) is the EntryPointResolver. This is used by the Model when the
UMOComponent is registered to find the method to call on your object when an event is received for it.
If a method is not found an exception will be thrown. The details of the EntryPoint resolver can be seen
here.

Events
Mule is an event-based architecture, that is, actions within a Mule network are triggered by either events
occurring in Mule or in external systems. Events always contain some sort of data, the payload, which
will be used and/or manipulated by one or more components and a set of properties that are associated
to the processing of the event. These properties are arbitrary and can be set at any time from when the

Document generated by Confluence on Oct 27, 2008 21:07 Page 594


event is created. The data in the event can be accessed in its original state or in its transformed state.
The event will use the transformer associated with the Endpoint that received the event to transform its
payload into a format that the receiving component understands. For more information about the event
lifecycle see the Message Flow section below.

Event Processing
Mule can send and receive events using 3 processing models -

1. Asynchronously - Many events can be processed by the same component at a time in different
threads. When the Mule server is running asynchronously instances of a component run in different
threads all accepting incoming events, though the event will only be processed by one instance of
the component.
2. Synchronously - When a UMO Component receives an event in this mode the the whole request is
executed in a single thread
3. Request-Response - This allows for a UMO Component to make a specific request for an event and
wait for a specified time to get a response back.

You can control the synchronicity of event processing by setting the synchronous property on the
endpoint (or programmatically on the event). Synchronicity of the call can be propagated across the
network where the transports being used support a reply channel. For example, a synchronous JMS
request will establish a temporary reply queue when a request is made and will wait for a response on
that queue. The same applies to socket based transports.
The actual event flow is governed by the synchronous property, whether the endpoint is inbound or
outbound and if there is a transaction in progress. The following rules apply.

Asynchronous Event Processing

Asynchronous event processing occurs when the inbound endpoint synchronous flag is set to false.

Asynchronous inbound and outbound

Cannot resolve external resource into attachment.

In this scenario the message is dispatched to a queue and is consumed by a worker thread in a pool that
actually does the execution work of your UMOComponent. The outbound endpoint is also asynchronous
the resulting message will be dispatched by a dispatcher thread.

Asynchronous inbound, synchronous outbound

Cannot resolve external resource into attachment.

In this scenario the message is dispatched to a queue and is consumed by a worker thread in a pool
that actually does the execution work of you UMOComponent. The outbound endpoint is synchronous
so the dispatch happens in the same thread as component execution. This scenario is used by outbound
transactions so that all dispatches from the component occur in the same thread. This behavior is
handled automatically by Mule.

Synchronous Processing

Synchronous inbound only

Cannot resolve external resource into attachment.

An event is received and processed by your UMOComponent in the same thread and any result is
returned from your UMO component will be passed back to the receiver where if there is a response
channel, i.e Socket outputstream a result will be sent.

Synchronous inbound and outbound

Cannot resolve external resource into attachment.

Document generated by Confluence on Oct 27, 2008 21:07 Page 595


An event is received and processed in the same thread. The outbound dispatch also happens in the
receiver thread. Here if the outbound endpoint transport being used supports a reply channel such
as sockets or JMS a response from the dispatch will be intercepted (or the wait will timeout) and that
response is passed back to the receiver where if there is a response channel, i.e Socket outputstream a
result will be sent.

Synchronous inbound and outbound with transaction

Cannot resolve external resource into attachment.

Transactions can only (currently) be managed over synchronous endpoints. Thus if an endpoint has been
configured for transactions it will automatically be synchronous. When dispatching and a transaction is in
progress the dispatch will also happen in the current thread.

Message Routers
Message routers are used to control how events are sent and received by components in the system.
Mule defines Inbound routers that apply to events as they are received and outbound routers that are
invoked when an event is being dispatched.

EIP - Message Router (78) http://www.eaipatterns.com/MessageAdapter.html

Cannot resolve external resource into attachment. Mule provides extensible routers to control how
messages are dispatched.

"a Message Router ... consumes a Message from one Message Channel and republishes it to a different
Message Channel channel depending on a set of conditions."

Inbound Routers
Inbound routers can be used to control and manipulate events received by a component. Typically, an
inbound router can be used to filter incoming event, aggregate a set of incoming events or re-sequence
events when they are received. You can chain inbound routers together, in this scenario each router is
matched before the event is dispatched to a Mule component. Inbound routers are different to outbound
routers in that the provider is already known so the purpose of the router is to control how messages are
sent via the provider. You can specify a catch-all strategy which will be invoked if any of the routers do
not accept the current event. An Inbound Router can be configured on a mule-descriptor element in the
mule-config.xml -

<inbound-router>
<catch-all-strategy
className="org.mule.tck.testmodels.mule.TestCatchAllStrategy"/>
<router className="org.mule.routing.inbound.SelectiveConsumer">
<filter expectedType="java.lang.String"
className="org.mule.routing.filters.PayloadTypeFilter"/>
</router>
<router className="org.mule.routing.inbound.Aggregator">
</router>
</inbound-router>

If there are no special processing requirements for messages received by a component there is no need
to configure an inbound router.

Outbound Routers
Outbound routers are used to control which providers are used to send events once an UMO component
has finished processing. Message Routers are configured on UMOCompnent and allow the developer to
define multiple routing constraints for any given Event. You can specify a catch-all strategy which will be

Document generated by Confluence on Oct 27, 2008 21:07 Page 596


invoked if none of the routes accept the current event. An example of an Outbound Message Router is
given below -

<outbound-router>
<catch-all-strategy className="org.mulerouting.ForwardingCatchAllStrategy"
provider="catchAll"/>
<router providers="TestApple-Out"
className="org.mule.routing.outbound.FilteringOutboundRouter">
<filter expectedType="java.lang.String"
className="org.mule.routing.filters.PayloadTypeFilter"/>
</router>
<router providers="waterMelonProvider"
className="org.mule.routing.outbound.FilteringOutboundRouter">
<filter className="org.mule.routing.filters.logic.AndFilter">
<left-filter pattern="the quick brown (.*)"
className="org.mule.routing.filters.RegExFilter"/>
<right-filter pattern="(.*) brown (.*)"
className="org.mule.routing.filters.RegExFilter"/>
</filter>
</router>
</outbound-router>

Catch All Strategy

The catch all strategy receives the event if none of the router accept the event. Custom strategies must
implement org.mule.umo.routing.UMORoutingCatchAllStrategy which defines a method -

public void catchMessage(UMOMessage message, UMOSession session,


boolean synchronous) throws RoutingException;

Note that this a void method, so that no return event can be passed back to the calling code. This is
important when running synchronously as the synchronous chain of events is broken. It is considered an
error condition when a catch-all strategy is invoked.

Routers

In the example, there are 2 routers defined, with the outbound-router element as the parent. This means
that each router will be checked in order to see if the current event can be routed.

It is not recommended to use transacted providers in router configurations. As routing of the event is
determined at run-time, there are situations where an event within a transaction is routed to a non-
transacted provider, thus orphaning the current transaction causing 'surprise' transaction timeouts. For
transacted providers it is recommended that you configure one inbound and one outbound transacted
provider for the event path.

In situations where only one outbound provider is configured for an UMO component it is not necessary to
define a Message router.

For more information about using the routers that ship with Mule, see the MULEUSER:Message Routers
chapter of the MULEUSER:Home.

Interceptors
Mule interceptors are useful for attaching common behavior to multiple UMOs. The Interceptor or
Command pattern is often referred to as practical AOP (Aspect Oriented Programming) as it allows
the developer to intercept processing on an object and potentially alter the processing and outcome.
Interceptors a very useful for attaching profiling, permission and security checks, etc, to a component in
Mule.

Mule has two types of interceptors -

1. org.mule.interceptors.EnvelopeInterceptor - Envelope filter that will execute before and after the
event is processed. Good for Logging and profiling.

Document generated by Confluence on Oct 27, 2008 21:07 Page 597


2. org.mule.umo.UMOInterceptor - Simply gets invoked then forwards processing to the next element.
An interceptor can stop further processing by not forwarding control to the next interceptor, for
example as permissions checker interceptor.

The following shows a typical interceptor stack and the event flow. Cannot resolve external resource into
attachment.

Exception Management
Exception strategies can be defined on UMOComponents, but sometimes it's sufficient to have all
components managed by the the model tp use the same exception strategy. By defining the exception
strategy on the model, it is not necessary to define individual exception strategies (by default if no
exception strategy is defined on a UMO Component the org.mule.impl.DefaultExceptionStrategy will be
used).

It is common to define your own exception strategy, to do so you must implement


org.mule.umo.UMOExceptionStrategy.

Document generated by Confluence on Oct 27, 2008 21:07 Page 598


Explanation of MULE_SERVICE_METHOD

This page last changed on Apr 15, 2008 by tcarlson.

MULE_SERVICE_METHOD
Mule's entry point resolver class (based upon org.mule.umo.model.UMOEntryPointResolver) works
its way through its priority scheme to be able to figure out what entry point to use. This allows Mule
to dynamically use a different entry point depending on the payload of the inbound message. Other
entry point resolver classes can also be used if the DynamicEntryPointResolver is not sufficient for
your needs. The only drawback to the default mechanism is the fact that if two methods have the
same type of parameters, Mule obviously cannot decide which of the methods to use and raises a
TooManySatisfiableMethods exception. In such cases, you can easily implement the Callable interface in
your component and direct the message to the correct method.

However, this is not always a feasible solution; perhaps you do not have access to the source code of
your service component or perhaps you do not want to make your component "Mule-aware". The work
around to this would be to have a wrapper component that can direct the message for you but this just
adds another level of abstraction that you may not want either. Besides, this is all routing logic so why
should we put this into a service component?

Let us illustrate this with a simple example - If we have two components called "A" and "B" that
communicate synchronously using the VM channel called "vm://Communication". Let us assume that "A"
is the producer of string messages and "B" consumes these messages. However, "B" has more than one
method that accepts strings.

What we need is a routing mechanism that allows us to select which method to use. We need to be able
to specify a number of methods within our configuration that can be used directly and therefore bypass
the entry point resolver logic. What we really need is the ability to specify a different endpoint for each
of the methods; i.e, to be able to route along a particular channel but control which part of the consumer
will actually be invoked. Mule has such a property for the endpoints - the MULE_SERVICE_METHOD
property that needs to be configured on both the inbound and outbound endpoints. Component "A" would
have the following outbound router configured:

<outbound-router>
<router className="org.mule.routing.outbound.OutboundPassThroughRouter">
<endpoint address="vm://Communication?method=Method1"/>
</router>
</outbound-router>

Here, the endpoint is defined as it usually is but has a "method" property which we have set to
"Method1". We therefore want the result of this service component to be sent along the VM channel
called "Communication" and passed along to the method called "Method1" Component "B" would have the
following inbound router configured:

Document generated by Confluence on Oct 27, 2008 21:07 Page 599


<mule-descriptor name="ComponentB" implementation="org.foo.ComponentB">
<inbound-router>
<endpoint address="vm://Communication"/>
</inbound-router>
<properties>
<property name="MULE_SERVICE_METHOD" value="Method1"/>
<property name="MULE_SERVICE_METHOD" value="Method2"/>
<property name="MULE_SERVICE_METHOD" value="Method3"/>
<property name="MULE_SERVICE_METHOD" value="Method4"/>
</properties>
</mule-descriptor>

Note that the configuration of the inbound router and the inbound endpoint is the same as it usually
is. The difference is the addition of the properties on the Mule descriptor. We can therefore route a
message along a channel for a specific method as long as the methods are defined as properties on the
mule-descriptor. This allows us to bypass the entry point resolver logic and control which method to
invoke in case of multiple methods having the same parameters.

Pitfalls
Here, the Mule configuration is tightly coupled with the implementation of your component. If
the component changes and the methods are renamed, you will need to adjust your configuration
accordingly.

Restrictions
This will only work on synchronous paradigms. This will currently not work if your processing is
asynchronous due to an issue with threading.

Filtering
Of course, we still need to figure out what criteria to look out for before routing using this mechanism. If
"B" has any number of methods, we still need to figure out which method is the correct one for each
message. If we take a simple content based example, the criteria would be contained within the payload
itself. In such a situation, the Mule configuration would look like this:

<mule-descriptor name="CompA" implementation="org.foo.ComponentA">


<inbound-router>
<endpoint address="vm://inFromSource"/>
</inbound-router>
<outbound-router>
<router className="org.mule.routing.outbound.FilteringOutboundRouter">
<endpoint address="vm://Communication?method=Method1"/>
<filter patter="pattern1" className="org.mule.routing.filters.WildcardFilter"/>

Document generated by Confluence on Oct 27, 2008 21:07 Page 600


</router>
<router className="org.mule.routing.outbound.FilteringOutboundRouter">
<endpoint address="vm://Communication?method=Method2"/>
<filter patter="pattern2" className="org.mule.routing.filters.WildcardFilter"/>
</router>
<router className="org.mule.routing.outbound.FilteringOutboundRouter">
<endpoint address="vm://Communication?method=Method3"/>
<filter patter="pattern3" className="org.mule.routing.filters.WildcardFilter"/>
</router>
<router className="org.mule.routing.outbound.FilteringOutboundRouter">
<endpoint address="vm://Communication?method=Method4"/>
<filter patter="pattern4" className="org.mule.routing.filters.WildcardFilter"/>
</router>
</outbound-router>
</mule-descriptor>

<mule-descriptor name="ComponentB" implementation="org.foo.ComponentB">


<inbound-router>
<endpoint address="vm://Communication"/>
</inbound-router>
<properties>
<property name="MULE_SERVICE_METHOD" value="Method1"/>
<property name="MULE_SERVICE_METHOD" value="Method2"/>
<property name="MULE_SERVICE_METHOD" value="Method3"/>
<property name="MULE_SERVICE_METHOD" value="Method4"/>
</properties>
</mule-descriptor>

Document generated by Confluence on Oct 27, 2008 21:07 Page 601

Anda mungkin juga menyukai