Mule 2.1.2 Users Guide
Mule 2.1.2 Users Guide
Mule 2.1.2 Users Guide
Key: MULE2USER
Name: Mule 2.x User Guide
Description: Mule Users Guide for the 2.x release line
Available Pages
• ActiveMQ Integration
• Example Archetype
• Home
• About Transports
• Available Transports
• BPM Transport
• CXF Transport
• Building a CXF Web Service
• CXF Transport Configuration Reference
• Enabling WS-Addressing
• Enabling WS-Security
• Supported Web Service Standards
• 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
• HTTPS Transport
• HTTP Transport
• IMAPS Transport
• IMAP Transport
• JDBC Transport
• JDBC Transport Examples
• JDBC Transport Performance Benchmark Results
• Jetty Transport
• Jetty SSL transport
• JMS Transport
• Mule WMQ Transport
• Multicast Transport
• POP3S Transport
• POP3 Transport
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.
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.
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:
<persistence>
<vmPersistence/>
</persistence>
</broker>
</beans>
Example 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 example archetype will help you generate a tailored boilerplate example project in seconds. For
more information on using Maven, see Using Maven.
Follow the instructions below to create template files for a new Mule example, including all the necessary
Java boilerplate and detailed implementation instructions in comments.
Configuring Maven
Add the following to the file settings.xml (usually in your Maven conf or $HOME/.m2 directory) so that
Maven will allow you to execute Mule plug-ins.
<settings>
<pluginGroups>
<pluginGroup>org.mule.tools</pluginGroup>
</pluginGroups>
...
</settings>
> cd yourDir
Next, you will execute the archetype and generate the code. If this is your first time running this
command, Maven will download the archetype for you.
• artifactId: The short name for the project (such as 'myExample'). This must be a single word in
lower case with no spaces, periods, hyphens, etc.
• 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.
artifactId
As of Mule 2.2 the artifactId can contain characters such as underscore or hyphen.
However, the plug-in will convert the name into a usable form suitable for Java. For
example, if the argument is specified as -DartifactId=My#Awesome-Mule_Project,
the project will be created in a directory of that name, but the project name will be
MyAwesomeMuleProject and the package name will be .myawesomemuleproject
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.
You should provide an accurate description of the example with any high-level details of what you can or
cannot do with it. This text will be used where a description of the example is required.
The version of Mule you want to use for your example. This will default to the archetype version passed in
on the command line.
If the example will be hosted on MuleForge, additional information will be added to your example for
linking to its issue tracker, web site, build server, and deployment information.
A comma-separated list of the transports you plan to use in this example (such as HTTP and VM). This
will add the namespaces for those transports to the configuration file.
A comma-separated list of the modules you plan to use in this example (such as XML and Scripting). This
will add the namespaces for those modules to the configuration file.
[default:]
********************************************************************************
[INFO] muleVersion:
********************************************************************************
[default: 2.1.2]
********************************************************************************
[INFO] forgeProject:
********************************************************************************
[INFO] transports:
********************************************************************************
[default: cxf,file,http,jdbc,jms,stdio,vm]
********************************************************************************
[INFO] modules:
********************************************************************************
(options: bulders,client,jaas,jbossts,management,ognl,pgp,scripting,
spring-extras,sxc,xml):
[default: client,management,scripting,sxc,xml]
********************************************************************************
-Dinteractive=false
groupId - org.mule.example.<artifactId>
DgroupId=org.mule.examplexxx
forgeProject -DforgeProject=n y
Mule 1.x
• Getting Started
• User Guide
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
Creating Transports
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.
The following list includes some prominent transports from MuleForge (denoted by ). Transports that
Mule Transports
Transport Description
IMAP In-Only
IMAPS In-Only
Jetty In-
Only In-
Out In-
Optional-
Out
POP3 In-Only
POP3S In-Only
Servlet In-
Only In-
Out In-
SMTP Out-Only
SMTPS Out-Only
VM In- Out-Only
Only In- Out-
Out In- In Out-
Optional- Optional-
Out In
Heading Descriptions
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).
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
bpm://ProcessType
bpm://ProcessType/ProcessID
bpm://MyBigProcess
bpm://MyBigProcess?processId=4561&action=advance
bpm://MyBigProcess/4561
bpm://MyBigProcess/4561?action=update
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.
These process variables may then be used to drive the logic of the running process.
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
bpm://MyBigProcess
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.
Therefore, until such a specification ever emerges, the Mule BPM Transport simply defines its own.
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.
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
</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:
<process-definition name="sendMessageProcess">
<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>
</process-definition>
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.
Configuration
Following is a simple configuration example:
<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/>
<outbound>
<filtering-router>
<outbound-endpoint address="bpm://MyProcess" synchronous="false" />
</filtering-router>
</outbound>
</service>
Message Properties
Attributes of <connector...>
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.
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.
Troubleshooting
This section includes common problems and solutions you might encounter when using the CXF transport.
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.
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.
@WebService(serviceName = "YourServiceName",
portName = "YourPortName",
targetNamespace = "http://your-namespace",
endpointInterface = "your.endpoint.Interface",
wsdlLocation = "your.wsdl")
Suggested Reading
This page describes how to build a CXF web service and use it in Mule.
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);
}
package demo.hw.server;
import javax.jws.WebService;
@WebService(endpointInterface = "demo.hw.server.HelloWorld",
serviceName = "HelloWorld")
public class HelloWorldImpl implements HelloWorld {
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:
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.
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
CXF is able to locate this WSDL inside your webapp, on the classpath, or on the file system.
1. AegisDatabinding
2. JAXBDatabinding (Default)
3. StaxDatabinding
<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>
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);
}
Table of Contents
• 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...>
initializeStaticBusInstance
boolean no Initialize the static
CXF Bus with a
Bus configured to
use Mule for all
transports. This
Inbound Endpoint
Attributes of <inbound-endpoint...>
applyTransformersToProtocol
boolean no Whether or not
to apply the
transformers
to the protocol
endpoint.
Outbound Endpoint
Attributes of <outbound-endpoint...>
Endpoint
Attributes of <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.
Features
Wrapper Component
The WebServiceWrapperComponent class allows you to send
the result of a web service call to another endpoint.
Attributes of <wrapper-component...>
Attributes of <stax...>
xmlInputFactory string no
xmlOutputFactory string no
Enabling WS-Addressing
To enable your services to use WS-Addressing, you must configure the CXF endpoint to use the WS-
Adressing feature:
<cxf:inbound-endpoint address="http://localhost:63081/services/employee">
<cxf:features>
<wsa:addressing />
</cxf:features>
</cxf:inbound-endpoint>
Note that currently "decoupled" reply to endpoints are not supported with Mule.
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.
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
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 javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import org.apache.ws.security.WSPasswordCallback;
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
<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>
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.
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;
Future versions of Mule may support WS-ReliableMessaging. Although CXF currently supports it, it is not
easy to support "decoupled" WS-RM over non-native CXF transports, so it does not work well with Mule
transports. One-way channels might work but are currently untested.
Future Releases
In version 2.2, the CXF transport is slated to support the following additional standards:
• WS-Trust
• WS-SecureConversation
• WS-SecurityPolicy
• WS-Security
Next, you configure the client as an outbound endpoint using the following properties:
<service name="csvPublisher">
<inbound>
<inbound-endpoint address="file://./books?pollingFrequency=100000&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>
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:
// Endpoint Address
String endpointAddress = http://localhost:63081/hello";
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
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;
}
}
http://localhost:65081/services/EchoUMO/echo/string/hello
This will send the value "hello" for the string parameter to the echo() method.
Using MTOM
[ Writing an MTOM-enabled WSDL ] [ Generating Server Stubs and/or a Client ] [ Configuring the CXF
Inbound Endpoint ] [ Configuring the CXF Outbound Endpoint ]
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.
Normally, when creating XML schema types for binary data, you would write a schema type like this:
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">
You can use this DataHandler method to access the attachment data by calling
"handler.getInputStream();".
When you configure the endpoint, set the mtomEnabled attribute to true to enable MTOM:
<service name="mtomService">
<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>
<cxf:outbound-endpoint
name="outboundEmployeeDirectoryEndpoint"
address="http://localhost:63081/services/employeeDirectory"
clientClass="org.mule.example.employee.EmployeeDirectory_Service"
operation="addEmployee"
wsdlPort="EmployeeDirectoryPort"
wsdlLocation="classpath:employeeDirectory.wsdl"
mtomEnabled="true"/>
See the Using a Web Service Client as an Outbound Endpoint page for more information.
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.
Connector
The Mule EJB Connector provides connectivity for EJB beans.
Attributes of <connector...>
For example:
• registry host
• registry port
• remote home name
• remote method name
These values will be used to establish the dispatcher connection. For example:
<outbound-endpoint address="ejb://localhost:1099/SomeService?method=remoteMethod"/>
If the method can take one or more input arguments, you configure their types as a comma-separated
list using the methodArgumentTypes attribute. Multiple arguments are passed in as an array of objects as
the payload of the Mule message.
Transformers
There are no specific transformers required for EJB.
Email Transport
The Email transport provides a standard email connector that is extended by each of the email protocols.
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 messages 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 transports support protocol features such as attachments, replyTo, CC and BCC addresses,
binary content types, and custom headers. Each email transport supports the following attributes for
connecting to the mail server:
Attribute Description
For information about configuring specific endpoints, see the following links:
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.MailSubjectRegExFilter
Applies a regular expression to a Mail Message
subject.
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
Name Description
File Transport
Table of Contents
• File Transport
• ° Connector
° - Attributes of <connector...>
- Child Elements of <connector...>
° Endpoint
° - Attributes of <endpoint...>
° Inbound Endpoint
° - Attributes of <inbound-endpoint...>
° Outbound Endpoint
° - Attributes of <outbound-endpoint...>
° File To Byte Array Transformer
° File To String Transformer
° Legacy Filename Parser
° Expression Filename Parser
° Custom Filename Parser
° - Attributes of <custom-filename-parser...>
° Abstract Filenameparser
° Expressing File Endpoints
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 the
output will be placed in a new file or if it should be 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...>
Endpoint
Attributes of <endpoint...>
Inbound Endpoint
Attributes of <inbound-endpoint...>
Outbound Endpoint
Attributes of <outbound-endpoint...>
#[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]
Attributes of <custom-filename-parser...>
Abstract Filenameparser
A placeholder for flename parser elements.
file://<path>[MULE:?params]
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).
file://./temp
or
file://temp
Note only two slashes are used for the protocol, so it's a relative path.
or
file://?address=./temp
FTP Transport
Table of Contents
• FTP Transport
• ° 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
The FTP transport provides connectivity to FTP servers to allow files to be read and written as messages
in Mule.
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...>
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
The following attributes are available on the FTP connector in Mule Enterprise only (as of version 1.6):
fileAge Does not process the file unless it's older than the
specified age in milliseconds.
Endpoint
Attributes of <endpoint...>
Inbound Endpoint
Attributes of <inbound-endpoint...>
Attributes of <outbound-endpoint...>
ftp://<username>:<password>@<hostname[MULE::port]>/[MULE:address]
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.
If you use a URI-style endpoint and you include the user name and password, 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.
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:
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).
ftp://joe:123456@ftp.mycompany.com/ftp/done?outputPattern=FtpFile-${DATE}.done
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
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
For example:
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.
HTTP Transport
Table of Contents
• 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
° Handling Redirects
° Getting a Hash Map of Properties
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...>
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...>
Outbound Endpoint
The HTTP outbound endpoint allows Mule to send requests to external servers or Mule inbound HTTP
endpoints using the HTTP protocol.
Attributes of <outbound-endpoint...>
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 Description
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...>
Attributes of <rest-service-component...>
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:
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:
To configure the HTTP Polling receiver, you include an HTTP polling-connector configuration in your Mule
configuration:
Sending HTTP
The following behavior applies when sending POST request bodies as a client and when returning a
response body:
Receiving HTTP
When receiving HTTP responses, the payload of the MuleMessage will always be the InputStream of the
HTTP response.
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">
<property key="Content-Type" value="image/png"/>
<property key="Accept" value="*.*"/>
</outbound-endpoint>
</outbound-pass-through-router>
</outbound>
Handling Redirects
To redirect an HTTP client, you must set two properties on the endpoint. First, set the http.status
property to '307', which instructs the client that the resource has be temporarily redirected. Alternatively,
you can set the property to '301' for a permanent redirect. Second, set the Location property, which
specifies the location where you want to redirect your client.
See the HTTP protocol specification for detailed information about status codes at http://
www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
<service name="redirecter">
<inbound>
<inbound-endpoint address="http://localhost:8080/mine" synchronous="true">
<property key="http.status" value="307"/>
<property key="Location" value="http://mule.mulesource.org/"/>
</inbound-endpoint>
<inbound>
Note that you must set the synchronous attribute to true. Otherwise, the service will be asynchronous,
and a response will be immediately returned while the request is placed on an internal queue.
For example:
<http:inbound-endpoint ...>
<custom-transformer name="myTransformer"
class="org.mule.transport.http.transformers.HttpRequestBodyToParamMap" />
</http:inbound-endpoint>
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
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.
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.
IMAP Connector
The IMAP connector supports all the common connector attributes and properties and the following
additional attributes:
Endpoints
IMAP and IMAPS endpoints include details about connecting to an IMAP mailbox. You configure the
endpoints just as you would with any other transport, with the following additional attributes:
For example:
or for IMAPS:
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. You can also specify the endpoint settings using a URI,
but the above syntax is easier to read.
If you use a URI-style endpoint and you include the user name and password, 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.
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 (e.g., to create new tables dynamically).
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.
When using JDBC EE features, you will need to import the EE namespace for the JDBC transport, which
has .com instead of .org in the URL, and the XSD name is mule-jdbc-ee.xsd instead of mule-jdbc.xsd.
For example:
<mule
xmlns:jdbc="http://www.mulesource.com/schema/mule/jdbc/2.1"
xsi:schemaLocation="http://www.mulesource.com/schema/mule/jdbc/2.1 http://www.mulesource.com/
schema/mule/jdbc/2.1/mule-jdbc-ee.xsd">
As of Mule EE 2.2, the path will be slightly different (.org instead of .com, addition of /ee in path):
<mule
xmlns:jdbc="http://www.mulesource.org/schema/mule/ee/jdbc/2.2"
Document generated by Confluence on Jan 30, 2009 11:37 Page 85
xsi:schemaLocation="http://www.mulesource.org/schema/mule/ee/jdbc/2.2 http://www.mulesource.org/
schema/mule/ee/jdbc/2.2/mule-jdbc-ee.xsd">
If you are not using JDBC EE features, then you can use the normal CE namespace:
<mule
xmlns:jdbc="http://www.mulesource.org/schema/mule/jdbc/2.1"
xsi:schemaLocation="http://www.mulesource.org/schema/mule/jdbc/2.1 http://www.mulesource.org/
schema/mule/jdbc/2.0/mule-jdbc.xsd">
Inbound SELECT queries are queries that are executed periodically (according to the pollingInterval
set on the connector).
Here is an example:
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.
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
batch processing flow to make sure that it does not process the next batch until the previous batch has
finished processing.
Detailed usage of the large dataset retrieval feature is shown in JDBC Example #4.
Important Limitations
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).
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.
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>
...
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).
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
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)".
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.
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:
Also, the XML message payload (passed in or out as a String) must adhere to a particular schema format:
<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:
The following table summarizes the properties that can be set on this transformer:
Property Description
For an example, see Example #1, which uses the CSV Transformer to load data from a CSV file to a
database table.
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>
<pass-through-router>
<jdbc:outbound-endpoint queryKey="selectMules"/>
</pass-through-router>
</outbound>
</service>
</model>
In this scenario, if a Map is sent to the vm://mapReceiver endpoint containing this key/value pair:
key=ID
value=3
See Examples #2 and #3 for further outbound SELECT query examples. Note that this feature is
available in Mule Enterprise Edition only.
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:
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:
...
<pass-through-router>
<jdbc:outbound-endpoint queryKey="storedProc1"/>
</pass-through-router>
...
<pass-through-router>
<jdbc:outbound-endpoint address="jdbc://storedProc2?value=25"/>
</pass-through-router>
...
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:
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.
For Oracle databases only, an OUT parameter can return a cursor. The following example shows how this
works.
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: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>
<pass-through-router>
<jdbc:outbound-endpoint queryKey="SingleCursor"/>
</pass-through-router>
</outbound>
</service>
<service name="cursorOutputAsResultSet">
<inbound>
<vm:inbound-endpoint path="returns.resultset" responseTransformer-refs="MapLookup"/>
</inbound>
<outbound>
<pass-through-router>
<jdbc:outbound-endpoint queryKey="SingleCursor"/>
</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:
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.
You can use any JDBC data source library with the JDBC Connector. The "myDataSource" reference below
refers to a DataSource bean created in Spring:
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.
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 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:
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>
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.1"
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.1"
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.1 http://www.mulesource.org/schema/mule/core/2.1/
mule.xsd
http://www.mulesource.org/schema/mule/jdbc/2.1 http://www.mulesource.org/schema/mule/jdbc/2.1/
mule-jdbc.xsd">
Transactions
Transactions are supported on JDBC Endpoints. See Transaction Management for details.
Connector Properties
SQL queries are used by endpoints and should be configured on the connector using the "query" element:
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.
Setup
The Mule Enterprise JDBC Examples are located in your installation at $MULE_HOME/examples/jdbc.
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...
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.
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.
COUNT(1)
----------
If you want to run the example again, first delete the records from mule_source.
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.
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.
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.
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!
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.
Before running this example, you can optionally change the location of the ID store in jdbc-etl.xml:
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:
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.
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".
Configuration
JDK 1.5.0.11
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.
Jetty Transport
[ Connector ] [ Endpoints ] [ Using Web Services over Jetty ]
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.
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...>
For example:
Endpoints
Jetty endpoints are configured the same way as HTTP endpoints. Note that only inbound endpoints can
use the Jetty transport.
For example:
Using the Jetty transport simply requires that you use the "jetty://" URL scheme as opposed to the
regular HTTP scheme. For example:
<service name="greeterService">
<inbound>
<cxf:inbound-endpoint address="jetty://localhost:63081/services/greeter" synchronous="true" />
</inbound>
<component>
<singleton-object class="org.apache.hello_world_soap_http.GreeterImpl"/>
</component>
</service>
Due to limitations of the CXF and HTTP transports, if you are talking to outbound endpoints
that do not use a CXF client underneath and are of the form "cxf:http://locahost/service?
method=echo", this will not work. We hope to address this during a future refactoring of
the HTTP transport.
For example, the following configuration specifies the HTTPS and Jetty-SSL connectors:
If you do not need this level of security, you can use the Jetty Transport instead.
JMS Transport
Table of Contents
• JMS Transport
• ° JMS Configuration
° - 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
° Configuring Specific JMS Servers
° 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. It also provides links to information
on configuring various types of JMS, such as ActiveMQ. Note that 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 information on managing JMS local and distributed (XA) transactions, as well as multi-resource
transactions (for Mule Enterprise Edition users), see Transaction Management.
Additionally, the Error Handler Example and Loan Broker Example demonstrate using the Active MQ
connector and various JMS transformers.
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.
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
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:
or
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.
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.
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:
If you want to set the durable name yourself, you can set the durableName property on the endpoint.
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.
<jms:connector name="jmsConnector">
<property key="jmsSupport" ref="customJmsSupport"/>
</jms:connector>
For more information about configuring specific JMS servers, see Configuring Specific JMS Servers below.
Mule can be configured to look up connection factories, queues, and topics from JNDI. Use the following
connector attributes to configure your JNDI connection:
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"
JMS Transformers
Transformer Description
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:
You can access any custom header properties on the message in the same way.
• ActiveMQ
Schema Reference
Connector
A generic connector for sending and receiving messages over JMS queues.
Attributes of <connector...>
redeliveryHandlerFactory-
name (no spaces) no Reference to the
ref redelivery handler.
acknowledgementMode
AUTO_ACKNOWLEDGE/
no AUTO_ACKNOWLEDGE
The
CLIENT_ACKNOWLEDGE/ acknowledgement
DUPS_OK_ACKNOWLEDGE mode to use:
AUTO_ACKNOWLEDGE,
CLIENT_ACKNOWLEDGE,
or
DUPS_OK_ACKNOWLEDGE.
recoverJmsConnections
boolean no Deprecated. This
attribute is no
longer relevant
for the new retry
policies.
jndiProviderProperties-
string no Feference to a
ref Map that contains
additional provider
properties.
connectionFactoryJndiName
string no The name to use
when looking up
the connection
factory from JNDI.
Custom Connector
A custom connector for sending and receiving messages over JMS queues.
Attributes of <custom-connector...>
redeliveryHandlerFactory-
name (no spaces) no Reference to the
ref redelivery handler.
acknowledgementMode
AUTO_ACKNOWLEDGE/
no AUTO_ACKNOWLEDGE
The
CLIENT_ACKNOWLEDGE/ acknowledgement
DUPS_OK_ACKNOWLEDGE mode to use:
AUTO_ACKNOWLEDGE,
CLIENT_ACKNOWLEDGE,
or
DUPS_OK_ACKNOWLEDGE.
recoverJmsConnections
boolean no Deprecated. This
attribute is no
longer relevant
for the new retry
policies.
jndiProviderProperties-
string no Feference to a
ref Map that contains
additional provider
properties.
connectionFactoryJndiName
string no The name to use
when looking up
the connection
factory from JNDI.
Attributes of <activemq-connector...>
redeliveryHandlerFactory-
name (no spaces) no Reference to the
ref redelivery handler.
acknowledgementMode
AUTO_ACKNOWLEDGE/
no AUTO_ACKNOWLEDGE
The
CLIENT_ACKNOWLEDGE/ acknowledgement
DUPS_OK_ACKNOWLEDGE mode to use:
AUTO_ACKNOWLEDGE,
CLIENT_ACKNOWLEDGE,
or
DUPS_OK_ACKNOWLEDGE.
recoverJmsConnections
boolean no Deprecated. This
attribute is no
longer relevant
for the new retry
policies.
connectionFactoryJndiName
string no The name to use
when looking up
the connection
factory from JNDI.
Activemq Xa Connector
ActiveMQ version of the JMS connector with XA transaction support.
Attributes of <activemq-xa-connector...>
redeliveryHandlerFactory-
name (no spaces) no Reference to the
ref redelivery handler.
acknowledgementMode
AUTO_ACKNOWLEDGE/
no AUTO_ACKNOWLEDGE
The
CLIENT_ACKNOWLEDGE/ acknowledgement
DUPS_OK_ACKNOWLEDGE mode to use:
AUTO_ACKNOWLEDGE,
recoverJmsConnections
boolean no Deprecated. This
attribute is no
longer relevant
for the new retry
policies.
jndiProviderProperties-
string no Feference to a
ref Map that contains
additional provider
properties.
connectionFactoryJndiName
string no The name to use
when looking up
the connection
factory from JNDI.
Weblogic Connector
WebLogic version of the JMS connector.
Attributes of <weblogic-connector...>
redeliveryHandlerFactory-
name (no spaces) no Reference to the
ref redelivery handler.
acknowledgementMode
AUTO_ACKNOWLEDGE/
no AUTO_ACKNOWLEDGE
The
CLIENT_ACKNOWLEDGE/ acknowledgement
DUPS_OK_ACKNOWLEDGE mode to use:
AUTO_ACKNOWLEDGE,
CLIENT_ACKNOWLEDGE,
or
DUPS_OK_ACKNOWLEDGE.
recoverJmsConnections
boolean no Deprecated. This
attribute is no
longer relevant
for the new retry
policies.
jndiProviderProperties-
string no Feference to a
ref Map that contains
additional provider
properties.
connectionFactoryJndiName
string no The name to use
when looking up
the connection
factory from JNDI.
Websphere Connector
WebSphere version of the JMS connector.
Attributes of <websphere-connector...>
redeliveryHandlerFactory-
name (no spaces) no Reference to the
ref redelivery handler.
recoverJmsConnections
boolean no Deprecated. This
attribute is no
longer relevant
for the new retry
policies.
jndiProviderProperties-
string no Feference to a
ref Map that contains
additional provider
properties.
connectionFactoryJndiName
string no The name to use
when looking up
the connection
factory from JNDI.
Transaction
Transactions allow a series of operations to be grouped together so that they can be rolled back if a
failure occurs. Set the action (such as ALWAYS_BEGIN or JOIN_IF_POSSIBLE) and the timeout setting for
the transaction.
Inbound Endpoint
An endpoint on which JMS messages are received.
Attributes of <inbound-endpoint...>
Attributes of <outbound-endpoint...>
Endpoint
A global JMS endpoint definition.
Attributes of <endpoint...>
Property Filter
Allows you to filter messages based on a JMS property.
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.
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.
• 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="JMS_COMPLIANT"
...
• 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.
xsi:schemaLocation="
http://www.mulesource.com/schema/mule/mqseries/2.1 http://www.mulesource.com/schema/mule/
mqseries/2.1/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.1 http://www.mulesource.org/schema/mule/core/2.1/
mule.xsd
http://www.mulesource.org/schema/mule/stdio/2.1 http://www.mulesource.org/schema/mule/stdio/2.1/
mule-stdio.xsd
http://www.mulesource.org/schema/mule/vm/2.1 http://www.mulesource.org/schema/mule/vm/2.1/mule-
vm.xsd">
<mqs:connector name="mqSeriesConnector"
hostName="winter"
port="1414"
queueManager="HELLO.QMGR"
transportType="BINDINGS_MQ"
targetClient="NONJMS_MQ"
specification="1.1"
username=""
password=""
disableReplyToHandler="true"
connectionFactory-ref="connectionFactory">
</mqs:connector>
<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>
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.
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:
<mqs:connector name="mqSeriesConnector"
hostName="winter"
port="1414"
queueManager="HELLO.QMGR"
channel="HELLO.CHANNEL"
transportType="CLIENT_MQ_TCPIP"
targetClient="NONJMS_MQ"
specification="1.1"
username=""
password=""
disableReplyToHandler="true"
connectionFactory-ref="connectionFactory">
</mqs:connector>
<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.
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.
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.
<mqs:connector ...
connectionFactory-ref="connectionFactory"/>
<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:
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
Endpoints
You configure Multicast endpoints just as you would with any other transport, with the following additional
attributes:
Transformers
The following transformers are used by default for this connector unless a transformer is explicitly set on
the provider.
Transformer Description
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
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.
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.
POP3 Connector
The POP3 connector supports all the common connector attributes and properties and the following
additional attributes:
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:
For example:
or:
If you use a URI-style endpoint and you include the user name and password, 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.
Table of Contents
• 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.
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...>
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...>
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...>
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.
Example Configurations
Note that the documentation for this example should be embedded within the code.
<service name="testService1">
<description>
This configuration will create an inbound event for testService1 at 12 noon every day. The event payload
will always have the same value 'foo'.
</description>
<inbound>
<quartz:inbound-endpoint name="qEP1" cronExpression="0 0 12 * * ?" jobName="job1" connector-
ref="quartzConnector1">
<quartz:event-generator-job>
<quartz:payload>foo</quartz:payload>
</quartz:event-generator-job>
</quartz:inbound-endpoint>
</inbound>
</service>
Example Configurations
Note that the documentation for this example should be embedded within the code.
<service name="testService2">
<description>
This configuration will create an inbound event for testService2 every 1 second indefinitely. The event
payload
will always have the same value, which the contents of the file 'payload-data.txt'. The file can be on
the classpath of on the local file system.
</description>
<inbound>
<quartz:inbound-endpoint name="qEP2" repeatCount="10" repeatInterval="1000" jobName="job2"
connector-ref="quartzConnector1">
<quartz:event-generator-job >
<quartz:payload file="payload-data.txt"/>
</quartz:event-generator-job>
</quartz:inbound-endpoint>
</inbound>
Example Configurations
Note that the documentation for this example should be embedded within the code.
<service name="testService5">
<description>
The endpoint polling Job will try and perform a 'request' on any Mule endpoint. If a result is received
it will be handed off to this 'testService5' service for processing.
The trigger will fire every 5 minutes starting at 2pm and ending at 2:55pm, every day. during this
period the job will check the file directory /N/drop-data/in every 5 minutes to see if any event data is
available. The request will timeout after 4 seconds if there are no files in the directory.
</description>
<inbound>
</inbound>
</service>
Example Configurations
Note that the documentation for this example should be embedded within the code.
<service name="testService6">
<description>
This outbound Quartz endpoint will receive an event after the component has processed it and store it in
the event store. When the trigger kicks in at 10:15am everyday it will dispatch the event on the
endpoint referenced as 'scheduledDispatchEndpoint'. Since the 'repeatCount' is set to 0, the event will
only be sent out once.
</description>
<inbound>
<inbound-endpoint address="test://inbound6"/>
</inbound>
<test:component/>
<outbound>
<outbound-pass-through-router>
<quartz:outbound-endpoint name="qEP6" repeatCount="0" cronExpression="0 15 10 * * ? *"
jobName="job6" connector-ref="quartzConnector1">
<quartz:scheduled-dispatch-job>
<quartz:job-endpoint ref="scheduledDispatchEndpoint"/>
</quartz:scheduled-dispatch-job>
</quartz:outbound-endpoint>
</outbound-pass-through-router>
</outbound>
</service>
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...>
Note that the documentation for this example should be embedded within the code.
<service name="testService4">
<description>
This configuration will store the outbound event in the local event store (this can be a database). Then
on the 1st November at 8am the Job will be triggered and the custom job will get invoked. Notice that
the repeatCount is set to 0, this mean the even will only happen once. If you wanted to fire an even
every year at this time for the next 3 years then set the 'repeatCount' to 2.
The 'job-ref' refers to a bean configured inside the XML.
</description>
<inbound>
<inbound-endpoint address="test://inbound4"/>
</inbound>
<test:component/>
<outbound>
<outbound-pass-through-router>
<quartz:outbound-endpoint name="qEP4" repeatCount="0" cronExpression="0 11 1 8 * ?"
jobName="job4"
connector-ref="quartzConnector1">
<quartz:custom-job job-ref="custJob"/>
</quartz:outbound-endpoint>
</outbound-pass-through-router>
</outbound>
</service>
Attributes of <custom-job-from-message...>
Example Configurations
Note that the documentation for this example should be embedded within the code.
RMI Transport
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.
<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:rmi="http://www.mulesource.org/schema/mule/rmi/2.1"
xmlns:vm="http://www.mulesource.org/schema/mule/vm/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/vm/2.1 http://www.mulesource.org/schema/mule/
vm/2.1/mule-vm.xsd
http://www.mulesource.org/schema/mule/rmi/2.1 http://www.mulesource.org/schema/mule/
rmi/2.1/mule-rmi.xsd">
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.1"
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.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/jnp/2.1 http://www.mulesource.org/schema/mule/
jnp/2.1/mule-jnp.xsd">
Configuration Reference
Connector
Attributes of <connector...>
Endpoint
Attributes of <endpoint...>
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...>
For example:
You can also specify the servlet URL as part of the endpoint:
or:
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.
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
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.
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.
SMTP Connector
The SMTP connector supports all the common connector attributes and properties and the following
optional element and attributes:
<connector ...>
Attributes
For example:
Endpoints
SMTP endpoints describe details about the SMTP server and the recipients of messages sent from
the SMTP endpoint. You configure the endpoints just as you would with any other transport, with the
following additional attributes:
Attribute Description
For example:
<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"/>
If you only need a few attributes, you can specify the endpoint as a URI. However, the above syntax is
recommended for easier readability. The URI syntax is as follows:
For example:
smtp://muletestbox:123456@smtp.mail.yahoo.co.uk?address=dave@mycompany.com
This will send mail using smtp.mail.yahoo.co.uk (using the default SMTP port) to the address
dave@mycompany.com. The SMTP request is authenticated using the username muletestbox and the
password 123456.
If you use a URI-style endpoint and you include the user name and password, 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.
So far, all configuration has been static, in that you define all the information in the configuration of the
endpoint. However, you can set the connector properties 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 to attribute (or the address parameter if you're using URIs} on the
SMTP endpoint.
SOAP Transport
The SOAP transport is deprecated and will be desupported in a future release. 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.
Endpoints
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.
Transformer
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:
...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.
<custom-transformer class="org.mule.transport.soap.transformers.HttpRequestToSoapRequest">
<spring:property name="namespace" value="http://acme.com/hello">
</custom-transformer>
SSL Transport
The SSL transport can be used for secure socket communication using SSL or TLS.
Connector
Connects Mule to an SSL socket to send or receive data via the network.
Endpoint
Attributes of <endpoint...>
host string no
Inbound Endpoint
Attributes of <inbound-endpoint...>
host string no
Outbound Endpoint
Attributes of <outbound-endpoint...>
host string no
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:
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...>
Transformers
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.
Table of Contents
• 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.
Attributes of <inbound-endpoint...>
host string no
Outbound Endpoint
Attributes of <outbound-endpoint...>
host string no
Endpoint
Attributes of <endpoint...>
host string 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.
Attributes of <eof-protocol...>
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...>
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.
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...>
Custom Protocol
The user may supply their own protocol implementation via this element.
Attributes of <custom-protocol...>
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
UDP Transport
The UDP transport enables events to be sent and received as Datagram packets.
Connector
Attributes of <connector...>
Endpoints
You configure UDP endpoints just as you would with any other transport, with the following additional
attributes:
For example:
Message Payload
The default message payload of the UDP transport for incoming messages is a byte[] array.
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.
Using VM Queues
When using a synchronous VM endpoint, messages are delivered in memory from one component to
another (asynchronous endpoints introduce a queue that threads can consume from). However, when the
queueEvents property is set, messages 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 messages must use a VM connector that has queueEvents enabled. You cannot set the
queueEvents property on the endpoint. For example:
<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.
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.
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.
Configuration Reference
Following are the elements and attributes you can set for the VM transport.
Connector
Attributes of <connector...>
Inbound Endpoint
The endpoint on which this connector receives messages from the transport.
Attributes of <inbound-endpoint...>
Outbound Endpoint
The endpoint to which this connector sends messages.
Attributes of <outbound-endpoint...>
Endpoint
An endpoint "template" that can be used to construct an inbound or outbound endpoint elsewhere in the
configuration by referencing the endpoint name.
Transaction
The transaction configuration.
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.
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.
<endpoint
address="wsdl-cxf:http://localhost:8080/book/services/BookService?method=getBooks">
<properties>
<property name="wsdlLocation" value="file:///c:/BookService.wsdl"/>
</properties>
</endpoint>
In this case, the WSDL CXF endpoint works as it normally does, except that it reads the WSDL from the
local drive.
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>.
<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&method=ConversionRate"
synchronous="true"/>
<outbound-endpoint address="stdio://System.out"/>
</chaining-router>
</outbound>
For example, type "EUR,USD" to get the conversion rate for Euros to US Dollars, and you'll get something
like this:
XMPP Transport
[ Inbound Endpoint ] [ Outbound Endpoint ] [ Endpoint ] [ Transformers ] [ Filters ]
The XMPP transport enables the XMPP (Jabber) instant messaging protocol. The XMPPS connector
provides a secure implementation.
Inbound Endpoint
The endpoint on which this connector receives messages from the transport.
Attributes of <inbound-endpoint...>
Outbound Endpoint
The endpoint to which this connector sends messages.
Attributes of <outbound-endpoint...>
Endpoint
An endpoint "template" that can be used to construct an inbound or outbound endpoint elsewhere in the
configuration by referencing the endpoint name.
Attributes of <endpoint...>
</mule>
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.1 http://www.mulesource.org/schema/mule/xmpps/2.1/
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.
Filters
There are several filters in the org.mule.transport.xmpp.filters package that filter XMPP messages.
AbstractXmppFilter is an abstract filter adapter that allows Smack filters to be configured as Mule
filters. The following filter classes extend the abstract filter:
All objects you add to the registry using this mechanism must have a default constructor. They can
implement injection interfaces such as org.mule.MuleContextAware and lifecycle interfaces such as
org.mule.api.lifecycle.Initialisable .
src/main/resources/META-INF/services/org/mule/config/registry-bootstrap.properties
Each entry in the registry-bootstrap.properties file is a simple key/value pair that defines the
object:
myobject=org.foo.MyObject
If this file is in a module or transport's META-INF directory, Mule will register an instance of
org.foo.MyObject with a key of 'myobject' into the local registry when that module or transport is
loaded.
If you want to ensure that the object gets a unique ID in the local registry, you can use object.n for the
key, where n is a sequential number:
object.1=org.foo.MyObject
object.2=org.bar.MyObject
Adding Transformers
When adding transformers, you can also define the returnClass and name of the transformer as
parameters:
transformer.1=org.mule.transport.jms.transformers.JMSMessageToObject,returnClass=byte[]
transformer.2=org.mule.transport.jms.transformers.JMSMessageToObject,returnClass=java.lang.String,
name=JMSMessageToString
transformer.3=org.mule.transport.jms.transformers.JMSMessageToObject,returnClass=java.util.Hashtable)
Note that the key used for transformers must be transformer.n where n is a sequential number.
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:
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).
• Straightforward to do
• Well understood by developers
Cons:
Pros:
• Straightforward to do
• Well understood by developers
Cons:
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.
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:
Cons:
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.
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.
Related Topics
As you design your topology, there are several other topics to keep in mind that are beyond the scope of
this documentation:
Configuration Overview
[ Configuration Files ] [ Configuration Builders ] [ Accessing the Configuration Programmatically ] [
Configuring System Properties ]
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:
If you want to start Mule by calling it from your code, you specify the configuration file as a parameter to
the ConfigurationBuilder:
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:
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.
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.
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.
You can also specify the configuration builder as a parameter to the MuleContextFactory when starting
Mule programatically:
For example:
For more information on the system properties you can set programmatically, see
DefaultMuleConfiguration .
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
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.
<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
<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.
Child Elements
<custom-async-reply-router ...>
Attributes
Child Elements
<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
<custom-catch-all-strategy ...>
Attributes
Child Elements
spring:property 0..*
<forwarding-catch-all-strategy ...>
Forwards the message to the specified endpoint if no outbound routers match.
Child Elements
<custom-forwarding-catch-all-strategy ...>
Attributes
Child Elements
spring:property 0..*
<component ...>
A simple POJO (Plain Old Java Object) component that will be invoked by Mule when a message is
received. The class or object instance to be used can be specified using a child object factory element,
or via the 'class' attribute. If the 'class' attribute is used, an object factory cannot be configured as well.
Using the 'class' attribute is equivilant to using the propotype object factory ('prototype-object' child
element).
Attributes
Child Elements
abstract-lifecycle-adapter- 0..1
factory
<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 a class.
Attributes
Child Elements
abstract-lifecycle-adapter- 0..1
factory
<pooling-profile ...>
A pooling profile is used to configure the pooling behaviour of Mule components. Each component can
have its own pooling profile.
Attributes
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
by invoking
Object.wait(long)
until a new or
idle object is
available, or
WHEN_EXHAUSTED_GROW,
which will create a
new Mule instance
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.
Child Elements
<bridge-component ...>
Transfers a message from inbound to outbound endpoints. This element is provided for backward
compatibility - it is equivalent to not specifying any component.
Attributes
Child Elements
<echo-component ...>
Logs the message and returns the payload as the result.
Attributes
Child Elements
<log-component ...>
Logs the message content (or content length if it is a large message).
Attributes
Child Elements
<null-component ...>
Throws an exception if it receives a message.
Attributes
Child Elements
<spring-object ...>
Object factory used to obtain Spring bean instances. This object factory does not create any instances but
rather looks them up from Spring.
Child Elements
<singleton-object ...>
Object factory that creates and always returns a singleton object instance.
Attributes
Child Elements
<prototype-object ...>
Object factory that creates and returns a new 'prototype' object instance every time it is called.
Attributes
Child Elements
<custom-lifecycle-adapter-factory ...>
Attributes
<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.
Attributes
Child Elements
Interceptors
See Using Interceptors.
<inbound-endpoint ...>
An inbound endpoint receives messages via the associated transport. As with global endpoints, each
transport implements its own inbound endpoint element.
Attributes
Attributes
Child Elements
<endpoint ...>
A global endpoint, which acts as a template that can be used to construct an inbound or outbound
endpoint elsewhere in the configuration by referencing the global 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.
Child Elements
<default-service-exception-strategy ...>
Provide default exception handling for a service via an endpoint.
Attributes
Child Elements
<default-connector-exception-strategy ...>
Provide default exception handling for a connector via an endpoint.
Attributes
Child Elements
Attributes
Child Elements
spring:property 0..*
Filter
A filter that is defined elsewhere (at the global level, or as a Spring bean).
Attributes of <filter...>
Not Filter
Inverts the enclosed filter. For example, if the filter would normally return true for a specific message, it
will now return false, and vice versa.
And Filter
Returns true only if all the enclosed filters return true.
Or Filter
Returns true if any of the enclosed filters returns true.
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...>
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...>
Attributes of <message-property-filter...>
Attributes of <exception-type-filter...>
Attributes of <payload-type-filter...>
Custom Filter
A user-implemented filter.
spring:property 0..*
Attributes of <encryption-security-filter...>
Is Xml Filter
Accepts XML messages only. Alternatively, you can set the "not" attribute to filter out XML messages.
Jxpath Filter
Filters messages based on XPath expressions using JXPath.
Jaxen Filter
The Jaxen filter allows you to route messages based on XPath expressions. The Jaxen filter is generally
faster than the JXPath filter and should be considered the first choice when using an XPath filter.
Attributes of <jaxen-filter...>
<configuration ...>
Specifies defaults and general settings for the Mule instance.
Attributes
defaultSynchronousEndpoints
boolean no false If true, all
requests to
endpoints will wait
for a response.
defaultSynchronousEventTimeout
string no 10000 The default period
(ms) to wait for
a synchronous
response.
Child Elements
<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
Child Elements
<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
Child Elements
<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
<forwarding-router ...>
Allows messages to be forwarded to the outbound routers without first being processed by a component.
Attributes
Child Elements
<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.
Child Elements
<correlation-resequencer-router ...>
Holds back a group of messages and resequences them using each message's correlation sequence
property.
Attributes
Child Elements
Attributes
Child Elements
<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
<collection-aggregator-router ...>
Configures a Collection Response Router. This will return a MuleMessageCollection message type that will
contain all messages received for a each correlation group.
Attributes
Child Elements
<custom-inbound-router ...>
Allows for custom inbound routers to be configured.
Attributes
spring:property 0..*
<model ...>
The container for a set of services, providing basic settings and processing for all the services it contains.
Attributes
Child Elements
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...>
maxOutstandingMessages
integer no Defines the
maximum number
of messages that
can be queued.
Exception Strategy
See Exception Strategy Configuration Reference.
Service
See Service Configuration Reference.
Notifications
Registers listeners for notifications and associates interfaces with particular events.
Attributes of <notifications...>
Notification
Associates an event with an interface. Listeners that implement the interface will receive instances of the
event.
Attributes of <notification...>
Disable Notification
Blocks the association of an event with a particular interface. This filters events after the association with
a particular interface (and so takes precedence).
Attributes of <disable-notification...>
Notification Listener
Registers a bean as a listener with the notification system. Events are dispatched by 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.
Attributes of <notification-listener...>
Notification Types
You can specify the following types of notifications using the event attribute of the <notification> and
<disable-notification> element:
"CONTEXT"
"MODEL"
"SERVICE"
"SECURITY"
"ENDPOINT-MESSAGE"
"COMPONENT-MESSAGE"
"MANAGEMENT"
"CONNECTION"
<pass-through-router ...>
This router always matches and simply sends or dispatches message via the endpoint that is configured.
Attributes
Child Elements
<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.
Attributes
Child Elements
<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.
Attributes
Child Elements
<chaining-router ...>
Sends the message through multiple endpoints using the result of the first invocation as the input for the
next.
Attributes
Child Elements
<exception-based-router ...>
Sends a message over an endpoint by selecting the first endpoint that can connect to the transport.
Attributes
Child Elements
Attributes
Child Elements
<endpoint-selector-router ...>
Selects the outgoing endpoint based on an expression evaluator ("header:endpoint" by default). It will
first try to match the endpoint by name and then by address. The endpoints to use can be set on the
router itself or be global endpoint definitions.
Attributes
Child Elements
<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
Child Elements
<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
Attributes of <filter-based-splitter...>
externalSchemaLocation
string no The location of a
schema location
that should be
Attributes of <round-robin-splitter...>
externalSchemaLocation
string no The location of a
schema location
that should be
used to validate
the current
message. This is
not required if the
message contains
the location of the
schema.
<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
Child Elements
<static-recipient-list-router ...>
Sends the same message to multiple endpoints over the same endpoint, or implements routing-slip
behavior where the next destination for the message is determined from message properties or the
payload. It uses a static list of recipient endpoints.
Attributes
Child Elements
<expression-recipient-list-router ...>
Sends the same message to multiple endpoints over the same endpoint, or implements routing-slip
behavior where the next destination for the message is determined from message properties or the
payload. The recipients can be extracted from the message using an expression, or you can specify a
static list of recipient endpoints. (As of version 2.1)
Attributes
Child Elements
<custom-outbound-router ...>
Allows you to configure a custom outbound router by specifying the custom router class and by using
Spring properties.
Attributes
Child Elements
spring:property 0..*
Global Property
A global property is a named string. It can be inserted in most attribute values using standard (ant-style)
Spring placeholders.
Attributes of <global-property...>
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. Typically, 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...>
key string no
value string no
Properties
A map of Mule properties.
Attributes of <jndi-provider-property...>
key string no
value string no
<service ...>
Describes how to receive messages, deliver them to a component, and handle the results (if any).
Attributes
Child Elements
<custom-service ...>
A user-implemented service (typically used only in testing).
Attributes
Child Elements
<description ...>
Holds any kind of documentation that accompanies this configuration file. It is intended to be "human
readable" only and is not used by the system.
Child Elements
<description ...>
This can hold any kind of documentation related to the service. It is intended to be "human readable"
only and is not used by the system.
Attributes
Child Elements
<inbound ...>
The elements within 'inbound' describe how a service receives messages.
Attributes
Child Elements
<outbound ...>
The elements within 'outbound' describe how a service sends or dispatches messages.
Attributes
Child Elements
<async-reply ...>
The elements within 'async-reply' describe how asynchronous replies are handled.
Attributes
Child Elements
<queue-profile ...>
Specifies the properties of an internal Mule queue. Internal queues are used to queue messages for each
component managed by Mule.
Attributes
Exception Strategy
See Exception Strategy Configuration Reference.
Component
See Component Configuration Reference.
Attributes of <abstract-transaction...>
Attributes of <custom-transaction...>
Xa Transaction
An XA transaction.
Attributes of <websphere-transaction-manager...>
Attributes of <jboss-transaction-manager...>
Attributes of <jrun-transaction-manager...>
Attributes of <resin-transaction-manager...>
Attributes of <jndi-transaction-manager...>
Attributes of <custom-transaction-manager...>
spring:property 0..*
<mule xmlns="http://www.mulesource.org/schema/mule/core/2.1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:vm="http://www.mulesource.org/schema/mule/vm/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.org/schema/mule/vm/2.1 http://www.mulesource.org/schema/mule/vm/2.1/
mule-vm.xsd">
<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>
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
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:
<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.
<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:
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.
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.
<jms:endpoint queue="in.queue">
<jms:selector expression="JMSPriority > 5"/>
</jms: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.
<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
<service name="Receiver">
<inbound>
<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
<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.
<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>
Catch-all Strategies
A single "catch-all" endpoint can be configured for certain types of routers. See Using Message Routers.
<service name="dataService">
<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.
<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.
<model>
<service name="Priority1">
<file:inbound-endpoint ref="fileReader" path="/var/prio1"/>
...cut...
</service>
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.
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
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
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
axis:http://wsuser%40username:password%40localhost/services/services/Version?method=getVersion
ftp://username:password%40ftpserver
smtp://'sender%40mydomain.com':'123456'%40mailserver?address=QA
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.
<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:
• RegEx Filter
• Wildcard Filter
• Exception Type Filter
• Message Property Filter
• Logic Filters
• ° And Filter
° Or Filter
° Not Filter
<payload-type-filter expectedType="java.lang.String">
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 ognl, 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
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.
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.
You can also use the JXPath filter from the XML Module, which supports some additional properties.
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:
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.
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.
<exception-type-filter expectedType="java.lang.RuntimeException"/>
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
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.
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 (.*)"/>
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>
This method returns true if the message matches the criteria that the filter imposes. Otherwise, it returns
false.
You can then use this filter with the <custom-filter...> element, using the class attribute to specify
the custom filter class you created and specifying any necessary properties using the <spring:property>
child element. For example:
<outbound>
<filtering-router>
<cxf:outbound-endpoint address="http://localhost:65071/services/EnterOrder?method=create"
synchronous="true"/>
<custom-filter class="org.mule.transport.http.filters.HttpRequestWildcardFilter">
<spring:property name="pattern" value="/services/EnterOrder?wsdl"/>
</custom-filter>
</filtering-router>
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.
numberOfConcurrentTransactedReceivers
If No
createMultipleTransactedReceivers
is set to true, the number of
concurrent receivers that will be
launched.
Retry Policies
Retry policies are used to configure how a connector behaves when its connection fails. For complete
information, see Configuring Retry Policies.
• Service overrides
Attributes of <receiver-threading-profile...>
Attributes of <dispatcher-threading-profile...>
Service Overrides
Service overrides allow the connector to be further configured/customized by allowing parts of
the transport implementation to be overridden, for example, the message receiver or dispatcher
implementation, or the message adaptor that is used.
Attributes of <service-overrides...>
transactedMessageReceiver
name (no spaces) no
xaTransactedMessageReceiver
name (no spaces) no
streamMessageAdapter
name (no spaces) no
[ Configuring Retry Policies with the Retry Schema ] [ Simple Policy ] [ Forever Policy ] [ Custom
Policy ] [ Connect Notifier ] [ Custom Notifier ] [ Creating a Custom Retry Policy ] [ Configuring Retry
Policies with the Spring Schema ]
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 for JMS connectors as of Mule 2.1 (as of
Mule 2.1.2, it has been officially tested with Active MQ only).
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.
<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...>
For example:
Forever Policy
Retry an infinite amount of times at the specified frequency.
Attributes of <forever-policy...>
Custom Policy
A user-defined retry policy.
Attributes of <custom-policy...>
spring:property 0..*
For example:
By default, a retry policy will block until it is able to connect/reconnect. Enabling asynchronous retry
means the application does not need to wait for all endpoints to connect before it can start up, and if a
connection is lost, the reconnection will happen in a separate thread from the application thread. Note
that such behavior may or may not be desirable depending on your application.
Any retry policy can be made asynchronous by simply setting the attribute asynchronous="true". For
example:
Transactions
If transactions are properly configured, any messages being routed by Mule at the time a retry policy
goes into effect will not be dropped. Instead, the transaction will roll back and only commit once the
transport finally reconnects successfully via the retry policy.
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:
Custom Notifier
A user-defined retry notifier.
Attributes of <custom-notifier...>
spring:property 0..*
For example:
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.
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>
For example:
package com.acme.retry;
Configuring Logging
[ Troubleshooting Logging ] [ Controlling Logging from JMX ]
For logging, Mule uses slf4j, which is a logging facade that discovers and uses a logging strategy from the
classpath, such as Log4J or the JDK Logger. By default, Mule includes Log4J, which is configured with a
file called log4j.properties.
The Mule server has a log4j.properties in its conf directory, which you can customize when running
the server in standalone mode. Additionally, all the examples included with Mule have log4j.properties
files in their conf directories.
Troubleshooting Logging
A log4j.properties file must be at the root of your classpath. If you don't have a log4j.properties
file, you can get a simple one here. For more information about configuring Log4J, see their website.
This happens because there is another log4j.properties file on your classpath that is getting picked up
before your modified one. To find out which configuration file Log4J is using, you must add the following
JVM parameter to the Mule startup script (or container startup script if you are embedding Mule):
-Dlog4j.debug=true
This parameter will write the Log4J startup information, including the location of the configuration file
being used, to stdout. You must remove that configuration file before your modified configuration will
work.
You can remove Log4J by deleting log4j-xx.jar from your Mule classpath. You will then need to check
that the logging system you are using is supported by slf4j and put the necessary JAR (unless using
JDK1.4 Logger) and configuration files on the Mule classpath.
Configuring Queues
[ SEDA Service Queues ] [ Transport Queues ] [ Queue Configuration ] [ Queue Profile ]
Mule uses queues to enable asynchronous message processing. This page describes the places where
Mule uses queues and how to configure them. Note that you can use Mule HQ to monitor your queues
and see historically how many messages they have contained. For more information, see Using Mule HQ.
When a SEDA service is stopped either by calling stop() on the service or by shutting down Mule,
all messages still in the queue are processed before the service completes the stop phase if a non-
persistent queue is being used. If a persistent queue is being used, Mule will complete the processing of
any messages that are currently being processed but will not take any new messages from the queue
once the service has been requested to stop. Once the service or Mule is restarted, any messages in the
persistent queue will be processed.
Note: If a SEDA service is paused when stop() is called, and a non-persistent queue is being used, all
messages pending processing in the queue will be lost.
By using persistent SEDA queues and using transports that support persistence for any message channels
that Mule uses internally, you can easily achieve graceful shutdown. Although message loss shouldn't
occur if you design your system using these guidelines, if messages are absolutely critical, you should be
using synchronous endpoints with transactions.
Transport Queues
Transports may also uses queues internally to enable asynchronous message delivery. Often this is
inherent in the transport implementation, such as with JMS, whereas the Mule VM Transport allows you to
enable or disable queuing and to configure the queue.
Queue Configuration
You configure the queue profile using the <queue-profile> element on the model and/or services,
where services inherit the queue configuration from the model but override it if a <queue-profile> is
configured explicitly on a service.
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...>
Persistence Strategies
You specify the persistence strategy to use by setting the persistent attribute of the queue-profile.
If set to true, the FilePersistenceStrategy is used, and if false, the MemoryPersistenceStrategy is
used.
Currently, you cannot configure alternative persistence strategies as part of the typed Mule XML
configuration. However, if you need to change them, such as to persist to a database instead of disk, you
can override the defaults in mule-default-config.xml by redefining the _muleQueueManager bean in
your own configuration file. Custom persistence strategies must implement QueuePersistenceStrategy .
Configuring Security
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. All
security is pluggable via the Mule security API , so you can easily plug in custom implementations.
Acegi
Acegi provides a number of authentication and authorization providers such as JAAS, LDAP, CAS (Yale
Central Authenication service), and DAO. The following topics will help you get started securing your
services using Acegi:
This page describes how you can configure method-level authorization on your components so that users
with different roles can only invoke certain service methods.
• MethodSecurityInterceptor
• AuthenticationManager
• AccessDecisionManager
• AutoProxyCreator
• RoleVoter
The MethodSecurityInterceptor
• AuthenticationManager
• AccessDecisionManager
Following is a security interceptor for intercepting calls made to the methods of a component that has an
interface myComponentIfc, which defines two methods: delete and writeSomething. Roles are set on
these methods as seen below in the property objectDefinitionSource.
<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.2"
xmlns:acegi="http://www.mulesource.org/schema/mule/acegi/2.2"
...cut...
<bean id="myComponentSecurity"
class="org.acegisecurity.intercept.method.aopalliance.MethodSecurityInterceptor">
<property name="authenticationManager" ref="authenticationManager"/>
<property name="accessDecisionManager" ref="accessDecisionManager"/>
<property name="objectDefinitionSource">
<value>
com.foo.myComponentIfc.delete=ROLE_ADMIN
com.foo.myComponentIfc.writeSomething=ROLE_ANONYMOUS
</value>
</property>
</bean>
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.
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.
• MODE_THREADLOCAL, which allows the authentication to be set on the current thread (this is the
default 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
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 for the authentication to be set on more than one thread.
<acegi:security-manager>
<acegi:delegate-security-provider name="memory-dao" delegate-ref="daoAuthenticationProvider">
<acegi:security-property name="securityMode" value="MODE_GLOBAL"/>
</acegi:delegate-security-provider>
</acegi:security-manager>
This feature requires Mule 2.2, which is currently available as a snapshot only
This page describes how you can configure method-level authorization using Spring Security on your
components so that users with different roles can only invoke certain service methods.
• MethodSecurityInterceptor
• AuthenticationManager
• AccessDecisionManager
• AutoProxyCreator
• RoleVoter
The MethodSecurityInterceptor
• AuthenticationManager
• AccessDecisionManager
Following is a security interceptor for intercepting calls made to the methods of a component that has an
interface myComponentIfc, which defines two methods: delete and writeSomething. Roles are set on
these methods as seen below in the property objectDefinitionSource.
<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.2"
xmlns:mule-ss="http://www.mulesource.org/schema/mule/spring-security/2.2"
...cut...
<bean id="myComponentSecurity"
class="org.springframework.security.intercept.method.aopalliance.MethodSecurityInterceptor">
<property name="authenticationManager" ref="authenticationManager"/>
<property name="accessDecisionManager" ref="accessDecisionManager"/>
<property name="objectDefinitionSource">
<value>
com.foo.myComponentIfc.delete=ROLE_ADMIN
com.foo.myComponentIfc.writeSomething=ROLE_ANONYMOUS
</value>
</property>
The AuthenticationManager
This bean is responsible for passing requests through a chain of AuthenticationProvider objects.
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.
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 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 ConfigAttribute objects 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.
• MODE_THREADLOCAL: allows the authentication to be set on the current thread (this is the default
strategy used by Acegi)
• MODE_INHERITABLETHREADLOCAL: allows authentication to be inherited from the parent thread
• MODE_GLOBAL: allows the authentication to be set on all threads
The use of Acegi's security strategies is particularly useful for asynchronous systems, since we have to
add a property on the security provider for the authentication to be set on more than one thread. In this
case, we would use MODE_GLOBAL as shown in the following example:
<mule-ss:security-manager>
<mule-ss:delegate-security-provider name="memory-dao" delegate-ref="authenticationManager">
<mule-ss::security-property name="securityMode" value="MODE_GLOBAL"/>
</mule-ss::delegate-security-provider>
</mule-ss:security-manager>
Example Configuration
The following example illustrates how to configure a single security provider on Mule, in this case an
in-memory DAO. Here we have a static DAO security provider that allows user credentials to be set in
memory with two users: ross and anon.
<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:acegi="http://www.mulesource.org/schema/mule/acegi/2.2"
...cut...
<spring:bean id="daoAuthenticationProvider"
class="org.acegisecurity.providers.dao.DaoAuthenticationProvider">
<spring:property name="userDetailsService" ref="inMemoryDaoImpl"/>
</spring:bean>
<acegi:security-manager>
<acegi:delegate-security-provider name="memory-dao" delegate-ref="daoAuthenticationProvider"/>
</acegi:security-manager>
...cut...
</mule>
Security Filters
Security filters can be configured on an object to either authenticate inbound requests or attach
credentials to outbound requests. For example, to configure an HTTP basic authorization filter on an HTTP
endpoint, you would use the following endpoint security filter:
<inbound-endpoint address="http://localhost:4567">
<acegi:http-security-filter realm="mule-realm"/>
</inbound-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.
This feature requires Mule 2.2, which is currently available as a snapshot only
Mule supports using Spring Security 2.0 as a Security Manager inside of Mule. You can use any of the
library's security providers such as JAAS, LDAP, CAS (Yale Central Authenication service), and DAO.
Example
The following example illustrates how to configure a single security provider on Mule, in this case an
in-memory database of users. To configure the provider, we set up a <user-service> element and the
<authentication-manager> to which Mule delegates.
<mule-ss:security-manager>
<mule-ss:delegate-security-provider name="memory-provider" delegate-ref="authenticationManager" />
</mule-ss:security-manager>
<spring:beans>
<ss:authentication-manager alias="authenticationManager" />
<ss:authentication-provider>
<ss:user-service id="userService">
<ss:user name="ross" password="ross" authorities="ROLE_ADMIN" />
<ss:user name="anon" password="anon" authorities="ROLE_ANON" />
</ss:user-service>
</ss:authentication-provider>
</spring:beans>
...cut...
</mule>
<inbound-endpoint address="http://localhost:4567">
<mule-ss:http-security-filter realm="mule-realm"/>
</inbound-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.
<inbound-endpoint address="http://localhost:4567">
<mule-ss:http-security-filter realm="mule-realm" securityProviders="default,another"/>
</inbound-endpoint>
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 transports such as SSL or HTTPS. These
encryption strategies can greatly simplify configuration for secure messaging as they can be shared
across components.
<security-manager>
<password-encryption-strategy name="PBE" password="mule"/>
</security-manager>
This strategy can then be referenced by other components in the system such as filters or transformers.
<service name="Svc1">
<inbound>
<inbound-endpoint address="vm://test">
<encryption-security-filter strategy-ref="PBE"/>
</inbound-endpoint>
</inbound>
...cut...
<service name="Svc2">
...cut...
<outbound>
<pass-through-router>
<outbound-endpoint address="vm://output" transformer-refs="EncryptedToByteArray"/>
</pass-through-router>
</outbound>
This page describes how you can configure an Acegi LDAP provider, which can be:
<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.2"
xmlns:acegi="http://www.mulesource.org/schema/mule/acegi/2.2"
...cut...
<acegi:security-manager>
<acegi:delegate-security-provider name="acegi-ldap" delegate-ref="authenticationProvider"/>
</acegi:security-manager>
With the above configuration, you can achieve endpoint-level security and other security features in Mule
that require one or more security providers.
The roles are looked up by the DefaultLdapAuthoritiesPopulator, which you configured in the
previous section. By default, a role is prefixed with ROLE_ and its value is extracted (and converted to
uppercase) from the LDAP attribute defined by the groupRoleAttribute.
This feature requires Mule 2.2, which is currently available as a snapshot only
This page describes how you can configure a Spring Security LDAP provider, which can be used by Mule
as follows:
<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.2"
xmlns:mule-ss="http://www.mulesource.org/schema/mule/spring-security/2.2"
...cut...
<bean id="initialDirContextFactory"
class="org.springframework.security.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.springframework.security.providers.ldap.LdapAuthenticationProvider">
<constructor-arg>
<bean class="org.springframework.security.providers.ldap.authenticator.BindAuthenticator">
<constructor-arg ref="initialDirContextFactory" />
<property name="userDnPatterns">
<list>
<value>uid={0},ou=people</value>
</list>
</property>
</bean>
</constructor-arg>
<constructor-arg>
<bean
class="org.springframework.security.providers.ldap.populator.DefaultLdapAuthoritiesPopulator">
<constructor-arg ref="initialDirContextFactory"/>
<mule-ss:security-manager>
<mule-ss:delegate-security-provider name="acegi-ldap" delegate-ref="authenticationManager"/>
</mule-ss:security-manager>
With the above configuration, you can achieve endpoint-level security and other security features in Mule
that require one or more security providers.
The roles are looked up by the DefaultLdapAuthoritiesPopulator, which you configured in the
previous section. By default, a role is prefixed with ROLE_, and its value is extracted and converted to
uppercase from the LDAP attribute defined by the groupRoleAttribute.
Spring Security is version 2.0 of the Acegi Security framework. Upgrading your Mule application to use
Spring Security instead of Acegi involves the following steps:
<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:mule-ss="http://www.mulesource.org/schema/mule/spring-security/2.2"
xmlns:ss="http://www.springframework.org/schema/security"
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.2 http://www.mulesource.org/schema/mule/core/2.2/
mule.xsd
http://www.mulesource.org/schema/mule/spring-security/2.2
http://www.mulesource.org/schema/mule/spring-security/2.2/mule-spring-security.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-2.0.xsd">
...
</mule>
The mule-ss namespace is for the Mule Spring Security extensions. The ss namespace is for the Spring
Security schema elements that are not Mule specific and allows you to use the less verbose XML that is
part of Spring Security 2.0.
<bean class="org.acegisecurity.providers.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userService"/>
</bean>
To use Spring Security, you simply change the acegisecurity package to springframework.security:
<bean class="org.springframework.security.providers.dao.DaoAuthenticationProvider">
Using an AuthenticationManager
The only major difference between Mule integration with Acegi and Spring Security is that the latter
uses the AuthenticationManager to provider authentication functions, while the former tied in at the
Acegi AuthenticationProvider level. With the Acegi provider, the authentication flow followed this
progression:
This allows the authentication manager to try multiple authentication providers to authenticate your
messages.
Configuration of this approach requires a little more XML. For example, consider this original
configuration:
<mule ...>
<acegi:security-manager>
<acegi:delegate-security-provider name="memory-dao" delegate-ref="daoAuthenticationProvider"/>
</acegi:security-manager>
<spring:bean id="daoAuthenticationProvider"
class="org.acegisecurity.providers.dao.DaoAuthenticationProvider">
<spring:property name="userDetailsService" ref="inMemoryDaoImpl"/>
</spring:bean>
</mule>
To upgrade this configuration, you add an AuthenticationManager. This would result in the following:
<mule ...>
<mule-ss:security-manager>
<mule-ss:delegate-security-provider name="memory-dao" delegate-ref="authenticationManager"/>
</mule-ss:security-manager>
<spring:bean id="daoAuthenticationProvider"
class="org.springframework.security.providers.dao.DaoAuthenticationProvider">
<spring:property name="userDetailsService" ref="inMemoryDaoImpl"/>
</spring:bean>
<spring:bean id="authenticationManager"
class="org.springframework.security.providers.ProviderManager">
<spring:property name="providers">
<spring:list>
<spring:ref bean="daoAuthenticationProvider"/>
</spring:list>
</spring:property>
</spring:bean>
</mule>
<mule ...>
<mule-ss:security-manager>
<mule-ss:delegate-security-provider name="memory-dao" delegate-ref="authenticationManager" />
</mule-ss:security-manager>
<spring:beans>
<ss:authentication-manager alias="authenticationManager" />
<ss:authentication-provider>
<ss:user-service id="userService">
<ss:user name="ross" password="ross" authorities="ROLE_ADMIN" />
<ss:user name="anon" password="anon" authorities="ROLE_ANON" />
</ss:user-service>
</ss:authentication-provider>
</spring:beans>
</mule>
For more information on how to configure Acegi, see the following Spring documentation:
• 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.
• 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.
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>.
Mule Namespace
<spring:beans>
<!-- and you can have nested spring definitions -->
</spring:beans>
</mule>
Note here we have a spring namespace declared so we can embed spring beans directly inside your Mule
configuration file.
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:
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:
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-J. For more information see this post
about how to work with Mule schemas in IntelliJ.
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.
• 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
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>.
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 should
extend the corresponding complex type. Using TCP as an example, here is an excerpt from where
we define the noProtocolTcpConnectorType:
<xsd:import namespace="http://www.mulesource.org/schema/mule/core/2.1"/>
<xsd:complexType name="noProtocolTcpConnectorType">
<xsd:complexContent>
<xsd:extension base="mule:connectorType">
<xsd:attribute name="sendBufferSize" type="mule:substitutableInt">
<xsd:annotation>
<xsd:documentation>
The size of the buffer (in bytes) used when sending data, set on the socket itself.
</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="receiveBufferSize" type="mule:substitutableInt">
<xsd:annotation>
<xsd:documentation>
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:
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.1
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.
http\://www.mulesource.org/schema/mule/tcp/2.1/mule-tcp.xsd=META-INF/mule-tcp.xsd
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:
http\://www.mulesource.org/schema/mule/tcp/2.1=org.mule.transport.tcp.config.TcpNamespaceHandler
The TcpNamespaceHandler code is very simple because there is a base support class provided:
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
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:
Naming Conventions
The number and variety of definition parsers is growing rapidly. To make them more manageable, please
use the following conventions.
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:
}
}
<xsd:import namespace="http://www.w3.org/XML/1998/namespace"/>
<xsd:import namespace="http://www.mulesource.org/schema/mule/core/2.1"
schemaLocation="http://www.mulesource.org/schema/mule/core/2.1/mule.xsd" />
<xsd:import namespace="http://www.mulesource.org/schema/mule/tcp/2.1"
schemaLocation="http://www.mulesource.org/schema/mule/tcp/2.1/mule-tcp.xsd"/>
Simple Recipe
The following recipe is sufficient for a simple transport (like UDP). The ordering helps guarantee complete
coverage.
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
import org.mule.routing.outbound.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":
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:
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:
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.
The other responsibility of inbound routers is to control how a message is processed by a service. It can
choose to:
Creating Transports
[ Overview ] [ Transport Interfaces ] [ Implementation ] [ Connectors ] [ Message Receivers ] [ Message
Dispatchers ] [ Message Requesters ] [ Service Descriptors ] [ Coding Standards ] [ Package Structure ]
Transports are used to implement message channels and provide connectivity to an underlying data
source or message channel 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. If you want to update an existing transport,
use the Module Archetype instead.
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
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, Dispatchers and Requesters
are stored on the connector. Usually, only one connector instance is needed for multiple inbound and
outbound endpoints as multiple Message Receivers, Dispatchers and Requesters 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 messages, which is akin to making client calls with the
underlying technology. For example, the CXF 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.MessageRequester
The Message Requester is used to request messages from a message channel or resource rather than
subscribing to inbound events or polling a resource for messages. This is often used programatically but
is not used for inbound endpoints configured on services. An implementation of this class is needed if the
transport supports the requesting of messages from a message channel.
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.
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
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.
• 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 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
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.
Setting up and destroying the listening thread should occur in the doStart() and doStop() methods
respectively.
Methods to Implement
Methods to Implement
You implement the following methods for the transacted polling message receiver in addition to those in
the standard Message Receiver:
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.
When scheduling work with the WorkManager, you should call scheduleWork(...) on the WorkManager
rather than startWork(...).
Message Dispatchers
Whereas a message receiver is equivalent to a server for the transport in that it serves client requests,
a message dispatcher is the client implementation of the transport. Message dispatchers 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 three methods for the custom
MessageDispatcher to implement.
Methods to Implement
Message Requesters
As with message receivers and dispatchers the implementation of a message requester for a transport,
if it even applies, will vary greatly. The abstract AbstractMessageRequester provides a base from which
to extend and implement your own Message Requester and implemented methods for routing events.
Although requesters can implement doConnect} and {{doDisconnect methods given the nature of a
requester this can also be done as part of the doRequest implementation, it really depending on the
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.
Message Adapters
Message adapters are usually simple objects that provide a uniform way of accessing a message 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 message adapter just
needs to allow access to the header properties using standard Map notation. For example:
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.
Methods to Implement
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
Following are coding standards to use when creating transports.
Package Structure
All Mule transports 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 in either a 'transformers' or 'filters' package under the main package.
Note that if a transport has more than one implementation for a given protocol, such as the Axis and CXF
implementations of the SOAP protocol, the package name should be the protocol, such as soap instead of
axis or cxf.
Any exceptions messages used in your transport implementation should be stored in a resource bundle
so that they can be internationalized . The message bundle is a standard Java properties file and must be
located at:
META-INF/services/org/mule/i18n/<protocol>-messages.properties
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.
For more information on Maven, see Using Maven.
If you want to update an existing transport instead of creating a new one, such as adding new schema
namespaces and registry bootstrapping to the transport, use the Module Archetype instead.
Follow the instructions below to create template files for a new transport, including all the necessary Java
boilerplate and detailed implementation instructions in comments.
Configuring Maven
Add the following to the file settings.xml (usually in your Maven conf or $HOME/.m2 directory) so that
Maven will allow you to execute Mule plug-ins.
<settings>
<pluginGroups>
<pluginGroup>org.mule.tools</pluginGroup>
</pluginGroups>
...
</settings>
> cd yourDir
Next, you execute the archetype and generate the code. If this is your first time running this command,
Maven will download the archetype for you.
As of Mule 2.2, the parameter -DtransportId can be replaced with -DartifactId, which is
in line with the other Mule archetypes.
• artifactId: The short name for the project (such as 'tcp'). This must be a single word in lower
case with no spaces, periods, hyphens, etc. For transports this is usually the short protocol name of
the underlying transport being connected.
• 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.
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 transport is required.
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.
If the transport 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 transport have a custom schema for configuring the transport in Xml?
All new transports targeted for Mule 2.x 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 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.
To receive a message, some transports must do polling. For example, the File transport must
poll a directory to know something has been written there, whereas JMS provides a callback
(MessageListener) to deliver the message. This question is asked only 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 enter the name of the transformer class (without package name) to generate, such as
JmsMessageToObject.
Asks whether messages can be written to this transport. With the File transport, you can write file data to
a directory, and with JMS you can write to a queue or topic.
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 enter the name of the transformer class (without package name) to generate, such as
ObjectToJmsMessage.
This is usually only required if the underlying transport has an API that has a
message object i.e. JMSMessage or HttpServletRequest.
Can the transport request individual messages from the underlying resource?
If the transport can request messages from a message channel or resource rather than subscribing to
inbound events or polling a resource, answer yes to this question. This will generate a MessageRequester
class.
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.
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.
The Custom option allows you to deviate from the existing endpoint styles and parse your own.
If you are extending one or more existing transports, specify them here in a comma-separated list.
By default, the Mule client module is included to enable easier testing. If you want to include other
modules, specify them here in a comma-separated list.
Will this transport have a custom schema for configuring the transport in Xml?
[y] or [n]
[default: y]
********************************************************************************
[INFO] hasReceiver:
********************************************************************************
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:
********************************************************************************
If this transport will have a default outbound transformer, enter the name of the
transformer? (i.e. ObjectToJmsMessage)
[default: n]
********************************************************************************
[INFO] hasCustomMessageAdapter:
********************************************************************************
Which Mule transports do you want to include in this project? If you intend extending a
transport you should add it here:
(options: axis,cxf,ejb,file,ftp,http,https,imap,imaps,jbpm,jdbc,
jetty,jms,multicast,pop3,pop3s,quartz,rmi,servlet,smtp,
smtps,servlet,ssl,tls,stdio,tcp,udp,vm,xmpp):
[default: vm]
********************************************************************************
[INFO] modules:
********************************************************************************
Which Mule modules do you want to include in this project? The client is added f
or testing:
(options: bulders,client,jaas,jbossts,management,ognl,pgp,scripting,
spring-extras,sxc,xml):
[default: client]
********************************************************************************
-Dinteractive=false
hasCustomMessageAdapter - false
(Since Mule 2.2) DhasCustomMessageAdapter=true
groupId - org.mule.transport.<transportId>
DgroupId=org.mule.transport.tcp
endpointBuilder -DendpointBuilder=s r
transports -Dtransports=vm,jms vm
META-INF/services/org/mule/providers/<protocol>.properties
Following are the properties that can be set in a transport service descriptor.
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:
• Geronimo: The Geronimo application server uses ActiveMQ as its default JMS provider. For details,
see ActiveMQ Integration.
• JBoss
• WebLogic
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.
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 instructions 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.
Note: You can also deploy the Mule JCA Resource Adapter within an EAR, in which case you follow the
same steps but deploy your EAR rather than the RAR. Alternatively, you can deploy Mule embedded
in a web application, in which case you will need to configure logging as described below, but you will
not need to switch configuration files in the RAR, and you won't use the JCA Resource Adapter, as your
web.xml file will define the configuration file to use instead.
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.
Configuring Logging
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 using Commons logging and WebLogic, see http://e-docs.bea.com/wls/docs103/logging/
config_logs.html#wp1015132.
set CLASSPATH=%CLASSPATH%;%MEDREC_WEBLOGIC_CLASSPATH%...
set CLASSPATH=%WL_HOME%/user_projects/domains/Mule2.1/lib/commons-lang.osgi-2.4.jar;
%CLASSPATH%;%MEDREC_WEBLOGIC_CLASSPATH%...
6. Configure a system property in WebLogic's startup script by adding the following line after the
classpath modification line:
set JAVA_OPTIONS=%JAVA_OPTIONS% -
Dorg.apache.commons.logging.LogFactory=weblogic.logging.commons.LogFactoryImpl
Setting Up Web.xml
You must set up your WebLogic web.xml file to enable WebLogic to work with Mule. Open your web.xml
file and modify it with the following information:
For example, the beginning of the file should look similar to this:
<web-app id="WebApp_ID">
<!--Mule configuration (Mule format)-->
<context-param>
<param-name>org.mule.config</param-name>
<param-value>mule-config.xml</param-value>
</context-param>
<listener>
<listener-class>
org.mule.config.builders.MuleXmlBuilderContextListener
</listener-class>
</listener>
<servlet>
<servlet-name>muleServlet</servlet-name>
<servlet-class>org.mule.transport.servlet.MuleReceiverServlet</servlet-class>
<load-on-startup>100</load-on-startup>
</servlet>
<!--Mule configuration ends-->
...
</web-app>
Note: Make sure that the ports you specify in your Mule configuration file are open. You can use netstat
-a to verify this.
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. Note that this section also applies when deploying an EAR or WAR that embeds Mule to
WebLogic, in which case you deploy the EAR or WAR instead of the RAR file.
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.
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>
4. Repackage the RAR file and deploy it by copying it to the autodeploy directory and running
startWebLogic.
You can 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.
To start Mule from any Java application, you can call one of its configuration builders. To use Mule XML
configuration:
Make sure you store a reference to the MuleContext, as you will need it to stop Mule.
If you have multiple configuration files, you can provide a comma-separated list or an array of
configuration files:
SpringXmlConfigurationBuilder configBuilder =
new SpringXmlConfigurationBuilder(new String[] { "mule-config.xml", "another-config.xml" });
muleContext.start();
muleContext.stop();
muleContext.dispose();
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>
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.
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();
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.
• 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.
The file structure of the EAR file should have the following format:
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
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.
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.
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
Mule as MBean
[ Creating a Simple MBean ] [ Creating JBoss Service Descriptor ] [ Deploying MBean to JBoss ] [ Copy
the Dependencies ] [ References ]
An MBean is a named managed object representing a resource in an JMX environment. You can easily
deploy an MBean with Mule by taking the following steps:
1. Create an MBean
2. Create service descriptor
3. Deploy MBean (as .sar) to application server
4. Copy dependencies to the service's classpath
This page describes these steps using the JBoss application server.
package foo.mbean;
package foo.mbean;
import org.jboss.system.ServiceMBeanSupport;
import org.mule.config.spring.SpringXmlConfigurationBuilder;
import org.mule.api.MuleContext;
import org.mule.api.context.notification.ServerNotification;
try{
MuleContext context = new DefaultMuleContextFactory().createMuleContext
(new SpringXmlConfigurationBuilder("foo-config.xml"));
context.registerListener(this);
context.start();
}
catch(Exception e){
e.printStackTrace();
}
this.getLog().info("MBean started");
}
try {
if (context != null) {
context.stop();
context.dispose(); //
}
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.
.
./foo
./foo/FooService
./foo/FooServiceMBean
./META-INF
./META-INF/jboss-service.xml
Package the distribution either as a JAR, which you can then rename to a *.sar that you will eventually
extract, or as a directory called <dirName>.sar.
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. To
specify the method explicitly on your endpoint, you can use the method argument on the endpoint, such
as:
<outbound-endpoint address="ejb://localhost:1099/SomeService?method=remoteMethod"/>
or
If you do not specify this argument, 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.
For details on configuring entry point resolvers, see Entry Point Resolver Configuration Reference.
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.
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.
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.
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.
//or to request
InboundEndpoint endpoint = ...
MuleMessage quote = context.request(endpoint, 5000);
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.
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
Your component can implement several lifecycle interfaces. The lifecycle flow typically looks like this, with
onCall() often being replaced by an entry point resolver as described above:
• 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.
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.
<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 message to the
component. This element can be set on the model or component; the model value provides a default that
individual component values can override.
Attributes
Child Elements
<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 that individual component values can
override.
Child Elements
<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 that individual component values can override.
Attributes
Child Elements
spring:property 0..*
<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 that 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.
Child Elements
<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 that 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
Child Elements
spring:property 0..*
<property-entry-point-resolver ...>
Uses 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 that 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
Child Elements
<method-entry-point-resolver ...>
Delivers the message to a named method. This element can be set on the model or component; the
model value provides a default that 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
Child Elements
Attributes
Child Elements
<array-entry-point-resolver ...>
Delivers the message to a method that takes a single array as argument. This element can be set on the
model or component; the model value provides a default that 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.
Child Elements
<no-arguments-entry-point-resolver ...>
Calls a method without arguments (the message is not passed to the component).
Child Elements
<include-entry-point ...>
A possible method for delivery.
Child Elements
Error Handling
Error handling includes setting exceptions on models, components, and connectors. 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. For information on setting retry policies, see Configuring Retry Policies.
Exception Strategies
Exception strategies are used to handle exception conditions when an error occurs processing a message.
Exception strategies are used by components and connectors. You can set a common exception strategy
for all components in a model by configuring the exception strategy on that model.
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.
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>
<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 message that failed to a destination such as
an error queue.
If you want to change the way exceptions are logged, override the logException() method from the
org.mule.AbstractExceptionListener .
<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>
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():
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 .
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:
<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:
The component includes two methods: the onCall method and the onReceive method that basically do
the same thing.
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.
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:
<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
Now, in order for our listener to start listening for notifications, we must register it:
muleContext.registerListener(this,"myComponent");
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>
<test:component>
<test:return-data file="abc.txt"/>
</test:component>
Forcing Exceptions
You can use throwException to always return the exception specified by exceptionToThrow, as follows:
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
To enable:
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.
You can use appendString to append text to the response message, as follows:
Delayed Responses
You can set waitTime to delay responses from this FunctionalTestComponent. In this example,
responses are delayed five seconds:
You can set doInboundTransform to false to disable the inbound transformer. For example:
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.
ApplicationContext ac =
(ApplicationContext)muleContext.getRegistry().lookupObject(SpringRegistry.SPRING_APPLICATION_CONTEXT);
FunctionalTestComponent testComponent = (FunctionalTestComponent) ac.getBean("FTC");
testComponent.setEventCallback(callback);
<model name="TestComponentModel">
<service name="TestComponentService">
<inbound>
<inbound-endpoint address="vm://test" />
</inbound>
<component>
<spring-object bean="FTC" />
</component>
</service>
</model>
</mule>
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.
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:
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:
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.
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:
To load a message from this bundle, pass in the resource bundle name as follows:
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:
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 Extensions
There are four types of extensions you can create: projects, modules, transports, and examples.
• 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.
• A transport is a type of module that carries messages between Mule services via a specific
protocol. For a list of the available transports you can use, see Available Transports.
• An example is a sample application that you create to help users get up and running more quickly.
There are several examples provided with Mule.
Mule provides Maven archetypes that create the templates for each of these types of functionality in
seconds, including the configuration files, unit tests, and packages:
• Project Archetype
• Module Archetype
• Transport Archetype
• Example Archetype
An archetype acts as a wizard, prompting you to provide input, and then creates template configuration,
source, and unit test files. Furthermore, if you run an archetype on an existing project or module you
created, it will update it for you. For more information on Maven, see Using Maven.
When working with transports, note that you can configure an existing transport, or you can create a new
one. The recommended approach is to try to use and configure an existing transport first.
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.
For more information on hosting your project on MuleForge, see the Despot's Guide.
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.
• 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
Attributes of <jmx-default-config...>
For example:
Note: you only specify the port if you don't want to use the default of 1099.
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:
You configure the JMX agent using the <jmx-server> element. You can set the following properties on the
agent.
Attributes of <jmx-server...>
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().
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.
For example:
Attribute Description
For example:
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/>
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:
For example:
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.
Attributes of <jmx-mx4j-adaptor...>
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.
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.
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.
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
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.1"
...
xmlns:management="http://www.mulesource.org/schema/mule/management/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/management/2.1 http://www.mulesource.org/schema/mule/
management/2.1/mule-management.xsd"
...>
<management:jmx-default-config port="1098" registerMx4jAdapter="true" />
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.
For example:
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 Mule being
started. You can set up your agents or service components to react to these notifications.
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 notifications.
For example, first you create beans for the notification listeners, specifying the class of the type of
notification you want to receive:
Next, you specify the notifications you want to receive 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 specify the COMPONENT-MESSAGE notification, 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 types, see Notifications Configuration Reference. For a list of notification listener
interfaces, see Notification Interfaces below.
If you want to change the interface that is associated with a notification, you specify the new interface
with the interface-class and interface attributes:
<notifications>
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 a notification, you specify it with the <disable-
notification> element. You can specify the notification type (event), event class, interface, and/or
interface class to block.
<notifications>
<disable-notification interface="ComponentMessageNotificationListener"/>
...
Using 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 notifications from
a service component called "MyService1", you would configure the listener as follows:
You can also register listeners and filter the subscriptions from your Java code:
MuleServer.getMuleContext().registerListener(listener, "MyService1");
To register interest in notifications from all service components with "Service" in the name, you would use
a wildcard string as follows:
MuleServer.getMuleContext().registerListener(listener, "*Service*");
Any objects implementing CustomNotificationListener will receive this notification. It's a good idea to
extend CustomNotification and define actions for your custom notification type. For example:
Note that non-system objects in Mule can only fire custom notifications through the manager. Attempting
to fire other notifications such as ModelNotification will cause an UnsupportedOperationException.
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.
Depending on the listener implemented, only certain notifications will be received. For example, if the
object implements ManagerNotificationListener, only notifications of type ManagerNotification will
be received. Objects can implement more than one listener to receive more types of notifications.
MuleServer.getMuleContext().registerListener(listener);
If you have local access to the Mule context already (for example, if you created it right before
registering the listener), you would simply call registerListener() on the existing context instead of on
MuleServer.getMuleContext(). For example:
By default, you cannot register listeners in the Mule context after Mule has started. Therefore, you would
register your listeners in your code before starting Mule. For example:
To change this behavior so that you can add listeners dynamically at run time, you can set the dynamic
attribute on the <notifications> element. If you just want to enable dynamic notifications for a specific
connector, you can set the dynamicNotification attribute on the connector.
Each notification has an action code that determines the notification type. 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:
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 payloads for each type of notification.
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.
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.
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.
EJB Configuration
The resource adapter supports inbound and outbound communication.
<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.module.jca.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>
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
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.
JBI
The Sun JBI Site
Concurrency
Java Concurrency in Practice by Brian Goetz
Quality Improvement in Volunteer Free and Open Source Software Projects: Exploring the Impact of
Release Management by Martin Michlmayr
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.
Apache XML Security Apache 2.0 Mx4j 1.2 MX4J License 1.0
Transaction Management
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 synchronous 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.
For an excellent article on distributed transactions using both XA and non-XA approaches, see http://
www.javaworld.com/javaworld/jw-01-2009/jw-01-spring-transactions.html. The multi-resource
transaction support described below maps to the Best Efforts 1PC pattern described in the article.
Single-resource Transactions
Single-resource transactions (also called "local 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.
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.
Multi-resource Transactions
If you are using Mule Enterprise Edition, you can use the <multi-transaction> element to enable a
series of operations from multiple JMS resources to be grouped into a single transaction. Multi-resource
transactions work without the overhead of XA. The trade-off is that XA reliability guarantees aren't
provided, and your services must be ready to handle duplicates. This is very similar to a 1.5 phase
commit concept.
Multi-resource transactions are useful for creating transactional non-XA bridges. For example, if you
want to bridge two different JMS connectors (such as WebSphere MQ and Active MQ), each of which is
running local transactions instead of XA transactions, you could configure the multi-resource transaction
as follows:
<jms:websphere-connector name="jmsWSConnector"
connectionFactory-ref="mqQueueConnectionFactory"
specification="1.1"
username="" password=""
numberOfConsumers="16"/>
<jms:activemq-connector name="jmsAMQConnector"
specification="1.1"/>
<service name="JMSService1">
<inbound>
<jms:inbound-endpoint queue="in" connector-ref="jmsWSConnector">
<ee:multi-transaction action="ALWAYS_BEGIN"/>
</jms:inbound-endpoint>
</inbound>
<test:component/>
<outbound>
<pass-through-router>
<jms:outbound-endpoint queue="out" connector-ref="jmsAMQConnector"
disableTemporaryReplyToDestinations="true">
<ee:multi-transaction action="ALWAYS_JOIN"/>
</jms:outbound-endpoint>
</pass-through-router>
</outbound>
</service>
</model>
</mule>
Because the inbound JMS endpoint has a multi-resource transaction configured on it, any outbound
endpoints must also be configured with multi-resource transaction support to become part of the
transaction.
XA Transactions
You can use XA transactions if you want to enlist multiple managed resources within the same transaction
and require 100% reliability. 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.
• 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>
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.
Note: Depending on your application server vendor, the transaction manager might be available via JNDI
or only through proprietary APIs.
Weblogic javax.transaction.TransactionManager
org.mule.transaction.lookup.We
For example, to use Weblogic's transaction manager, you would configure Mule as follows:
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.
Tuning Performance
[ About Thread Pools ] [ About Threading Profiles ] [ About Pooling Profiles ] [ Calculating Threads ] [
Additional Performance Tuning Tips ] [ Threading Profile Configuration Reference ] [ Receiver Threading
Profile ] [ Dispatcher Threading Profile ] [ Pooling Profile Configuration Reference ] [ Pooling Profile ]
A Mule application is a collaboration of a set of services. Messages are processed by services in three
stages:
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.
Keep in mind that Mule can send messages asynchronously or synchronously. By default, messages are
asynchronous, which 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.
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.
The following diagram illustrates these threads.
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 given 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 that share the same connector. Typically, you get the total concurrent user requests from
the business requirements.
• 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 the connector receiver after
a round trip. Typically, you determine the processing time from the unit tests.
• Response Time: If a service runs in synchronous mode, the response time is the actual amount
of time the end user is required to 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. 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. Therefore, the
response time is a function of the following:
Response time = average of thread pool waiting time in work queue + average of processing time
Your business requirements will dictate the actual response time required from the application.
• Timeout Time: If your business requirements dictate a maximum time to wait for a response
before timing out, it will be an important factor in your calculations below.
After you have determined these requirements, you can calculate the adjustments you need to make
to maxThreadsActive and maxBufferSize for the service and the receiver thread pool. In general, the
formula is:
Where maxThreadsActive is the number of threads that run concurrently and maxBufferSize is the
number of requests that can wait in the queue for threads to be released.
Your business requirements dictate how many threads each service must be able to process concurrently.
For example, one service might need to be able to process 50 requests at a time, while another might
need to process 40 at a time. Typically, you use this requirement to set the maxThreadsActive attribute
on the service (maxThreadsActive="40").
If you have requirements for timeout settings for synchronous processing, you must do some additional
calculations for each service.
For example, assume a service must have the ability to process 200 concurrent user requests, your
timeout setting is 10 seconds, and the response time is 2 seconds, making your maximum wait time
8 seconds (10 seconds timeout minus 2 seconds response time). Divide the maximum wait time
(8 seconds) by the response time (2 seconds) to get the number of batches (4). Finally, divide the
concurrent user requests requirement (200 requests) by the batches (4) to get the maxThreadsActive
setting (50) for the service. Subtract this number (50) from the concurrent user requests (200) to get
your maxBufferSize (150).
In summary, the formulas for synchronous processing with timeout restrictions are:
A connector's receiver is shared by all services that specify the same connector on their inbound
endpoint. The previous section described how to calculate the maxThreadsActive attribute for each
service. To calculate the maxThreadsActive setting for the receiver, that is, how many threads you should
assign to a connector's receiver thread pool, sum the maxThreadsActive setting for each service that
uses that connector on their inbound endpoints:
For example, if you have three components whose inbound endpoints use the VM connector, and your
business requirements dictate that two of the services should handle 50 50 requests at a time and the
third service should handle 40 requests at a time, set maxThreadsActive to 140 in the receiver threading
profile for the VM connector.
In the component stage, the transformed message from the inbound endpoint is passed to the
component thread. As you can see from the previous illustration, there are two pools involved here:
a component thread is taken from component's thread pool, and a POJO instance is taken from the
component object pool (if the component is configured as a pooled component instead of a singleton).
Therefore, the number of component threads must match the number of component instances in the
component pool. Otherwise, a bottle neck on either side will develop.
Like the receiver thread pool, the component thread pool can be shared if multiple services use the same
component. In this case, use the following formula:
Like component threads, dispatcher threads are used only for asynchronous processing. Typically, set the
dispatcher threads to the same number as the component threads.
Other Considerations
You can trade off queue sizes and maximum pool sizes. Using large queues and small pools minimizes
CPU usage, OS resources, and context-switching overhead, but it can lead to artificially low throughput.
If tasks frequently block (for example, if they are I/O bound), a system may be able to schedule time
for more threads than you otherwise allow. Use of small queues generally requires larger pool sizes,
which keeps CPUs busier but may encounter unacceptable scheduling overhead, which also decreases
throughput.
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.
Attributes of <receiver-threading-profile...>
Attributes of <dispatcher-threading-profile...>
Attributes of <pooling-profile...>
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
• 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.
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:
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 stand-alone 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. Mule HQ supports stand-alone Mule deployments
only and cannot monitor embedded Mule instances.
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:
In large environments, the HQ Server can be clustered to enhance fault tolerance and to share the overall
system load across multiple machines.
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.
Your Mule configuration files must be available to Mule HQ on a relative or absolute path.
They cannot be embedded in a JAR file.
The default JMX support agent configures several JMX agents simultaneously. To add this to your
configuration, you add the management namespace and the <management:jmx-default-config>
element to your configuration file. For example, the following example includes the xmlns:management
entry, the declaration of the XSD location (http://www.mulesource.org/schema/mule/management/2.1
http://www.mulesource.org/schema/mule/management/2.1/mule-management.xsd) and the
<management...> entries:
Note: you only specify the port if you don't want to use the default of 1099.
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>
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 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.
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 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:
You should see an output similar to the one below at the end:
Prerequisites
1. If you have not already done so, contact MuleSource Sales to obtain a license (you can get a trial
license for free). Mule HQ will not run without a license.
2. 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. If you already have
Mule installed, ensure that your system is still using the supported platforms (e.g., a supported
version of Java).
3. Configure your Mule instance to support Mule HQ (see Enabling Mule to Use Mule HQ).
4. 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.
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
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']:
Installation Complete:
Agent successfully installed to: d:/server/MuleHQ/agent-3.1.2-EE
--------------------------------------------------------------------------------
d:\server\MuleHQ\agent-3.1.2-EE\hq-agent.exe start
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:
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
For more detailed installation instructions, see the following Hyperic documentation:
• Windows
• Non-Windows
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.
You can set the environment variable HQ_JAVA_HOME to use a Java VM other than the one that ships
with Mule HQ.
Starting Mule HQ
To start Mule HQ, you start the database, then the server, and then the agent.
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:
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.
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
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.
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.
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
The following optional parameters constrain the subcommand to a specific Mule platform (otherwise, all
Mule platforms are affected):
Command Description
After importing a Mule instance manually or through the scripts, the Mule servers are added to Mule HQ.
After importing the Mule platform, if you want to run auto-discovery manually to discover recently added
Mule instances, do the following:
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.
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:1099/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.
• 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.
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 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.
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.
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.
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.
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
For complete information on uninstalling HQ, see Uninstalling Hyperic HQ on the Hyperic site.
PostgreSQL
Oracle
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.
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.
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.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.
Spring Extras Module Extensions for using the Spring framework with
Mule.
Acegi Module
This module provides Acegi-based security and delegates authorization to some other provider.
Security Manager
Attributes of <delegate-security-provider...>
security-property 0..*
Attributes of <http-security-filter...>
realm string no
JAAS Module
This module provides security via JAAS.
Security Manager
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...>
loginContextName string no
credentials string no
loginConfig string no
loginModule string no
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.
Table of Contents
• 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.
Name Description
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
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...>
Example Configurations
This example demonstrates how to configure a Groovy Script component with an in-line script.
<mule xmlns="http://www.mulesource.org/schema/mule/core/2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:script="http://www.mulesource.org/schema/mule/scripting/2.0"
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/scripting/2.0 http://www.mulesource.org/schema/mule/
scripting/2.0/mule-scripting.xsd
http://www.mulesource.org/schema/mule/vm/2.0 http://www.mulesource.org/schema/mule/vm/2.0/
mule-vm.xsd">
<model>
<service name="inlineScript">
<description>
This example demonstrates how to configure a Groovy Script component with an in-line script.
</description>
<inbound>
<inbound-endpoint address="vm://in1"/>
</inbound>
<script:component>
<script:script engine="groovy">
return "$payload Received"
</script:script>
</script:component>
<outbound>
<outbound-pass-through-router>
<outbound-endpoint address="vm://out1"/>
</outbound-pass-through-router>
</outbound>
</service>
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.
<service name="Callout1">
<inbound>
<inbound-endpoint ref="callout_1"/>
</inbound>
<test:component appendString=" Received by ${mule:serviceName}"/>
</service>
<service name="Callout2">
<inbound>
<inbound-endpoint ref="callout_2"/>
</inbound>
<test:component appendString=" Received by ${mule:serviceName}"/>
</service>
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...>
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...>
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.
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.
Package Description
SXC Module
The SXC module contains an outbound router and a filter that use 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 supports a limited subset of XPath expressions. For details, see the SXC documentation. To request
support for a missing XPath feature, please file a SXC JIRA.
<sxc:filtering-router>
<outbound-endpoint address="vm://log"/>
<sxc:filter pattern="//purchaseOrder[@country]"/>
<sxc:namespace prefix="test" uri="http://foo"/>
</sxc:filtering-router>
Following is another example of a filter that looks for messages where the billing address is within the
United States:
<sxc:filtering-router>
...
<sxc:filter pattern="/customer/billingaddress/country[text()='US']"/>
...
</sxc:filtering-router>
XML Module
[ XML Formats ] [ Transformers ] [ Filters ] [ Splitters ]
The XML module contains several tools to help you read, transform, and write XML.
In addition to the functionality described on this page, you can also use the SXC Module, which enables
efficient XPath XML routing.
XML Formats
Mule understands a wide variety of XML Java representations:
• org.w3c.dom.Document, org.w3c.dom.Element
• org.dom4j.Document
• javax.xml.transform.Source
• InputStream, String, byte[]
• OutputHandler
• XMLStreamReader
• org.mule.module.xml.transformer.DelayedResult
Any transformer that accepts XML as an input will also understand these types.
Transformers
There are several standard transformers that process XML inside Mule.
Transformer Description
XmlToObject <-> ObjectToXml Converts XML to a Java object and back again
using XStream.
DomToXml <-> XmlToDom Converts DOM objects to XML and back again.
Mule contains a special XML output format called DelayedResult. This format allows very efficient XML
transformations by delaying any XML serialization until an OutputStream is available.
<mxml:xslt-transformer name="transform-in"
If the result of this transformation were being sent to an HTTP client, the HTTP client would ask Mule for
an OutputHandler and pass in the OutputStream to it. Only then would Mule perform the transformation,
writing the output directly to the OutputStream.
If DelayedResult were not used, the XML result would first be written to an in-memory buffer before
being written to the OutputStream. This will cause your XML processing to be slower.
Filters
The XML module contains both a Jaxen and a JXPath filter. For general details on how to use filters, see
Using Filters.
The Jaxen and JXPath filters allow you to route messages based on XPath expressions.
Jaxen Filter
The Jaxen filter is generally faster than the JXPath filter and should be considered the first choice when
using an XPath filter.
The following configuration routes messages to the "vm://echo" endpoint when the value of "/
e:purchaseOrder/e:shipTo/@country" is "US".
<outbound>
<filtering-router>
<outbound-endpoint address="vm://echo" synchronous="true"/>
<mule-xml:jaxen-filter pattern="/e:purchaseOrder/e:shipTo/@country" expectedValue="US">
<mule-xml:namespace prefix="e" uri="http://www.example.com"/>
</mule-xml:jaxen-filter>
</filtering-router>
....
</outbound>
JXPath Filter
The JXPath filter is very similar to the Jaxen filter. It is still used for historical purposes (it existed before
the Jaxen filter).
<outbound>
<filtering-router>
<outbound-endpoint address="vm://echo" synchronous="true"/>
<mule-xml:jxpath-filter pattern="/e:purchaseOrder/e:shipTo/@country"
expectedValue="US">
<mule-xml:namespace prefix="e" uri="http://www.example.com"/>
</mule-xml:jxpath-filter>
</filtering-router>
....
</outbound>
Splitters
The XML module contains two splitters, a filter-based splitter and a round-robin splitter. For more
information on these splitters, see Using Message Routers.
DOM/XML Transformers
Mule contains several transformers that convert between a W3C DOM object and its serialized
representation. The DomToXml transformer converts DOM objects to XML, the XmlToDom transformer
converts XML strings to DOM objects, and the DomToOutputHandler transformer converts from a DOM to
an OutputHandler serialization.
These transformers support the standard transformer attributes plus the following:
Attributes of <dom-to-xml-transformer...>
Attributes of <dom-to-output-handler-transformer...>
Attributes of <xml-to-dom-transformer...>
<xm:dom-to-xml-transformer name="DomToXml"/>
<xm:xml-to-dom-transformer name="xmlToDom" returnClass="org.w3c.dom.Document" />
<xm:xml-to-output-handler-transformer name="xmlToOutputHandler" />
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
nodes).
XML-Object Transformers
[ Object to XML ] [ XML to Object ] [ Testing the Transformers ]
This pair of transformers converts XML code to serialized objects and back again. For serialization of Java
XML objects, see DomToXml Transformer.
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 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:
XmlToXMLStreamReader Transformer
The XmlToXMLStreamReader transformer converts XML representations to a StAX XMLStreamReader.
XMLStreamReaders allow XML to be parsed as a series of events that are "pulled" from the stream. It is
very efficient.
• javax.xml.transform.Source.class
• org.xml.sax.InputSource.class
• org.dom4j.Document.class
• org.w3c.dom.Document.class
• org.w3c.dom.Element.class
• org.mule.module.xml.transformer.DelayedResult.class
• String
• byte[]
• InputStream
Examples
To use the transformer, you must declare a custom transformer element:
// parse....
while (...) { xsr.next(); }
....
<xslt-transformer ...>
The XSLT transformer uses XSLT to transform the message payload. Transformation objects are pooled
for better performance. You can set transformation context properties on the transformer and can pull
these properties from the message using Expression Evaluators. This works in a very similar way to the
XQuery Transformer on MuleForge.
Attributes
transformerFactoryClass
name (no spaces) no The fully qualified
class name of the
{{javax.xml.TransformerFactory
instance to use.
If not specified,
the default
JDK factory
{{TransformerFactory.newInsta
will be used.
Child Elements
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:
<mulexml:xslt-transformer name="xslt">
<mulexml:xslt-text>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml"/>
<xsl:param name="title"/>
<xsl:param name="rating"/>
<xsl:template match="catalog">
<xsl:element name="cd-listings">
<xsl:attribute name="title">
<xsl:value-of select="$title"/>
</xsl:attribute>
<xsl:attribute name="rating">
<xsl:value-of select="$rating"/>
</xsl:attribute>
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
<xsl:template match="cd">
<xsl:element name="cd-title">
<xsl:value-of select = "title" />
</xsl:element>
</xsl:template>
</xsl:stylesheet>
This example configures a transformer using inline XSLT expressions. It also defines two context
parameters:
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:
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
<cd>
<title>Hide your heart</title>
<artist>Bonnie Tyler</artist>
<country>UK</country>
<company>CBS Records</company>
<price>9.90</price>
<year>1988</year>
</cd>
<!-- ... </catalog> -->
<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:mulexml="http://www.mulesource.org/schema/mule/xml/2.0"
xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.0"
<mulexml:xslt-transformer name="xslt">
<mulexml:xslt-text>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml"/>
<xsl:param name="title"/>
<xsl:param name="rating"/>
<xsl:template match="catalog">
<xsl:element name="cd-listings">
<xsl:attribute name="title">
<xsl:value-of select="$title"/>
</xsl:attribute>
<xsl:attribute name="rating">
<xsl:value-of select="$rating"/>
</xsl:attribute>
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
<xsl:template match="cd">
<xsl:element name="cd-title">
<xsl:value-of select = "title" />
</xsl:element>
</xsl:template>
</xsl:stylesheet>
</mulexml:xslt-text>
<model name="main">
<service name="Echo">
<inbound>
<!-- this endpoint is used by the functional test -->
<vm:inbound-endpoint path="test.in" transformer-refs="xslt" synchronous="true"/>
</inbound>
<echo-component/>
<outbound>
<outbound-pass-through-router>
<stdio:outbound-endpoint system="OUT"/>
</outbound-pass-through-router>
</outbound>
</service>
</model>
</mule>
//These are the message roperties that will get passed into the XQuery context
Map props = new HashMap();
props.put("ListTitle", "MyList");
props.put("ListRating", new Integer(6));
• XML Configuration
The default way to configure Mule is via a Spring 2.0 XML file.
• Spring Remoting
An example of accessing Mule from an external application using Spring remoting.
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.
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.
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.
package org.mule.module.spring.events;
public class TestSubscriptionEventBean extends TestMuleEventBean implements MuleSubscriptionEventListener
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 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 .
//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.
This page describes the options available for controlling how Mule creates and manages Spring
application contexts for your application.
muleContext.start();
muleContext.start();
muleContext.start();
muleContext.start();
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.
//notify kitchen
this.kitchen.submitOrder(order);
}
<beans>
<bean id="restaurantWaiter" scope="prototype" class="com.foo.RestaurantWaiter">
<property name="kitchenService">
<ref local="kitchenService"/>
</property>
</bean>
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.
xmlns:spring="http://www.springframework.org/schema/beans"
...
<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>
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.
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"
For more information, see Enterprise Java Beans (EJB) integration and the jee schema reference on the
Spring site.
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.
To make a regular synchronous call to a service and receive a result, you can use the send() method:
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
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:
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();
//A person object is returned, and all type mapping is handled for you
Person person (Person)result.getPayload();
System.out.println(person.toString());
The Mule SOAP Transport supports Apache Axis and CXF. For more information about Mule Axis support,
see Axis Web Services and Mule.
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.
//Set the JMSReplyTo property, which is where the response message will be sent
props.put("JMSReplyTo", "replyTo.queue");
//This is the message sent back from the first component to process our message
System.out.println(message.getPayload());
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.
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.
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.
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().
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:
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:
StockQuote sq = (StockQuote)result.getMessage(1000).getPayload();
You can specify the wire format to use for dispatching messages by configuring one of the following:
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>
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.
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.
HTTP Connector
The Mule HTTP Transport contains most of the basic HTTP functionality that the connectors in the
RESTpack build on, including:
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 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
To download and learn about using the Restlet connector, go to the MuleForge Restlet page.
Imagine that each resource is an object. You can then perform the following operations on this object:
Operation Description
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
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.
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.
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
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.
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.
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.
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.
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.
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.
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
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
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.
Using Transformers
[ Overview ] [ Configuring Transformers ] [ Types of Transformers ] [ Chaining Transformers ] [ Standard
Transformers Reference ] [ Transformation Best Practices ]
Overview
Mule provides 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.
Following is an example of declaring the standard Append String transformer, which appends string text
to the original message payload:
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.
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"/>
...
<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="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:
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:
<outbound>
<filtering-router transformer-refs="ErrorMessageToException">
<file:outbound-endpoint path="test-data/exceptions" outputPattern="Exception-[UUID].xml" transformer-
refs=
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.
<transformer ref="ByteArrayToString"/>
<transformer ref="StringToObject"/>
<transformer ref="ObjectToInputStream"/>
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
XML
The XML transformers are in the org.mule.module.xml.transformer package. They provide the ability to
transform between different XML formats, use XSLT, and convert to POJOs from XML. For information, see
XML Module.
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
Transformer Description
Compression
The compression transformers are in the org.mule.transformer.compression package. They do not require
any special configuration.
Transformer Description
Encoding
The encoding transformers are in the org.mule.transformer.codec package. They do not require any
special configuration.
Transformer Description
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.
For example, if we were to declare the Append String transformer above as a custom transformer and use
Spring for the property, it would look like this:
For example, the Hello World example defines a custom transformer called StdinToNameString, which
removes line breaks and newlines from the string:
package org.mule.example.hello;
import org.mule.api.transformer.TransformerException;
import org.mule.transformer.AbstractTransformer;
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. In this case, you override the method transform(MuleMessage
message, String outputEncoding) and can use message.getProperty(Object key) to retrieve the
properties or message.setProperty(Object key, Object value) to set properties in the transformed
message.
Mule also provides several standard 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, and more. For a list of the default transformers in
Mule, see Using Transformers.
This page provides details on configuring the standard transformers. Note that many transports and
modules provide their own transformers as well.
Transformer
A reference to a transformer defined elsewhere.
Attributes of <transformer...>
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...>
Custom Transformer
A user-implemented transformer.
Attributes of <custom-transformer...>
spring:property 0..*
Attributes of <message-properties-transformer...>
No Action Transformer
A transformer that has no effect.
Attributes of <no-action-transformer...>
Attributes of <base64-encoder-transformer...>
Attributes of <base64-decoder-transformer...>
Attributes of <xml-entity-encoder-transformer...>
Attributes of <xml-entity-decoder-transformer...>
Attributes of <gzip-compress-transformer...>
Attributes of <gzip-uncompress-transformer...>
Attributes of <byte-array-to-hex-string-transformer...>
Attributes of <hex-string-to-byte-array-transformer...>
Attributes of <byte-array-to-object-transformer...>
Attributes of <object-to-byte-array-transformer...>
Attributes of <object-to-string-transformer...>
Attributes of <byte-array-to-serializable-transformer...>
Attributes of <serializable-to-byte-array-transformer...>
Attributes of <byte-array-to-string-transformer...>
Attributes of <string-to-byte-array-transformer...>
Encrypt Transformer
A transformer that encrypts a message.
Decrypt Transformer
A transformer that decrypts a message.
Attributes of <decrypt-transformer...>
Expression Transformer
A transformer that evaluates one or more expressions on the current message. 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...>
Attributes of <xml-prettyprinter-transformer...>
expandEmptyElements
boolean no Whether to
expand empty
elements from
<tagName> to
<tagName></
tagName>.
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.
Proxying Web Services - Describes how to use Mule as a web service gateway/proxy in various scenarios.
Supported Web Service Standards - Web service standards supported by Mule and CXF.
Web Service Wrapper - Describes how to use the WebServiceWrapperComponent class to send the result
of a web service call to another endpoint.
RESTpack - Provides support for building RESTful services inside Mule. You can also use the REST service
wrapper (a specialized Mule service component) in the HTTP transport to proxy REST-style requests to
external REST/HTTP services. This wrapper component acts as a REST client and is appropriate if you do
not have strict REST requirements.
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.
• 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.
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.
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.
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.
Client Example
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.
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>
Notice the URL for the MuleClient call contains the name of the service endpoint, not the physical location
of the resource.
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.
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:
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.
<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¶m=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>
<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>
Note that you set the host, port, and path on the connector, not the endpoint, using the servletUrl
property.
//Client
//Server
axis:xmpp://mule1:mule@jabber.org.au/axis
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.
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...>
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.
bean-type 0..*
supported-scheme 0..*
Inbound Endpoint
Attributes of <inbound-endpoint...>
clientConfig string no
soapAction string no
SOAPAction string no
serviceNamespace string no
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>
If you use a URI-style endpoint and you include the user name and password, 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...>
clientConfig string no
soapAction string no
SOAPAction string no
serviceNamespace string no
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...>
<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.
To invoke the Echo service using the Mule Client, use the following code:
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.
//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:
• 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
• 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.
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.
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/
http://localhost:81/Version?method=getVersion
http://localhost:81/Version?wsdl
For more information about customizing Axis behavior, naming parameters, message style options, and
more, see Configuring Axis.
Configuring Axis
Table of Contents
• 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
<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:inbound-endpoint address="http://localhost:38009/mule/services"
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.
<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.
Any other properties on the event or the endpoint can be referenced by name in the soapAction
expression.
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>
qname{[MULE:prefix]:[MULE:localname]:[MULE:namespace]}
The qname syntax can be used with <soap-parameter> elements as well. For example:
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.
Note that you can use the qname notation for setting method and parameter names using the Mule client.
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.
Optionally, you can control the values used in Axis WSDL generation by setting WSDL-specific Axis
options. The options you can set are:
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.
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>
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.
This gets called when the service is initialized and allows you to customize the service configuration from
your Mule component.
Mule can act as a web service gateway/proxy. Gateways can perform several useful functions:
• Protocol bridging
• WSProxyService - allows you to service WSDLs locally while proxying remote web services
• CXF proxy services - perform WS-Security or WS-Policy actions, route based on information such as
the operation or SOAP Action, and easily work with just the payload by taking advantage of CXF's
web service capabilities
Protocol Bridging
The simplest type of web service proxy just involves forwarding a request from one endpoint to another
via service bridging. Following is a simple example that forwards a request from one HTTP endpoint to
another:
<service name="HttpWebServiceBridge">
<inbound>
<inbound-endpoint address="http://localhost:8080/my/service">
</inbound>
<outbound>
<outbound-pass-through-router>
<outbound-endpoint address="http://acme.come/remote/web/service"/>
</outbound-pass-through-router>
</outbound>
</service>
This type of bridge can be combined with filters for easy message routing. For fast XPath routing of
messages, you can use the SXC Module.
WSProxyService
The WSProxyService allows you to serve WSDLs locally while proxying remote web services. This is handy
when you have an alternate WSDL you want to service, or if you don't want WSDL requests to be routed
with all the other SOAP message requests. Any request that comes in with a "?wsdl" attached to the HTTP
URL will be redirected, and the specified WSDL will be served instead.
To configure this for your service, you must first define a WSProxyService bean with your WSDL:
<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<service name="HttpWebServiceBridge">
<inbound>
<inbound-endpoint address="http://localhost:8080/my/service">
</inbound>
<component>
<spring-object bean="WSProxyService" />
</component>
<outbound>
<outbound-pass-through-router>
<outbound-endpoint address="http://acme.come/remote/web/service"/>
</outbound-pass-through-router>
</outbound>
</service>
While many times you can proxy web services without using CXF (see above), there are several cases
where you might want to use CXF proxies:
Server-side Proxying
To proxy a web service so you can work with the raw XML, you can create a simple inbound endpoint:
This will make the SOAP body available in the Mule message payload as an XMLStreamReader.
Similarly, you can create an outbound endpoint to send raw XML payloads:
<cxf:outbound-endpoint address="http://localhost:63081/services/Echo"
proxy="true"/>
<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">
<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>
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.
Another alternative would be to use HTTPS where certificates are used for authentication.
For more information see Configuring Security and Using HTTPS with CXF.
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-Security. For details, see Enabling
WS-Security.
There are three methods for passing authentication information to a web service configured on Mule:
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
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.
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.
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:
The URL must be set on the message with the property name "ws.service.url".
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:
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.
Configuring Components
[ Simple Components ] [ Java Components ] [ Other Components ] [ Customizing Behavior with
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.
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"/>
Alternatively, you can explicitly specify object factories, such as the SingletonObjectFactory that
creates a single instance of the object:
<component>
<singleton-object class="org.my.ServiceComponentImpl"/>
</component>
The explicit syntax is required instead of the shortcut <component class> syntax if you add interceptors
to the component. 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
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:
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"/>
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 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.
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/>
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>.
Example:
<component class="org.my.PrototypeObjectWithMyLifecycle">
<custom-lifecycle-adapter-factory class="org.my.MyLifecycleMuleAdapterFactory"/>
</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.
Binding can be used on Java components and script components. For more information see Component
Bindings.
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.
Using Interceptors
[ Interceptor Types ] [ Interceptor Event Flow ] [ Writing Interceptors ] [ Configuring Interceptors ] [
Interceptor Configuration Reference ]
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.
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:
Configuring Interceptors
Interceptors can be configured on your components as follows:
<service name="MyService">
<component>
<custom-interceptor class="org.my.CustomInterceptor"/>
<logging-interceptor/>
<interceptor-stack ref="testInterceptorStack"/>
<timer-interceptor/>
<prototype-object class="org.my.ComponentImpl"/>
</component>
</service>
When you configure interceptors, you must specify the object factory explicitly (in this
example, <prototype-object>) instead of using the <component class> shortcut.
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
configuration file (above the <model> element):
<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.
<timer-interceptor ...>
The timer interceptor (ported from 1.x).
Attributes
Child Elements
<logging-interceptor ...>
The logging interceptor (ported from 1.x).
Attributes
Child Elements
<custom-interceptor ...>
A user-implemented interceptor.
Attributes
Child Elements
spring:property 0..*
Attributes
Child Elements
<interceptor-stack ...>
A reference to a stack of intereceptors defined globally.
Attributes
Child Elements
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>
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.
<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>
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.
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>
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.
There are several standard components you can use, such as <log-component>, which logs component
invocations, outputting the received message as a string, and <echo-component>, which extends the log
component to log and echo the incoming message. Typically, you will create your own component as a
plain old Java object (POJO) and configure it using the <component> element.
For more information about 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.
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>
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"/>
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.
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.
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 defaultSynchronousEventTimeout attribute
that has been configured for the Mule instance. (For more information, see Global Settings Configuration
Reference.) 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.
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.
The following example demonstrates reading a file and send its contents onto a JMS topic.
<service name="FileToJmsBridge">
<inbound>
<file:inbound-endpoint path="/data/in">
<file:filename-wildcard-filter pattern="*.txt"/>
</inbound-endpoint>
</inbound>
<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.
The messaging style is configured on endpoints, allowing multiple styles to be used with the same
service. For more information, see Mule Messaging Styles.
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
• 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
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
Pattern Description
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.
Example Configuration
<description>
Receives a message from another party. No result is expected and any result returned from the service will
be
ignored.
</description>
<model>
<service name="In-Only-Service">
<inbound>
<vm:inbound-endpoint ref="inboundEndpoint"/>
</inbound>
<script:component>
<script:script engine="groovy">
import org.mule.tck.functional.FunctionalTestNotification
muleContext.fireNotification(new FunctionalTestNotification(
src, FunctionalTestNotification.EVENT_RECEIVED));
</script:script>
</script:component>
</service>
Example Code
The following example shows how to test the above configuration using a FunctionalTestCase.
In-Out
Example Configuration
<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.
</description>
<model>
<service name="In-Out-Service">
<inbound>
<http:inbound-endpoint ref="inboundEndpoint"/>
</inbound>
<script:component>
<script:script engine="groovy">
if (message.getProperty("foo"))
return "foo header received"
else
return "foo header not received"
</script:script>
</script:component>
</service>
</model>
Example Code
The following example shows how to test the above configuration using a FunctionalTestCase.
In-Out (async)
Example Configuration
<description>
<jms:activemq-connector name="jmsConnector"/>
<model>
<service name="In-Out-Async-Service">
<inbound>
<inbound-endpoint ref="inboundEndpoint"/>
</inbound>
<script:component>
<script:script engine="groovy">
message.setProperty("foo", "bar");
return "got it!"
</script:script>
</script:component>
<!-- Mule will now read the ReplyTo header on the message and send the response there. -->
</service>
</model>
Example Code
The following example shows how to test the above configuration using a FunctionalTestCase.
assertNotNull(result.getProperty("foo"));
assertEquals("bar", result.getProperty("foo"));
}
}
Example Configuration
<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.
</description>
<model>
<service name="In-Optional-Out-Service">
<inbound>
<inbound-endpoint ref="inboundEndpoint"/>
</inbound>
<script:component>
<script:script engine="groovy">
if (message.getProperty("foo"))
return "foo header received"
else
return null
</script:script>
Example Code
The following example shows how to test the above configuration using a FunctionalTestCase.
In-Only, Out-Only
Example Configuration
<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.
MEP TODO: If a message does not originate from the service an exception should be thrown.
</description>
<model>
<service name="In-Only_Out-Only-Service">
<inbound>
<vm:inbound-endpoint ref="inboundEndpoint"/>
</inbound>
<script:component>
<script:script engine="groovy">
if (message.getProperty("foo")!=null)
return "foo header received"
else
return "foo header not received"
</script:script>
</script:component>
<outbound>
<filtering-router>
<vm:outbound-endpoint ref="receivedEndpoint"/>
<wildcard-filter pattern="* header received"/>
</filtering-router>
<filtering-router>
<vm:outbound-endpoint ref="notReceivedEndpoint"/>
<wildcard-filter pattern="* header not received"/>
</filtering-router>
</outbound>
</service>
</model>
Example Code
The following example shows how to test the above configuration using a FunctionalTestCase.
}
}
In-Only, Optional-Out
Example Configuration
<description>
Receives a message from another party but will not return a result. The service component must always
return a
result.
</description>
<model>
<service name="In-Only_Optional-Out--Service">
<inbound>
<vm:inbound-endpoint ref="inboundEndpoint"/>
</inbound>
<script:component>
<script:script engine="groovy">
if (message.getProperty("foo"))
return "foo header received"
else
return null
</script:script>
</script:component>
<outbound>
<filtering-router>
<vm:outbound-endpoint ref="receivedEndpoint"/>
<wildcard-filter pattern="* header received"/>
</filtering-router>
<filtering-router>
<vm:outbound-endpoint ref="notReceivedEndpoint"/>
<wildcard-filter pattern="* header not received"/>
</filtering-router>
</outbound>
</service>
</model>
Example Code
The following example shows how to test the above configuration using a FunctionalTestCase.
In-Out, Out-Only
Example Configuration
<model>
<service name="In-Out_Out-Only-Service">
<inbound>
<vm:inbound-endpoint ref="inboundEndpoint"/>
</inbound>
<script:component>
<script:script engine="groovy">
if (message.getProperty("foo")!=null)
return "foo header received"
else
return "foo header not received"
</script:script>
</script:component>
<outbound>
<filtering-router>
<vm:outbound-endpoint ref="receivedEndpoint"/>
<wildcard-filter pattern="* header received"/>
</filtering-router>
<filtering-router>
<vm:outbound-endpoint ref="notReceivedEndpoint"/>
<wildcard-filter pattern="* header not received"/>
</filtering-router>
</outbound>
</service>
</model>
Example Code
The following example shows how to test the above configuration using a FunctionalTestCase.
}
}
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.
</description>
<jms:activemq-connector name="amq"/>
<model>
<service name="In-Optional-Out_Out-Optional-In-Service">
<inbound>
<vm:inbound-endpoint ref="inboundEndpoint"/>
</inbound>
<script:component>
<script:script engine="groovy">
if (message.getProperty("foo") != null)
{
message.setProperty("bar", "baz")
return message
}
else
return message
</script:script>
</script:component>
<outbound>
<outbound-pass-through-router>
<outbound-endpoint ref="ExternalEndpoint"/>
<!-- Mule will automatically listen n this destination when Remote sync is set. If this is not se
a temprary destination is set up -->
<!--<reply-to address="jms://reply"/>-->
</outbound-pass-through-router>
</outbound>
</service>
<service name="Mock-External-App">
<inbound>
<inbound-endpoint ref="ExternalEndpoint"/>
</inbound>
<script:component>
<script:script engine="groovy">
message.setProperty("externalApp", "Received")
if (message.getProperty("bar") != null)
return "bar header received"
else
return null
</script:script>
</script:component>
</service>
</model>
The following example shows how to test the above configuration using a FunctionalTestCase.
In-Out, Out-In
Example Configuration
<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.
</description>
<jms:activemq-connector name="amq"/>
<model>
<service name="In-Out_Out-In-Service">
<inbound>
<vm:inbound-endpoint ref="inboundEndpoint"/>
</inbound>
<script:component>
<script:script engine="groovy">
message.setProperty("bar", "baz")
return message
</script:script>
</script:component>
<outbound>
<outbound-pass-through-router>
<outbound-endpoint ref="ExternalEndpoint"/>
<!-- Mule will automatically listen n this destination when Remote sync is set. If this is not se
a temprary destination is set up -->
<!--<reply-to address="jms://reply"/>-->
</outbound-pass-through-router>
</outbound>
</service>
<service name="Mock-External-App">
<inbound>
<inbound-endpoint ref="ExternalEndpoint"/>
</inbound>
<script:component>
Example Code
The following example shows how to test the above configuration using a FunctionalTestCase.
In-Optional-Out, Out-Only
Example Configuration
<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.
</description>
<model>
<service name="In-Optional-Out_Out-Only-Service">
<inbound>
<vm:inbound-endpoint ref="inboundEndpoint"/>
</inbound>
<script:component>
<script:script engine="groovy">
if (message.getProperty("foo") != null)
return "foo header received"
else
return null
</script:script>
</script:component>
<outbound>
<outbound-pass-through-router>
<outbound-endpoint ref="receivedEndpoint"/>
</outbound-pass-through-router>
</outbound>
</service>
</model>
Example Code
The following example shows how to test the above configuration using a FunctionalTestCase.
Advanced Patterns
In-Optional-Out, Out-Only (Async Reply Router)
Example Configuration
<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
In-Out, Out-Only (async) should be used and a response always returned, even if it is an empty or
acknowledgement message.
Note: this fails with ActiveMQ because of an outstanding issue on the part of ActiveMQ for handling
temporary
destinations.
</description>
<model>
<service name="In-Out_Out-Only-Async-Service">
<inbound>
<inbound-endpoint ref="inboundEndpoint"/>
</inbound>
<script:component>
<script:script engine="groovy">
if (message.getProperty("foo") != null)
<outbound>
<filtering-router>
<outbound-endpoint ref="externalEndpoint"/>
<reply-to ref="replyEndpoint"/>
</filtering-router>
</outbound>
</service>
<service name="ExternalApp">
<inbound>
<inbound-endpoint ref="externalEndpoint"/>
</inbound>
<test:component>
<test:return-data>got it!</test:return-data>
</test:component>
</service>
</model>
Example Code
The following example shows how to test the above configuration using a FunctionalTestCase.
assertNotNull(result.getProperty("foo"));
assertEquals("bar", result.getProperty("foo"));
}
}
Example Configuration
<jms:activemq-connector name="jmsConnector"/>
<model>
<service name="In-Out_Out-Only-Async-Service">
<inbound>
<inbound-endpoint ref="inboundEndpoint"/>
</inbound>
<script:component>
<script:script engine="groovy">
message.setProperty("foo", "bar")
return message
</script:script>
</script:component>
<outbound>
<filtering-router>
<outbound-endpoint ref="externalEndpoint"/>
<reply-to ref="replyEndpoint"/>
</filtering-router>
</outbound>
</service>
<service name="ExternalApp">
<inbound>
<inbound-endpoint ref="externalEndpoint"/>
</inbound>
<test:component>
<test:return-data>got it!</test:return-data>
</test:component>
</service>
</model>
Example Code
The following example shows how to test the above configuration using a FunctionalTestCase.
assertNotNull(result.getProperty("foo"));
assertEquals("bar", result.getProperty("foo"));
}
}
TODO
Example Configuration
<description>
Receives a message from another party but will not return a result. The service component will call out to
another
service before sending the result out on the the outbound router. Bindings provide a way to orchestrate flows
between services.
<model>
<service name="In-Only_In-Out_Out-Only-Service">
<inbound>
<vm:inbound-endpoint ref="inboundEndpoint"/>
</inbound>
<script:component>
<script:script engine="groovy">
return "Total: " + AdditionService.add(payload)
</script:script>
<script:java-interface-binding interface="org.mule.tck.services.AdditionService" method="add">
<outbound-endpoint ref="additionEndpoint"/>
</script:java-interface-binding>
</script:component>
<outbound>
<filtering-router>
<vm:outbound-endpoint ref="receivedEndpoint"/>
</filtering-router>
</outbound>
</service>
<service name="Addition-Service">
<inbound>
<vm:inbound-endpoint ref="additionEndpoint"/>
</inbound>
<component class="org.mule.tck.services.SimpleMathsComponent"/>
</service>
</model>
Example Code
The following example shows how to test the above configuration using a FunctionalTestCase.
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:
For example, depending on the transport being used developers could define endpoints such as:
The MuleExchange object here provides an interface for all messages generated from the invocation.
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
Example Configuration
<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"
xmlns:spring="http://www.springframework.org/schema/beans"
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/test/2.0 http://www.mulesource.org/schema/mule/test/2.0/
mule-test.xsd
http://www.mulesource.org/schema/mule/jms/2.0 http://www.mulesource.org/schema/mule/jms/2.0/
mule-jms.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-2.5.xsd">
<model name="Asynchronous_Message_Pattern">
<service name="AsynchronousService">
<inbound>
<jms:inbound-endpoint queue="test.in" synchronous="false"/>
</inbound>
<test:component/>
</service>
</model>
</mule>
Request Response
Example Configuration
<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:http="http://www.mulesource.org/schema/mule/http/2.0"
xmlns:test="http://www.mulesource.org/schema/mule/test/2.0"
xmlns:spring="http://www.springframework.org/schema/beans"
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/test/2.0 http://www.mulesource.org/schema/mule/test/2.0/
mule-test.xsd
http://www.mulesource.org/schema/mule/http/2.0 http://www.mulesource.org/schema/mule/http/2.0/
mule-http.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-2.5.xsd">
<model name="Request-Response_Message_Pattern">
<service name="SynchronousService">
<inbound>
<http:inbound-endpoint host="localhost" port="8080" path="/mule/services" synchronous="true"/
>
</inbound>
<test:component/>
</service>
</model>
</mule>
Example Configuration
<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"
xmlns:spring="http://www.springframework.org/schema/beans"
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/test/2.0 http://www.mulesource.org/schema/mule/test/2.0/
mule-test.xsd
http://www.mulesource.org/schema/mule/jms/2.0 http://www.mulesource.org/schema/mule/jms/2.0/
mule-jms.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-2.5.xsd">
<test:component/>
<outbound>
<outbound-pass-through-router>
<jms:outbound-endpoint queue="test.out"/>
</outbound-pass-through-router>
</outbound>
</service>
</model>
</mule>
Remote Synchronous
Example Configuration
<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"
xmlns:spring="http://www.springframework.org/schema/beans"
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/test/2.0 http://www.mulesource.org/schema/mule/test/2.0/
mule-test.xsd
http://www.mulesource.org/schema/mule/jms/2.0 http://www.mulesource.org/schema/mule/jms/2.0/
mule-jms.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-2.5.xsd">
<model name="Remote_Synchronous_Message_Pattern">
<service name="RemoteSynchronousService">
<inbound>
<jms:inbound-endpoint queue="test.in" synchronous="true"/>
</inbound>
<test:component/>
<outbound>
<outbound-pass-through-router>
<jms:outbound-endpoint queue="another.service" remoteSync="true"
remoteSyncTimeout="5000"/>
</outbound-pass-through-router>
</outbound>
</service>
<service name="AnotherService">
<inbound>
<jms:inbound-endpoint queue="another.service" synchronous="true"/>
</inbound>
<test:component/>
</service>
</model>
</mule>
Example Configuration
<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:http="http://www.mulesource.org/schema/mule/http/2.0"
xmlns:jms="http://www.mulesource.org/schema/mule/jms/2.0"
xmlns:test="http://www.mulesource.org/schema/mule/test/2.0"
xmlns:scripting="http://www.mulesource.org/schema/mule/scripting/2.0"
xmlns:spring="http://www.springframework.org/schema/beans"
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/test/2.0 http://www.mulesource.org/schema/mule/test/2.0/
mule-test.xsd
http://www.mulesource.org/schema/mule/http/2.0 http://www.mulesource.org/schema/mule/http/2.0/
mule-http.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/scripting/2.0 http://www.mulesource.org/schema/mule/
scripting/2.0/mule-scripting.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-2.5.xsd">
<model name="Async_Request-Response_Message_Pattern">
<service name="AsyncRequestResponseService">
<inbound>
<http:inbound-endpoint host="localhost" port="8080" path="/mule/services" synchronous="true"/
>
</inbound>
<test:component/>
<async-reply timeout="5000">
<collection-async-reply-router/>
<jms:inbound-endpoint queue="reply.queue"/>
<outbound>
<multicasting-router>
<reply-to address="jms://reply.queue"/>
<jms:outbound-endpoint queue="service1" synchronous="false"/>
<jms:outbound-endpoint queue="service2" synchronous="false"/>
</multicasting-router>
</outbound>
</service>
</model>
</mule>
Message routers are used to control how messages are sent and received by components in the system.
Mule defines inbound routers that apply to messages as they are received, and outbound routers that are
invoked when a message 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
Custom
No Router
If no router is defined on the inbound, all messages 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.
<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.
<inbound>
<idempotent-receiver-router idExpression="#[message:id]-#[header:foo]">
<simple-text-file-store directory="./idempotent"/>
</idempotent-receiver-router>
</inbound>
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.
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.
<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 aggregator is based on the Selective Consumer, so you can also apply filters to the messages.
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.
<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.
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.
<inbound>
<custom-correlation-aggregator-router class="org.mule.CustomAgregator">
<payload-type-filter expectedType="org.foo.some.Object"/>
</custom-correlation-aggregator-router>
</inbound>
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 messages.
This router is based on the Selective Consumer, which means that filters can be applied to the incoming
messages.
<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 message 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.
<service name="FileReader">
<inbound>
<file:inbound-endpoint path="/temp/myfiles/in"/>
<forwarding-router/>
</inbound>
<echo-component/>
<outbound>
<tcp:outbound-endpoint host="192.168.0.6" port="12345">
<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 message'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 router extends the Selective Consumer, so you can configure filters on this router.
Wiretap 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.
<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>
Pass-through Router
This router always matches and simply sends or dispatches message via the one endpoint it has
configured.
2.0:
<outbound>
<outbound-pass-through-router>
<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>
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.
<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>
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.
<outbound>
<static-recipient-list-router>
<payload-type-filter expectedType="javax.jms.Message"/>
<recipients>
<spring:value>jms://orders.queue</spring:value>
<spring:value>jms://tracking.queue</spring:value>
</recipients>
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.
<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.
<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>
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
messages 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.
<outbound>
<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.
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
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.
<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>
The round robin message splitter will split a DOM4J document into nodes based on the "splitExpression"
property. It will then send these document fragments to the list of endpoints specified in a round
robbin fashion. Optionally, you can specify a namespaces property map that contain prefix/namespace
mappings.
For instance, the following fragment will route the "/a:orders/a:order" nodes inside the document to the
robin1 and robin2 endpoints.
<outbound>
<mxml:round-robin-splitter splitExpression="/a:orders/a:order" deterministic="false">
<outbound-endpoint ref="robin1"/>
<outbound-endpoint ref="robin2"/>
<mxml:namespace prefix="a" uri="http://acme.com"/>
</mxml:round-robin-splitter>
</outbound>
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.
<outbound>
<mxml:round-robin-splitter splitExpression="/a:orders/a:order" deterministic="false"
externalSchemaLocation="mySchema.xsd" validateSchema="true">
<outbound-endpoint ref="robin1"/>
<outbound-endpoint ref="robin2"/>
<mxml:namespace prefix="a" uri="http://acme.com"/>
</mxml:round-robin-splitter>
</outbound>
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
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.
<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
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.
<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" />
The endpoint template 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, such as:
axis:http://localhost:8082/MyService?method=[SOAP_METHOD]
<outbound>
<endpoint-template-router address="foobar://server:1234/path/path/path?
param1=[header1]¶m2=[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.
You can configure custom outbound routers by specifying the custom router class on the <custom-
outbound-router> element and by using Spring properties.
<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>
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.
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/>
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/>
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>
<inbound-endpoint address="vm://in2" connector-ref="vmQueue">
<string-to-byte-array-transformer/>
</inbound-endpoint>
<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>
Following are descriptions of the different catch-all strategies you can use.
Forwarding
This catch-all strategy is used to forward the message 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/>
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.
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.
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.
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.
Now, you simply configure your component to bind the sayHello method to the endpoint that will invoke
another service.
<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.
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.
<service name="ScriptService">
<inbound>
<vm:inbound-endpoint ref="inboundEndpoint"/>
</inbound>
<script:component>
<script:script engine="groovy">
return "Total: " + AdditionService.add(1,2)
</script:script>
<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:
We refer to the binding interface using the short class name AdditionService and invoke the add
method, which will call a local addition service.
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:
<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>
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 messages or to copy messages that require additional processing to a different
component. If filters aren't used, you can make a backup copy of all messages 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 messages from the In endpoint, and the router
passes the message 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>
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¶m=bar
When this message 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,
or by specifying ?method= so that the onCall() will be called instead. For example:
<wire-tap-router>
<outbound-endpoint addres="vm://inboundEndpoint3?connector=vm2"/>
</wire-tap-router>
...
<service name="serviceComponent3">
<inbound>
<inbound-endpoint address="vm://inboundEndpoint3?connector=vm2&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 messages can either start or join a transaction
provided that the endpoint supports transactions.
• Reply-To can be used to route replies from this endpoint.
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:
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:
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.1"
xsi:schemaLocation="http://www.mulesource.org/schema/mule/jms/2.1 http://www.mulesource.org/schema/
mule/jms/2.1/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):
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:
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:
Properties Files
To load properties from a file, you can use the standard Spring element
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"
smtp.username=JSmith
smtp.password=ChangeMe
The placeholderPrefix value can be anything other than "#[", which is what Mule uses to parse its
message properties in expressions. 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.
<context:property-placeholder location="email.properties,http.properties,system.properties"
placeholderPrefix="${"/>
Message Properties
You can use placeholders to perform logic on message properties such as the header. For example,
if you wanted to evaluate the content-type portion of the message header, you would specify it as
#[header:Content-Type]. Typically, you message property placeholders with expressions. For more
information, see Using Expressions.
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:
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();
There is no standard way in Java to access environment variables. However, this link has some options
you might find useful.
<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.
<jms:connector name="FioranoJMSConnector"
connectionFactoryJndiName="PrimaryCF"
jndiInitialFactory="fiorano.jms.runtime.naming.FioranoInitialContextFactory"
specification="1.1"
jndiProviderUrl="http://localhost:1856"
username="anonymous"
password="anonymous">
• 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:
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.
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.
<jms:connector name="jmsConnector"
connectionFactoryJndiName="ConnectionFactory"
jndiDestinations="true"
forceJndiDestinations="true"
jndiInitialFactory="com.swiftmq.jndi.InitialContextFactoryImpl"
jndiProviderUrl="smqp://localhost:4001/timeout=10000"
The Loan Broker ESB example uses the following JMS queues (Mule syntax):
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:
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.
Jaas Security
[ Using the Jaas Configuration File ] [ Passing the Credentials Directly to the Provider ] [ Passing a Non-
default Login Module ] [ Configuring the Security Filter on an Endpoint ]
The JaasSimpleAuthenticationProvider is a security provider that provides a way to interact with the Jaas
Authentication Service.
The security provider for Jaas can be configured in a couple of different ways. It allows you to configure
Jaas either by passing to the provider a Jaas configuration file or by passing the required attributes
directly to the JaasSimpleAuthenticationProvider. These two configuration methods are described
below.
jaasTest{
org.mule.module.jaas.loginmodule.DefaultLoginModule required
credentials="anon:anon;Marie.Rizzo:dragon;"
};
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 login module that will be used to authenticate the user. As a login module, you can either use Mule's
DefaultLoginModule, one of the login modules 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 login module specifies that the login module must succeed for the
authentication to be considered successful. Additional flags are:
Required - The login module is required to succeed. If it succeeds or fails, authentication still continues
to proceed down the login module list.
Requisite - The login module is required to succeed. If it succeeds, authentication continues down the
login module list. If it fails, control immediately returns to the application.
Sufficient - The login module is not required to succeed. If it does succeed, control immediately returns
to the application (authentication does not proceed down the login module list). If it fails, authentication
continues down the login module list.
Optional - The login module is not required to succeed. If it succeeds or fails, authentication still
continues to proceed down the login module list.
The entry also specifies the credentials, in which we put a string of authorized 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 login module to another.
The format of the credentials string must adhere to the following format if the DefaultLoginModule is
going to be used:
<username>:<password>;
<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaas="http://www.mulesource.org/schema/mule/jaas/2.2"
...cut...
<jaas:security-manager>
<jaas:security-provider name="jaasSecurityProvider" loginContextName="jaasTest"
loginConfig="jaas.conf"/>
</jaas:security-manager>
Note that in the above, the loginContextName contains the same name of the entry as in the Jaas
configuration file. This name will be used for creating the login context as well as to find the complete
URL of the jaas.conf file.
<jaas:security-manager>
<jaas:security-provider name="jaasSecurityProvider" loginContextName="jaasTest"
credentials="anon:anon;Marie.Rizzo:dragon;"/>
</jaas:security-manager>
In the above configuration, note that we removed the property loginConfig and don't need to pass any
Jaas configuration file. Instead, we simply pass the credentials to the provider (using the same format as
specified above). Since no login module is specified, the DefaultLoginModule is used.
<jaas:security-manager>
<jaas:security-provider name="jaasSecurityProvider" loginContextName="jaasTest"
loginModule="com.sun.security.auth.module.NTLoginModule"/>
</jaas:security-manager>
In the above configuration, we have added the loginModule property, which allows you to specify the
login module you want 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.
<inbound>
<inbound-endpoint address="vm://test">
<jaas:jaas-security-filter/>
</inbound-endpoint>
JavaRebel Integration
This page is under construction. JavaRebel Integration is not yet supported for Mule 2.x.
JavaRebel is a JVM plugin that reloads Java class files on the fly so that you can recompile and see your
changes to the application without restarting or redeploying it. This page describes how to integrate
JavaRebel with Mule. It assumes you have installed Mule and have an Internet connection available.
Note that JavaRebel reloads custom class files only, such as those in the examples, and not Mule core
classes.
Setup
These instructions use the Hello Example bundled with Mule to demonstrate the setup.
Note that we reference the configuration file as a resource. It's been put on the classpath in
MULE_HOME/lib/user when you built the project.
8. Type your name when prompted and watch the standard reply.
9. Modify the org.mule.samples.hello.Greeter#greet() method with a new greeting:
10. Make/build the project, then type your name again when prompted. Notice that the greeting has
changed.
<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>
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.
Module Archetype
[ Configuring Maven ] [ Using the Archetype ] [ The Questions Explained ] [ Example Console Output ] [
Updating an Existing Module ] [ Command Line Options ]
Mule provides Maven archetypes that you can use as code templates for your Mule modules that you
want to host on MuleForge or include with the Mule distribution. These templates include a set of
implementation notes and "todo" pointers that help you get started quickly. The Mule module archetype
will help you generate a tailored boilerplate module in seconds. For more information on using Maven, see
Using Maven.
The Module archetype allows developers to create new Mule modules or upgrade existing Mule modules
adding support for schemas and registry bootstrapping. See Updating an Existing Module for more
information.
Follow the instructions below to create template files for a new Mule module, including all the necessary
Java boilerplate and detailed implementation instructions in comments.
Configuring Maven
Add the following to the file settings.xml (usually in your Maven conf or $HOME/.m2 directory) so that
Maven will allow you to execute Mule plug-ins.
<settings>
<pluginGroups>
<pluginGroup>org.mule.tools</pluginGroup>
</pluginGroups>
...
</settings>
> cd yourDir
Next, you will execute the archetype and generate the code. If this is your first time running this
command, Maven will download the archetype for you.
• artifactId: The short name for the project (such as 'myApp'). This must be a single word in lower
case with no spaces, periods, hyphens, etc.
• 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.
• archetypeArtifactId: Enter mule-module-archetype when running the module archetype.
artifactId
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.
After you have answered all the questions, the archetype creates a directory using the module name you
specified that includes a POM file for building with Maven, a Mule configuration file (src\main\resources
\mule-config.xml) that includes the namespaces for the transports and modules you specified and has
placeholder elements for creating your first service, and a package.html file under src\main\java using
the package path you specified. Lastly, it creates some template files under src\test to help you get
started creating a unit test for the module. A new MULE-README.txt file will be created in the root of your
project explaining what files were created.
Are you creating a new module (rather than updating an existing one)?
If you are creating an brand new Mule module, chose yes here. The wizard will then ask you what
resources you want to create. If you are updating an existing module, choose no, and see Updating
an Existing Module for more information. The following questions get asked if you are creating a new
module.
You should provide an accurate description of the module with any high-level details of what you can or
cannot do with it. This text will be used where a description of the module is required.
The version of Mule you want to use for your module. This will default to the archetype version passed in
on the command line.
If the transport 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.
A comma-separated list of the transports you plan to use in this module (such as HTTP and VM). This will
add the namespaces for those transports to the configuration file.
A comma-separated list of the modules you are extending with this module (such as XML and Scripting).
This will add the namespaces for those modules to the configuration file.
Will this transport have a custom schema for configuring the transport in Xml?
All new transports targeted for Mule 2.x 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.
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 expression evaluators.
Are you creating a new module (rather than updating an existing one)? [y] or [n]
[default: y]
********************************************************************************
y
[INFO] description:
********************************************************************************
[INFO] forgeProject:
********************************************************************************
[INFO] transports:
********************************************************************************
(options: axis, cxf, ejb, file, ftp, http, https, imap, imaps, jbpm, jdbc,
jetty, jetty-ssl, jms, jnp, multicast, pop3, pop3s, quartz, rmi, servlet,
smtp, smtps, servlet, ssl, tls, stdio, tcp, udp, vm, xmpp):
[default: vm]
********************************************************************************
[INFO] modules:
********************************************************************************
[INFO] hasCustomSchema:
********************************************************************************
Will this module have a custom schema for configuring the module in Xml? [y] or [n]
[default: y]
********************************************************************************
[INFO] hasBootstrap:
Will this module make objects available in the Registry as soon as it's loaded? [y] or [n]
[default: n]
********************************************************************************
For example, if your existing Module or transport is located under /projects/foo, you update the project
by running the following commands:
cd /project/foo
mvn mule-module-archetype:create -DartifactId=foo -DmuleVersion=2.1.2 -DarchetypeArtifactId=mule-
module-archetype
Notice that the artifactId must be set to the name of your project. This ensures that any new classes
will be created with the same naming scheme.
When you run this command, you will be prompted with three questions. The first question will ask you
whether this is a new project. Make sure you select 'n' so that the wizard will upgrade your existing
module or transport. It then asks you the last two questions about the custom schema and registry
bootstrap. After you answer the questions, the code will be created and a new MULE-UPDATE-README.txt
file will be created in the root of your project explaining what files were created.
-Dinteractive=false
groupId - org.mule.application.<artifactId>
DgroupId=org.mule.applicationxxx
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"/>
PGP Security
[ Requirements ] [ Configuring the PGP Filter ] [ Configuration Reference ]
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
Libraries
• Cryptix OpenPGP
• Cryptix JCE
Policy Files
If you are running JDK 1.4+ that comes with the Sun JCE by default, you must 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 Downloads section):
JDK 1.4
JDK 5
JDK 6
According to Sun, the default distribution of the JCE allows "strong, but limited strength cryptography."
This 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.
<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:pgp="http://www.mulesource.org/schema/mule/pgp/2.2"
...cut...
You must also specify a class that identifies the sender of a message. For this example, we simply fake
the sender using the FakeCredentialAccessor (available in the test classes of mule-module-pgp), which
returns a fixed user name.
In this example, we 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. The configuration looks like this:
<pgp:security-manager>
<pgp:security-provider name="pgpSecurityProvider" keyManager-ref="pgpKeyManager"/>
<pgp:keybased-encryption-strategy name="keyBasedEncryptionStrategy" keyManager-
ref="pgpKeyManager"/>
</pgp:security-manager>
<model name="test">
<service name="echo">
<inbound>
<inbound-endpoint address="file:///temp/signedAndEncryptedFiles/in">
<pgp:security-filter strategyName="keyBasedEncryptionStrategy" signRequired="true"
credentialsAccessor-ref="fakeCredentialAccessor"
keyManager-ref="pgpKeyManager"/>
</inbound-endpoint>
</inbound>
<component class="org.mule.module.pgp.EchoMsg"/>
<outbound>
<pass-through-router>
<outbound-endpoint address="file:///temp/decryptedFiles/out">
<pgp:security-filter strategyName="keyBasedEncryptionStrategy"
credentialsAccessor-ref="fakeCredentialAccessor"
keyManager-ref="pgpKeyManager"/>
</outbound-endpoint>
</pass-through-router>
</outbound>
</service>
</model>
</mule>
The property signRequired in the inbound security filter controls whether to accept unsigned messages.
Configuration Reference
Security Manager
Security Provider
Security provider for PGP-related functionality.
Attributes of <security-provider...>
Attributes of <keybased-encryption-strategy...>
Security Filter
Filters messages based on PGP encryption.
Attributes of <security-filter...>
Project 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 project archetype will help you generate a tailored boilerplate project in seconds. For more
information on using Maven, see Using Maven.
Follow the instructions below to create template files for a new project, including all the necessary Java
boilerplate and detailed implementation instructions.
Configuring Maven
Add the following to the file settings.xml (usually in your Maven conf or $HOME/.m2 directory) so that
Maven will allow you to execute Mule plug-ins.
<settings>
<pluginGroups>
<pluginGroup>org.mule.tools</pluginGroup>
</pluginGroups>
...
</settings>
> cd yourDir
Next, you will execute the archetype and generate the code. If this is your first time running this
command, Maven will download the archetype for you.
• artifactId: The short name for the project (such as 'myApp'). This must be a single word in lower
case with no spaces, periods, hyphens, etc.
• 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.
artifactId
As of Mule 2.2 the artifactId can contain characters such as underscore or hyphen.
However, the plug-in will convert the name into a usable form suitable for Java. For
example, if the argument is specified as -DartifactId=My#Awesome-Mule_Project,
the project will be created in a directory of that name, but the project name will be
MyAwesomeMuleProject and the package name will be .myawesomemuleproject
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.
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.
The version of Mule you want to use for your project. This will default to the archetype version passed in
on the command line.
This should be a Java package path for you project, such as com/mycompany/project. Note that you must
use slashes for separators, not periods.
A comma-separated list of the transports you plan to use in this project (such as HTTP and VM). This will
add the namespaces for those transports to the configuration file.
A comma-separated list of the modules you plan to use in this project (such as XML and Scripting). This
will add the namespaces for those modules to the configuration file.
[default:]
********************************************************************************
[INFO] muleVersion:
********************************************************************************
[default: 2.1.2]
********************************************************************************
[INFO] package:
********************************************************************************
What is the base Java package path for this project? (i.e. com/mycompany/project):
[INFO] transports:
********************************************************************************
(options: axis,cxf,ejb,file,ftp,http,https,imap,imaps,jbpm,jdbc,
jetty,jms,multicast,pop3,pop3s,quartz,rmi,servlet,smtp,
smtps,servlet,ssl,tls,stdio,tcp,udp,vm,xmpp):
[default: cxf,file,http,jdbc,jms,stdio,vm]
********************************************************************************
[INFO] modules:
********************************************************************************
(options: bulders,client,jaas,jbossts,management,ognl,pgp,scripting,
spring-extras,sxc,xml):
[default: client,management,scripting,sxc,xml]
********************************************************************************
-Dinteractive=false
groupId - org.mule.application.<artifactId>
DgroupId=org.mule.applicationxxx
<jms:connector name="jmsConnector"
jndiInitialFactory="com.stc.is.naming.NamingContextFactory"
jndiProviderUrl="[ServerName]:18006"
connectionFactoryJndiName="/jms/connectionfactory/queue/[LogicalHostName]_[JMS iqManager
Name]"/>
</jms:connector>
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
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>
Streaming
[ Advantages of Streaming ] [ Streaming Filters and Transformers ] [ Configuring Stream Flows ] [
Writing Streaming Components, Routers, and Filters ]
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:
<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>
Note that when you use tibjmsnaming as the protocol in your jndiProviderUrl, you can also specify
TCP or SSL with the JNDI property com.tibco.tibjms.naming.security_protocol.
For XA transactions, you must create an XA Connection Factory from the TIBCO administration-tool
(tibemsadmin) as follows:
Using Expressions
[ Using Expressions with Transformers ] [ Using Expression Filters ] [ Using Expression Routers ]
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. For more details on how to configure expressions, see
Expressions Configuration Reference.
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:
And the message being passed to you component looks like this:
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>
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>
<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:
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"/>
As usual, you can use AND, OR, and NOT filters to combine expressions.
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.
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.
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.
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>
<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.
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.
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.
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
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. For more information, see Bootstrapping the Registry.
<expression-transformer>
<return-argument evaluator="custom" customEvaluator="myEval" expression="foo"/>
</expression-transformer>
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
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:
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:
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>
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.
web.proxy.host=192.168.2.2
web.proxy.port=8081
<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.
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.
<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"/>
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:
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"
<spring:beans>
<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.