Professional Documents
Culture Documents
Key: MULEUSER
Name: Mule 1.x User Guide
Description: Mule Users Guide for the 1.x release line
Architecture Introduction
Mule Integration
• Overview
• Models • AppServers
• Endpoints ° Geronimo
• Transports ° JBoss
• Routers ° Oracle
• Filters ° JMS
• Transformers ° EJB
° JBI
• MULE:Containers
° HiveMind
Configuring Mule
° PicoContainer
° Plexus
• Mule Configuration Overview
° Spring
• Configuration Options
• JavaSpaces
• Configuring Mule Programmatically
• JSR-223 Scripting (php, groovy, javascript)
• Configuring Endpoints
• JNDI
• Transports Guide
• Quartz
• JMX Management
• Security
• Configuring Jms
° Jaas Security
• Configuring Properties
° Acegi Security
• General Transport Configuration ° PGP Security
• Object Containers
• Transaction Managers
• Configuring Service Methods ° Jotm
° Tyrex
Using Mule • Web Services
° Axis
• Profiling Mule with YourKit ° Glue
• Writing Components ° REST
The Basics
At the most basic level, Mule is a distributable object broker called the Container or Mule Model.
TM
The Container manages operational objects, or Universal Message Objects . These guys, UMOs for
short, are simple Java objects that communicate between themselves and external applications. The
communication points are called "Endpoints".
The diagram below shows a simplified breakdown of the Mule Server components.
Cannot resolve external resource into attachment.
The Mule Manager is central to a Mule server instance (also known as a Node or Mule Node). Its primary
role is to manage the various objects such as connectors, endpoints and transformers for a Mule instance.
These objects are then used to control message flow to and from your services/components and provide
services to the Model and the components it manages.
The Model
The model is the container in which your components are managed and executed. It controls message
flow to and from your components, manages threading, lifecycle and pooling. The default MuleModel
is SEDA-based meaning it uses an efficient event-based queuing model to maximize performance and
throughput.
The container provides a range of services for UMO components such as transaction management,
transformation of events, routing, event correlation, logging, auditing and management. Mule separates
object construction from management meaning that popular IoC/DI containers such as Spring,
PicoContainer or Plexus can be used to construct your UMO components.
UMO Components
TM
UMO stands for Universal Message Object ; an object that can receive and send events from anywhere.
UMO Components are your business objects. These are components that execute business logic on
an incoming event. These components are standard JavaBeans, there is no Mule-specific code in your
components. Mule handles all routing and transformation of events to and from your objects based on the
configuration of your component
Endpoints
External Applications
External applications can be anything from application servers to legacy payroll systems, to mainframe
trading applications or a client application. Basically, any application that has a way of serving or
consuming data. As Mule performs all communication via endpoints, UMO components have no notion of
what application produced the data, where the application is located nor the transport protocol used.
Mule Objects
The terminology used within Mule might be a bit confusing, but it breaks down pretty simply.
NOTE: This is a work in progress! Your feedback and improvements would be very welcome.
Please email the user mailing list with your suggestions.
Introduction
Clustering means many things to many people. As you build your application, its important to think
critically about how to best architect your application to achieve the desired availability, fault
tolerance, and performance characteristics. There is no one size fits all solution for everyone.
This document attempts to outline some of the goals and tactics for achieving high availability and fault
tolerance with your application.
Goals
Typically when we are clustering an application we're trying to achieve two things:
• High availability (HA): Making your system continually available in the event a server(s) or data-
center fails.
• Fault tolerance (FT): The ability to recover from failure of some underlying component. Typically
through transaction rollback or compensating actions.
Pros:
• Easy to do
• Well understood by developers
Cons:
Pros:
• 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. Say we have an aggregator which is
aggregating messages from two different producers. Producer #1 sends a message to the aggregator and
it is received and held 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, Producer
#2 can simply fail over to a different server.
Pros:
Cons:
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 will not work as the load
balancer will not transparently switch connections between servers. In this case the HTTP client will need
to retry.
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 which is proxying requests
between multiple servers.
NOTE: If the HTTP connection is open for the duration of this process, this will not work as the load
balancer will not transparently switch connections between servers. In this case the HTTP client will need
to retry.
Related topics
There are many other topics that are important to discuss around clustering:
Interceptors - How to intercept the inbound and outbound event flow to a component to introduce new
behaviour.
Endpoints - All you need to know about configuring Endpoints for your components.
Message Routers - A guide to configuring routing paths to and from components and external systems.
Filters - Can be used on endpoints and Routers, here is information about the filters provided by Mule and
how to write your own.
Mule interceptors are useful for attaching common behaviour to multiple UMOs. The Interceptor or
Command pattern is often referred to as practical AOP (Aspect Oriented Programming) as it allows
the developer to intercept processing on an object and potentially alter the processing and outcome.
Interceptors a very useful for attaching profiling, permission and security checks, etc, to a component in
Mule.
Interceptor Types
1. org.mule.interceptors.EnvelopeInterceptor - Envelope filter that will execute before and after the event
is processed. Good for Logging and profiling.
2. org.mule.umo.UMOInterceptor - Simply gets invoked then forwards processing to the next element. An
interceptor can stop further processing by not forwarding control to the next interceptor, for example as
permissions checker interceptor.
The following shows an example interceptor stack and the event flow.
Cannot resolve external resource into attachment.
Writing Interceptors
If you want to intercept an event flow to a component on the inbound event flow, you should implement
the org.mule.umo.UMOInterceptor interface. it has a single method -
The invocation parameter contains the current event and the UMODescriptor object of the target
component. Developers can extract the current UMOMessage from the event and manipulate it any way
they wish. The intercept method must return a UMOMessage that will be passed on to the component (or
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.
If you wish to halt the event flow you can either call setStopFurtherProcessing() from the
UMOEventContext or else throw an exception. This will cause the ExceptionStrategy on the component to
be invoked.
Configuring Interceptors
Interceptors can be configured on your components using the <interceptor> element i.e.
You can also define interceptor stacks; these are one or more interceptors that can be referenced using
a logical name. To define an interceptor stack you must first configure it in the global section of the Mule
Xml config file (above the <model> element) -
You can configure zero or more <interceptor> elements on your components and you can mix using
explicit classnames or stack names.
This component can be used to proxy REST style services as local Mule Components. The
org.mule.components.rest.RESTServiceWrapper can be configured with a service URL. A number of
properties will allow you to configure the parameters and error conditions on the service.
serviceUrl the REST service url to invoke. Yes unless the urlFromMessage
If any parameters are specified is set to true
on this url they will always be
included on the Url invoked.
The MULEINTRO:Stock Quote Example demonstrates how to configure the RESTServletWrapper. It calls
an ASPX Stock Quote service hosted by http://www.webservicex.net.
Components are used to execute custom business logic in a Mule application. They are typically written
according to application requirements. Still, Mule ships with some default components.
Simple components
Specialized components
Name Description
Example usage: Reading a file and send its contents onto a Jms Topic.
<mule-descriptor name="FileToJmsBridge"
implementation="org.mule.components.simple.BridgeComponent">
<inbound-router>
<endpoint address="file:///data/in">
<filter className="org.mule.providers.file.filters.FilenameWildcardFilter" pattern="*.txt"/>
</endpoint>
</inbound-router>
<outbound-router>
<router className="org.mule.routing.outbound.OutboundPassThroughRouter">
<endpoint address="jms://topic:receivedFiles"/>
</router>
</outbound-router>
</mule-descriptor>
Transformers are used to convert inbound data to an object type required by the UMO Component
or outbound to an object type required by the transport such as a JmsMessage. Transformers can be
configured on Endpoints that receive data to ensure that the expected object type is always received by
an UMO Component. Transformers configured on an Outbound endpoint ensure that the endpoint receives
the the correct object type before dispatching the event. Multiple transformers can be chained together
to allow for finer grained transformer implementations that are easier to reuse. To configure an Endpoint
to use more than one transformer, just specify a space separated list of transformers in the config file
or programmatically chain the transformers together using the setNextTransformer() method on the
transformer.
For example an inbound transformer may look like -
Standard Transformers
Below are a list of standard transformers for Mule. Individual transports may also have their own
transformer types and these will be documented in the Transports Guide.
Xml
XSLT
Transform Xml payloads using XSL.
JXPath
Query and extract Object graphs using XPath expressions.
Scripting
Transform objects using scripting, e.g. JavaScript or Groovy scripts.
Encryption
Compression
These transformers can be found in the org.mule.transformers.compression package and do not require
any special configuration.
Encoding
These transformers can be found in the org.mule.transformers.codec package and do not require any
special configuration.
Object
These transformers can be found in the org.mule.transformers.simple package and do not require any
special configuration.
You may be wondering, how should I handle a given situation with regards to transformation and Mule.
Here is a quick guide which will try to address some best practices with Mule around transformations:
Transformations and Mule Best Practices
As components in Mule can be plain old objects it's not always clear to the newcomer how Mule will
interact with their component.
Entry Points
The entry point is the method executed by Mule when an event is received for the component. When
an event is received for your component Mule dynamically chooses the method to invoke based on the
payload type of the event. This means potentially your component may have many entry points. The
payload type of the event is almost always determined by the inbound transformer for the provider that
recieved the event for your component, but some providers such as the soap provider manage type
mappings themselves so there are no need for transformers.
If your component implements the Mule default event interface org.mule.umo.lifecycle.Callable it will
override any dynamic resolution and call the interface method implementation.
If you need to call a method on the component having no arguments, see Calling no-arguments Methods
(since Mule 1.4.2).
Event Flow
Mule has some default behavior rules about managing event flow to and from your component.
Customizing Behavior
While the default event flow behavior is sufficient, in most cases you may at some point want to
customize it. To do this, you need to get a reference to the org.mule.umo.UMOEventContext. This can be
done in two ways -
You can also obtain the EventContext from the static RequestContext -
From the EventContext you can send and receive events synchronously and asynchronously, manage
transactions and override the default event flow behavior. For example -
//or to receive
UMOMessage quote = context.receive(endpoint, 5000);
1. If your service method is not void you can return null. This tells Mule there is no further event
information to process.
2. If your service method is void, Mule will use the inbound event payload as the outbound event
payload. If you don't want this to happen, you need to make the following call-
context.setStopFurtherProcessing(true);
Component Lifecycle
Quite often there's a need to call a method having no arguments as part of the flow ( MULE-896). One
can't do it out of the box with Mule's entry point resolvers. Before Mule 1.4.2 the only workaround was
to implement a thin wrapper using a Callable interface and delegate an invocation to the method. Many
felt this was an intrusion in their ideal POJO worlds, and Mule 1.4.2 now features a facility to go about the
problem declaratively.
<mule-descriptor name="WrapperUMO"
implementation="org.mule.components.simple.NoArgsCallWrapper">
<inbound-router>
<endpoint address="vm://invoke"/>
</inbound-router>
<properties>
<property name="delegateClass" value="org.mule.tck.testmodels.fruit.Apple"/>
<property name="delegateMethod" value="toString"/>
</properties>
</mule-descriptor>
In the config above, the result of the Apple.toString() will be returned to the caller.
<mule-descriptor name="FruitWasher"
implementation="org.mule.components.simple.NoArgsCallWrapper">
<inbound-router>
<endpoint address="vm://invoke"/>
</inbound-router>
<outbound-router>
<router className="org.mule.routing.outbound.OutboundPassThroughRouter">
<endpoint address="vm://out"/>
</router>
</outbound-router>
<properties>
<container-property name="delegateInstance" reference="washerTarget" required="true"
container="spring"/>
<property name="delegateMethod" value="wash"/>
</properties>
</mule-descriptor>
In the config above, a delegate is instead injected from the Spring container, and the result of the wash()
method call on it routed to the vm://out endpoint.
Configuration Variables
The configuration object Mule uses is org.mule.config.MuleConfiguration and it defines the following
properties:
Pooling Profiles
A pooling profile is used to configure the pooling behaviour of UMO components. each descriptor
can set it's own pooling profile or a default one can be set on the mule-configuration. The
org.mule.config.PoolingProfile contains all the necessary values to create a pool of UMOComponent
proxies.
• WHEN_EXHAUSTED_FAIL
(FAIL) : will throw a
NoSuchElementException
• WHEN_EXHAUSTED_WAIT
(BLOCK) : will block (invoke
Object.wait(long) until
a new or idle object is
available.
• WHEN_EXHAUSTED_GROW
(GROW): will create a
new Mule and return
it(essentially making
maxActive meaningless.)
If a positive maxWait value
is supplied, it will block
for at most that many
milliseconds, after which a
NoSuchElementException
will be thrown. If
maxThreadWait is non-
positive, it will block
indefinitely.
• WHEN_EXHAUSTED_RUN
(RUN) : The thread making
the execute request runs
the task itself. This policy
helps guard against lockup.
• WHEN_EXHAUSTED_WAIT
(WAIT) : Wait until a thread
becomes available. This
policy should, in general,
not be used if the minimum
number of of threads
is zero, in which case a
thread may never become
available.
• WHEN_EXHAUSTED_ABORT
(ABORT) : Throw a
RuntimeException
Queue Profiles
A Queue Profile is used to describe the the properties of an internal Mule queue. Internal queues are used
to queue events for each component managed by Mule.
Comments
The Queue Profiles section has to be updated. The allowed properties, according to the API and DTD, are:
• maxOutstandingMessage
• persistent
yc
Endpoints in Mule are used to communicate with other applications or mule instances. They are like
message gateways through which events can be sent and received for more information see Mule
Endpoints.
Configuration
Endpoints can be configured on Exception Strategies, routers and catch-all strategies. The <endpoint>
elements represents the org.mule.umo.endpoint.UMOEndpoint class.
Lets start with a component example. the following configures one inbound and one outbound endpoint
The most simple endpoint configuration just needs to provide an address. For more information about
configuring components go here.
Filters
A filter can be configured on an endpoint to filter inbound messages. The filter can be transport
specific such as a Jms selector or file filter or can be a general filter such as using JXPath to filter on
email messages. Filtering is not supported by all transports and setting a filter on an endpoint using
some transports will result in an UnsupportedOperationException. See the Transports Guide for more
information about filtering on a particular transport.
For more information about Filters see Filters.
Transactions
Transaction element can be configured between two endpoints where the event processing between each
is synchronous, this is controlled by setting the synchronous property on the connectors for each of the
endpoints. For more information about configuring transactions go here.
Properties
Properties on endpoints can be used to customise behaviour for a particular endpoint instance. Any
properties set on the endpoint can be used to overload properties on the connector. An example of this
would be having an Smtp outbound endpoint and setting the fromAddress. See Configuring Properties for
more information about how various property types can be used.
Global Endpoints
Global endpoints are configured Endpoints that are registered with the MuleManager. This means any
object in Mule can make use of these endpoints. When you reference a global endpoint Mule actually
returns a clone of the Endpoint. This allows client code to change any attributes on the endpoint without
affecting other objects in the system that also use the endpoint.
To configure a global endpoint in the Mule Xml configuration use the following -
<mule-configuration>
<global-endpoints>
<endpoint name="ExceptionQueue" address="jms://exception.queue"/>
<global-endpoints>
....
<mule-configuration>
To reference a global endpoint in the configuration you use the <global-endpoint> element. The only
attibutes that can be set on this element are -
You can also set properties, transactions and filters on the referenced endpoint and these will override the
values set on the global endpoint.
To use the global ExceptionQueue endpoint as the catch all endpoint on our router do the following -
<outbound-router>
<catch-all-strategy className="org.mule.routing.inbound.ForwardingCatchAllStrategy">
<global-endpoint name="ExceptionQueue"/>
</catch-all-strategy>
<router
classname="org.mule.routing.outbound.OutboundPassthroughRouter">
<endpoint address="smtp://ross@muleumo.org"/>
</router>
</outbound-router>
</mule-descriptor>
Endpoint Identifiers
Endpoint identifiers can be used to map logical names to endpoint URIs. These identifiers can be used in
place of the actual URI in the configuration and in code. This allows you to define all your endpoint URIs
in one location which can be very useful when you move Mule instances between environments.
<mule-configuration>
<endpoint-identifiers>
<endpoint-identifier name="Component1Inbound" value="jms://in.queue"/>
<endpoint-identifier name="Component1Outbound" value="jms://out.queue"/>
<endpoint-identifiers>
<model>
<mule-descriptor name="Component1"
inboundEndpoint="Component1Inbound"
outboundEndpoint="Component1Outbound"
implementation="com.foo.Component">
</mule-descriptor>
</model>
<mule-configuration>
The below configuration which is also depicited in the Hello World example shows you how
to configure endpoints at Component level. This is the simplest form of defining a endpoint. Here the
component GreeterUMO would receive the event by configuring the attribute named inboundEndpoint.
Similarly the component GreeterUMO would send the event by configuring the outboundEndpoint
attribute.
<mule-descriptor
name="GreeterUMO"
inboundEndpoint="stream://System.in"
inboundTransformer="StringToNameString"
outboundEndpoint="vm://chitchatter"
implementation="org.mule.samples.hello.Greeter">
</mule-descriptor>
Developers can use the QuickConfigurationBuilder to programmatically build a Mule Manager instance.
This can be especially useful when configuring a Mule Instance from script or for test cases. You
can configure a server with only a few lines of code, for example to configure a server with a single
component -
This creates a new Mule Instance with a server admin url of 'tcp://localhost:60504' (if you don't want the
Mule Admin Agent to start, set this to ""). It also creates a Mule Component called 'echoComponent' that
is an Axis web service that will receive requests on 'http://localhost:81/services/echoComponent'.
The following example creates an asynchronous Mule Instance without an Admin Agent with a single
component that receives events via tcp and writes them out to file.
builder.registerComponent(AnotherComponent.class.getName(), "aComponent",
inboundEndpoint, outboundEndpoint);
The next example demonstrates adding additional configuration to the manager. In this case adding a jms
connector.
builder.registerComponent(AnotherComponent.class.getName(), "aComponent",
inboundEndpoint, outboundEndpoint);
Quick Links
Standard Properties - Simple key/value pairs
System Properties - Using system properties
Container Properties - Setting objects as properties from a container such as Jndi or Spring
Map Properties - Defining property maps
List Properties - Defining property lists and arrays
File Properties - Loading properties from file
Text Properties - Embedding Scripts and Xml in your configuration
Factory Properties - Using Object factories to create properties
Property Placeholders - Using variables
Mule Properties
Most of the configuration elements in the Mule Xml configuration can have a <properties> element. This
defines a set of bean properties that will be set on an object using standard getters and setters. As such,
the properties names themselves must follow the JavaBean naming convention where the 'get' or 'set'
part of the property method is removed and the first character of the property name is lowercase. So for
a bean that has a methods getTestProperty() and setTestProperty(...) the property name is testProperty.
<properties>
<property name="testProperty" value="foo"/>
</properties>
If a property is of type boolean, int, long, double, byte or float it will be automatically converted to the
correct type. Properties can also be Maps, Lists arrays,System properties, objects from a configured IoC
container and factory objects. Each of these are described in more detail below.
System Properties
<properties>
<system-property name="testProperty" key="TestProperty" defaultValue="foo"/>
</properties>
The name attribute refers to the name of the property on the bean, the key is the name of the property
to look for in the System properties. The defaultValue provides an optional default value if the property is
not set on the System properties. If the desired default value is null, just omit this attribute.
Container Properties
These are properties that are retrieved from a configured IoC or Naming container, such as Spring, Jndi
or EJB. The container is configured on the root configuration element using the ≶container-context>
element. See Object Containers for more information.
<properties>
<container-property name="testProperty" reference="testBean" required="true" container="jndi"/>
</properties>
Attribute Description
Factory Properties
Factory properties allow a property attribute to be created using a factory object. For example, in testing
you might want a property factory to create an InitialContext to save setting up Jndi. A property factory
must implement org.mule.config.PropertyFactory. This interface has a single method create with a
java.util.Map parameter that is a map of all the properties contained within the current <properties>
element. So you can configure properties for the factory instead of the bean itself if required.
<properties>
<factory-property name="testProperty" factory="org.foo.MyPropertyFactory"/>
</properties>
Configuring Maps
Maps can be expressed in a properties element using the <:map> element. The name of the property is
specified as an attribute of the element and each property entry below will be added to the map.
<properties>
<map name="testMap">
<property name="testProperty1" value="foo"/>
<property name="testProperty2" value="bar"/>
</map>
</properties>
A map element can contain all types of property elements listed above.
<properties>
<map name="testMap">
<container-property name="testProperty1" reference="foo"/>
<system-property name="testProperty2" value="bar"/>
<factory-property name="testProperty3" value="org.foo.TestFactory"/>
<property name="testProperty4" value="test4"/>
</map>
</properties>
Configuring Lists
Lists and Arrays are configured in the same way, in that there is not difference in configuring an array or
list in the configuration file, when the property is set it will be converted to a List or array depending on
the expected type.
<properties>
<list name="testList">
<entry value="foo"/>
<entry value="bar"/>
You can configure list entries as container, factory or system properties by using the 'container-entry',
'factory-entry' and 'system-entry' respectively.
<properties>
<list name="propertiesList">
<factory-entry factory="org.mule.tck.testmodels.mule.TestDependentObject"/>
<container-entry reference="Apple" required="true"/>
<system-entry key="os.version"/>
<entry value="test1"/>
</list>
</properties>
You can load properties for any object from a Java .properties file by using the 'file-properties' element.
This will load a properties file from the classpath or file system. You can also specify an 'override'
property that if set to true will over write any properties already configured on the object. The default for
'override' is true.
<properties>
<file-properties location="org/foo/some.properties" override="false"/>
</properties>
Text Properties
You can load a blob of text as a property string inside a Mule Xml Configuration file. This text can be an
embedded script, Xml, Xsl or any other type of text string. If embedding Xml you need to wrap the text in
a CDATA block. For example, to embed xml -
<properties>
<text-property name="configuration">
<![CDATA[
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="foo" class="org.bar.Foo"/>
</beans>
]]>
</text-property>
</properties>
The CDATA block is not necessary if embedding regular text. The following example embeds a groovy
script -
<mule-descriptor
name="GroovyUMO1"
inboundEndpoint="vm://groovy.1"
implementation="org.mule.components.script.jsr223.ScriptComponent">
<properties>
<text-property name="scriptText">
return "Groovy Received!"
</text-property>
<property name="scriptEngineName" value="groovy"/>
</properties>
</mule-descriptor>
jms.initial.context=org.jnp.interfaces.NamingContextFactory
jms.provider.url=jnp://localhost/
jms.connection.factory=java:/ConnectionFactory
jms.specification=1.1
These properties can then be loaded into the MuleManager properties. To load property values the Mule
Xml 'environment-properties' element must be used.
<mule-configuration>
<environment-properties>
<file-properties location="jndi.properties"/>
</environment-properties>
...
</mule-configuration>
Now you can reference the property values using property placeholders -
If a property is not found in the environment-properties the property placeholder is left intact.
Theoretically any attribute value in Mule Xml configuration can be substituted with a
property placeholder. However, the mule-configuration.dtd will complain if a placeholder is
used in an attribute that is an NMTOKEN or ID dtd type, such as class names. If you want
to use placeholders in these fields you will have to customise the mule-configuration.dtd.
Ejb Transport - Invoke remote Ejb session beans from your components.
Mule Resource Adapter - deploy Mule to your Application server and use JCA to configure your EJBs to
use Mule transports.
App Server Integration - Help deploying the Mule Resource Adapter to specific Application Servers.
Managing EJBs From Spring - how to invoke Spring-managed EJBs from Mule.
The EjbContainerContext can be used to expose EJB Session beans as Mule components. To
configure an Ejb container you need to add a <container-context> element that uses the
org.mule.impl.container.EjbContainerContext and set the Jndi environment properties.
The following example configures a JBoss Ejb container context -
<container-context className="org.mule.impl.container.EjbContainerContext">
<properties>
<!-- Jndi environment properties -->
<map name="environment">
<property name="java.naming.factory.initial" value="org.jnp.interfaces.NamingContextFactory"/>
<property name="java.naming.provider.url" value="jnp://localhost"/>
<property name="java.naming.factory.url.pkgs" value="org.jboss.naming:org.jnp.interfaces"/>
</map>
<!-- optional properties to configure custom security policies and security manager -->
<property name="securityPolicy" value="/projects/foo/classes/wideopen.policy"/>
<property name="securityManager" value="java.rmi.RMISecurityManager"/>
</properties>
</contianer-context>
Components can reference an Ejb session bean by setting the implementation attribute of a <mule-
descriptor> to the name of the Session bean stored in Jndi.
The following sample code and spring config fragements together with examples on page Using Spring
as a Component Factory, will help illustrate how Ejb can be exposed as Mule components via Spring
container.
Setting up Spring
<bean id="kitchenService"
class="org.springframework.ejb.access.SimpleRemoteStatelessSessionProxyFactoryBean">
<property name="jndiEnvironment">
<props>
<prop key="java.naming.factory.initial">${InitialContextFactoryClassName}</prop>
<prop key="java.naming.provider.url">${ProviderUrl}</prop>
<prop key="java.naming.security.principal">${Uid}</prop>
<prop key="java.naming.security.credentials">${Password}</prop>
</props>
</property>
<property name="jndiName">
<value>kitchenService</value>
</property>
<property name="businessInterface">
<value>com.foo.KitchenService</value>
</property>
</bean>
Spring 1.2.x
Starting from Spring 1.2, you can use a simpler form for property configuration. See
Section 3.3.3.7 in Spring Reference Documentation for details. The above config would look
like this:
<bean>
<!-- JNDI config omitted -->
...
<property name="jndiName" value="kitchenService"/
<property name="businessInterface" value="com.foo.KitchenService"/>
</bean>
Sometimes you'll have illegal (for URI) characters in your login/password. Use the standard
escape syntax your browser would use, e.g. the username user@mule would become user
%40mule.
Exception strategies are used to handle exception conditions when an error occurs processing an event.
There are two objects that support Exception strategies; components and connectors, plus a common
component exception strategy for components can be set on the model.
Exception Strategies associated with components or the Model are used to handle component exceptions.
These are typically business logic exceptions and the user will often want to customise 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 customised 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.impl.DefaultComponentExceptionStrategy and the connectors use
org.mule.impl.DefaultExceptionStrategy by default. Both of these strategies can be configured to
dispatch to one or more endpoints.
<mule-descriptor name="myComponent"
implementation="org.foo.MyComponent">
...
<exception-strategy className="
org.mule.impl.DefaultComponentExceptionStrategy"/>
</mule-descriptor>
Or you can set a common strategy for all components managed by the Model by setting it on the Model -
<model name="myModel">
...
<exception-strategy className="
org.mule.impl.DefaultComponentExceptionStrategy"/>
...
</model>
This will cause all components to use this exception strategy unless there is one explicitly defined for the
component.
You can set a endpoint on an exception strategy to forward the event that failed to a destination such as
an error queue. The org.mule.impl.DefaultComponentExceptionStrategy is a default implementation
that can be configured with an endpoint i.e.
<mule-descriptor name="mycomponent"
implementation="org.foo.mycomponent">
...
<exception-strategy className="
org.mule.impl.DefaultComponentExceptionStrategy">
<endpoint address="jms://error.queue"/>
</exception-strategy>
</mule-descriptor>
To implement your own strategy you class can extend the org.mule.impl.AbstractExceptionListener
though it is recommended that you extend the DefaultComponentExceptionStrategy and just overload
the defaultHandler() method. Bean properties can be set on your custom exception strategy in the
same way as other Mule configured objects using a <properties> element.
<mule-descriptor name="myComponent"
implementation="org.foo.MyComponent">
In some situations, you might want to change the way exceptions are logged. If so, all you have to do is
override the logException() method from the AbstractExceptionListener.
<connector name="tcpConnector"
classname="org.mule.providers.tcp.TcpConnector">
...
<exception-strategy className="
org.mule.impl.DefaultExceptionStrategy"/>
</connector>
The main difference is the type of exceptions that a Connector Exception Strategy will have to deal with.
These exceptions will typically be connection related exceptions that may or may not be recoverable.
The org.mule.impl.DefaultExceptionStrategy is the default used for connectors that simply logs the
exception and continues.
Configuring Filters
Filters can be used to express the rules that control how routers behave. Mule has the following default
filters:
PayloadTypeFilter
will check the class type of the payload object inside an event.
<filter expectedType="java.lang.String"
className="org.mule.routing.filters.PayloadTypeFilter"/>
RegExFilter
will apply a regular pattern to the event payload. The filter will do a toString() on the event payload, so
users may also want to apply a PayloadTypeFilter as well to the event using an AndFilter to make sure the
event payload is a String.
WildcardFilter
will apply a wildcard pattern to the event payload. The filter will do a toString() on the event payload, so
users may also want to apply a PayloadTypeFilter as well to the event using an AndFilter to make sure the
event payload is a String.
For the string "the quick brown fox jumped over the lazy dog" the following patterns would match -
JXPathFilter
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 user guide or this tutorial. Also there is a good XPath
tutorial at zvon.org.
<filter expression="(msg/header/resultcode)='success'"
className="org.mule.routing.filters.xml.JXPathFilter"/>
It is possible to set other JXPath context properties on the filter. Two of the important ones are
namespaces and value which is used to compare to the result of the XPath expression (value is 'true' by
default).
<filter expression="msg/header/resultcode"
OGNLFilter
OGNL is a simple yet very powerful expression language for plain Java objects. Similar to (J)XPath it
works on object graphs; the corresponding filter therefore enables simple and very efficient content
routing for payloads. As an example:
<filter className="org.mule.routing.filters.OGNLFilter">
<properties>
<property name="expression" value="\[MULE:0\].equals(42)"/>
</properties>
</filter>
This filter would block any messages whose payloads are not arrays or lists and do not contain the value
42 as first element.
MessagePropertyFilter
This filter allows you add logic to your routers based on the value of one or more properties of a Message.
This can be very powerful because Message properties of the underlying message are exposed meaning
you can reference any transport-specific or user defined property. So for an Http event you can match
one or more Http Headers; the same applies for all other message types such as Jms or email.
<filter expression="Content-Type=text/xml"
className="org.mule.routing.filters.MessagePropertyFilter"/>
The expression is always a key value pair. If you want to have more complex extressions you can use the
logic filters. For example -
<filter className="org.mule.routing.filters.logic.AndFilter">
<left-filter expression="JMSCorrelationID=1234567890"
className="org.mule.routing.filters.MessagePropertyFilter"/>
<right-filter expression="JMSReplyTo=null"
className="org.mule.routing.filters.MessagePropertyFilter"/>
</filter>
Logic Filters
AndFilter
An And filter combines two filters and only accepts if both filters match. Logic filters can be nested so that
more complex logic can be expressed.
<filter className="org.mule.routing.filters.logic.AndFilter">
<left-filter expectedType="java.lang.String"
className="org.mule.routing.filters.PayloadTypeFilter"/>
<right-filter pattern="the quick brown (.*)"
className="org.mule.routing.filters.RegExFilter"/>
</filter>
OrFilter
The Or filter combines two filters and accepts if either of the filters match.
<filter className="org.mule.routing.filters.logic.OrFilter">
<left-filter expectedType="java.lang.String"
className="org.mule.routing.filters.PayloadTypeFilter"/>
<right-filter expectedType="java.lang.StringBuffer"
className="org.mule.routing.filters.PayloadTypeFilter"/>
NotFilter
A not filter will accept if the filter assigned to it does not accept.
<filter className="org.mule.routing.filters.logic.NotFilter">
<filter expectedType="java.lang.String"
className="org.mule.routing.filters.PayloadTypeFilter"/>
</filter>
The filters provided should be able to handle most filtering requirements however if you need to write
your own it is really easy. You just need to implement the UMOFilter interface which has a single method.
This method should return true if the UMOMessage matches whatever critia the filter imposes otherwise it
should return false.
Like all other Mule object bean properties can be set on the filter.
The Mule DTD defines a number of default attibutes that can be set on a <filter> element in Mule Xml
such as pattern, expression, configFile, expectedType and path. You don't have to use these if you dont
want to as you can set any property using the <properties> element.
Testing Mule
As Mule is light-weight and embeddable it is easy to run a Mule Server inside a testcase. In fact Mule
provides an abstract JUnit test case called
org.mule.tck.FunctionalTestCase
for running Mule inside a testcase and manages the lifecycle of the server. The Mule TCK also contains a
for functionally testing Mule code. These are described in more detail in the following sections.
The FunctionalTestCase
The
FunctionalTestCase
is a base test case for tests that initialize Mule using a configuration file. Generally we would make
our Mule test cases extend the FunctionalTestCase so that we could use its functionality. The default
configuration builder used in the FunctionalTestCase is the MuleXmlConfigurationBuilder.
For this to work you need to have the mule-modules-builders jar on your classpath. This enables us to
just enter the name of the mule configuration file we are using in the method getConfigResources and the
FunctionalTestCase would automatically call the default builder to configure Mule.
If you want to use a different configuration builder, just overload the getBuilder() method of this class to
return the type of builder you want to use with your test.
The FunctionalTestComponent:
The FunctionalTestComponent is a component which, as the name implies, is used in the testing
environment. The component comprises of two methods: the onCall method and the onReceive method
that basically do the same thing
What the FunctionalTestComponent does in either one of the methods is to take the message passed to it
(either from the UMOEventContext or from the Object) and transform it into a String. It will then create
a message that it will send back to the caller. It also checks whether either one of its three properties are
set and acts accordingly.
• boolean throwException
By default the FunctionalTestComponent returns the received message and appends the word "Received"
to it, i.e. if we send the message "Hello World" it returns the message "Hello World Received".
The returnMessage property enables us to replace this default message with one of our own.
We can set our message in the returnMessage property in one of two ways:
<mule-descriptor name="myComponent"
implementation="org.mule.tck.functional.FunctionalTestComponent">
<inbound-router>
<endpoint address="vm://test"/>
</inbound-router>
<outbound-router>
<router className="org.mule.routing.outbound.OutboundPassThroughRouter">
<endpoint address="vm://testout"/>
</router>
</outbound-router>
<properties>
<property value="Customized Return Message" name="returnMessage"/>
</properties>
</mule-descriptor>
The eventCallback is a property which refers to the EventCallback interface. The scope of the Event
Callback is to be able to get a component we are using and to control it. This is especially useful when
we have beans configured in Spring that we need to exercise some form of control on, example setting
properties at runtime instead of in the configuration.
To be able to use the eventCallback from our test case, first we need to make our test case implement
the EventCallback interface. Then we would need to implement the single method that this interface
exposes, i.e. the eventReceived method.
In the example below, we are using the eventReceived method to get a message from the
event context. Then we transform the component received as an input parameter into a
FunctionalTestComponent by typecasting it and we set the returnMessage property discussed previously
on the FunctionalTestComponent at runtime.
For Information regarding how to use the EventCallback with components configured as Spring beans
click on the following link: Using the eventCallback with a bean configured in Spring
<mule-descriptor name="myComponent"
implementation="org.mule.tck.functional.FunctionalTestComponent">
<inbound-router>
<endpoint address="vm://test"/>
</inbound-router>
<properties>
</properties>
</mule-descriptor>
2. We could use the QuickConfigurationBuilder to build the configuration in our test case and set the
property programmatically.
single.setThrowException(true);
FunctionalTestNotificationListener:
When an event is received, the FunctionalTestComponent fires a notification informing us that the event
has been received. It is up to us to set up a listener (the FunctionalTestNotificationListener) on our test to
capture this notification.
To be able to do so, we must first make our test case implement the FunctionalTestNotificationListener
interface. Then we must implement the method exposed by this listener, which is the onNotification. In
the example below, we check the notification.getAction to see whether it is the FunctionalTestNotification
fired by the FunctionalTestComponent. If it is, we print it out to the console.
if (notification.getAction() == FunctionalTestNotification.EVENT_RECEIVED)
{
System._out_.println("Event Received");
}
}
Now, in order for our listener to start listening for notifications, we must register it. When using the
QuickConfigurationBuilder, which will soon be discussed, the listener is registered like so:
builder.getManager().registerListener(this,"myComponent");
The following is an example where we use the QuickConfigurationBuilder to overload the default
configuration builder.
Note: The method setUp() is the implementation of the method exposed by the TestCase class which our
test class extends.
{
builder = new QuickConfigurationBuilder();
QuickConfigurationBuilder builder;
The eventReceived method is the implementation of the method exposed by the EventCallback interface.
We simply set the returnMessage property on our FunctionalTestComponent to "Customized Return
Message", which is the message that we will expect to be returned to our test case
The following is our test case, i.e. from where we are going to send our request
The onNotification method where we assert that the notification received was the one fired by the
FunctionalTestComponent
Next we need to build a Test Case that extends the FunctionalTestCase. Since, unlike the test with the
QuickConfigurationBuilder, we do not create the component ourselves but is created for us through the
configuration, we need to get an instance of that component, i.e. myComponent. To do this we need to
use the MuleManager and retrieve from it the instance of the component from the model as seen in the
snippet of code below.
FunctionalTestComponent myComponent =
(FunctionalTestComponent)MuleManager.getInstance().getModel().getComponent("myComponent").getInstance();
Once we have the instance we have to create an eventCallback and set it on the component.
Note that we do not have to configure the setUp method since the setup will be done automatically.
However, you can implement the doPreFunctionalSetUp() method if you need to add some additional
things set up in your configuration.
// Create Callback
EventCallback callback = new EventCallback() {
public void eventReceived(UMOEventContext context, Object o) throws Exception
{
UMOMessage message = context.getMessage();
FunctionalTestComponent fc = (FunctionalTestComponent) o;
fc.setReturnMessage("Customised Return Message");
}
};
// set callback
myComponent.setEventCallback(callback);
We have to give the name of our configuration file to the method getConfigResources. We need to
implement this method when extending the FunctionalTestCase.
Note: Remember, the mule configuration must be on your classpath.
If we are configuring Mule with the configuration file then we would have to use the Mule Manager to get
an instance of the bean from the ContainerContext.
FunctionalTestComponent myComponent =
(FunctionalTestComponent)MuleManager.getInstance().getContainerContext().getComponent("FunctionalTestBean");
FunctionalTestComponent myComponent =
(FunctionalTestComponent)builder.getManager().getContainerContext().getComponent("FunctionalTestBean");
Once we have retrieved the instance of the bean, we create an eventCallback and set it on the bean.
The following is a complete example of how we would retrieve an instance of a spring bean from the
springcontainer using the QuickConfigurationBuilder style of configuring Mule.
//We need to create a SpringContainerContext and load the Spring configuration file in it.
SpringContainerContext ctx =new SpringContainerContext();
ctx.initialise();
ctx.setConfigFile("spring-context-config.xml");
builder.setContainerContext(ctx);
//We need to get an instance of the bean we have configured in Spring and set the Callback on it.
FunctionalTestComponent myComponent =
(FunctionalTestComponent)builder.getManager().getContainerContext().getComponent("FunctionalTestBean");
EventCallback callback = new EventCallback() {
public void eventReceived(UMOEventContext context, Object o) throws Exception
{
UMOMessage message = context.getMessage();
FunctionalTestComponent fc = (FunctionalTestComponent) o;
fc.setReturnMessage("Customised Return Message");
}
};
myComponent.setEventCallback(callback);
// Now we can continue to configure mule normally by adding the endpoints and registering the
listener, etc.
UMOEndpoint vmSingle = builder.createEndpoint("vm://Single","SingleEndpoint",
true);
builder.registerComponentInstance(myComponent, "SINGLE",vmSingle.getEndpointURI());
builder.getManager().registerListener(this,"SINGLE");
}
Now we proceed to set our test case. The FunctionalTestComponent should return the message
"Customized Return Message".
This is the notification of events that will listen for the notification fired by the FunctionalTestComponent.
Note: The Spring configuration file is still used to configure the beans.
<beans>
<bean id="FunctionalTestBean" class="org.mule.tck.functional.FunctionalTestComponent"/>
</beans>
Using the FunctionalTestCase, we can run the same example as above but using the mule configuration
file. So first, we need to configure the mule-config.xml file, with our component referring to the bean we
have configured in Spring (FunctionalTestBean).
Note: We will be using the same Spring bean we configured in the previous example.
Next we need to build a Test Case that extends the FunctionalTestCase. We should get the instance of the
component from the Container Context.
FunctionalTestComponent myComponent =
(FunctionalTestComponent)MuleManager._getInstance_().getContainerContext().getComponent("FunctionalTestBean");
As usual, once we get the instance of the bean, we can create an eventCallback and set it on the
component.
1. Using 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.
2. Defining a connector configuration in Mule XML, Spring or any other supported configuration.
3. Transport provider properties can be set on endpoints to customise the transport behaviour for a
single endpoint instance.
The actual configuration parameters for each transport type are described in the Transports Guide for
each particular transport. The following describes the common properties for all transports.
createDispatcherPerRequest
Determines whether false Yes
the connector caches
a MessageDispatcher
once it has been
created for an endpoint
or if a new one should
be created for each
dispatch request
For information about specific properties for a particular transport provider see the Transports Guide.
Connection Strategies
Connection strategies are used to configure how a connector behaves when its connection fails. Different
strategies can be used to control how a reconnection is made based on retries, frequency, exceptions
occurred or other factors such as only allowing a reconnect from JMX.
A connection strategy is configured on the connector using the <connection-strategy> element.
When a <connection-strategy> element is added to a connector the strategy is applied to inbound and
outbound connections. If you require a different behaviour for inbound and outbound connections on
the same connector you need to configure two connectors to handle inbound and outbound connections
differently. For example, to configure a TCP connector that will try to connect 3 times every 2 seconds if
the connection is lost -
Tip: setting retryCount to -1 will make it retry connections infinitely (available since Mule 1.4.2).
However, be careful with it depending on the nature of the transport. A doThreading option can be useful
in certain cases, it'll decouple the Mule thread from the reconnection attempts.
You can set a default connection strategy for all connectors on a Mule instance by setting the strategy in
the <mule-environment-properties> element, i.e.
<mule-environment-properties>
<connection-strategy className="org.mule.providers.SimpleRetryConnectionStrategy">
<properties>
<property name="retryCount" value="3"/>
<property name="frequency" value="2000"/>
</properties>
</connection-strategy>
</mule-environment-properties>
Mule comes with a few basic connection strategies such as the the SimpleRetryConnectionStrategy shown
above. However, you may need to implement your own. The ConnectionStrategy is an interface with one
method -
This method should attempt to call connect() on the UMOConnectable object, until the connection works
or the connection policy implemented by the custom UMOConnectionStrategy fails. If the connection
fails a FatalConnectException should be thrown to tell Mule that it cannot connect. No other exceptions
including RuntimeExceptions should be thrown.
Using the TCP transport provider as an example the file looks like -
connector=org.mule.providers.tcp.TcpConnector
dispatcher.factory=org.mule.providers.tcp.TcpMessageDispatcherFactory
message.receiver=org.mule.providers.tcp.TcpMessageReceiver
message.adapter=org.mule.providers.tcp.TcpMessageAdapter
inbound.transformer=org.mule.transformers.simple.ByteArrayToString
outbound.transformer=org.mule.transformers.simple.StringToByteArray
endpoint.builder=org.mule.impl.endpoint.SocketEndpointBuilder
When an endpoint URI is processed by Mule, it's service descriptor is located using the endpoint protocol
and the descriptor along with the information on the URI are used to create a connector and endpoint
instance.
Every connector has a serviceOverrides property which is a map containing one or more of the service
properties listed above. Continuing with the custom File Receiver example, a developer can override the
'message.reciever' Connector Service Descriptor property.
<environment-properties>
<property name="jms.jndiInitialFactory"
value="org.codehaus.activemq.jndi.ActiveMQInitialContextFactory"/>
</environment-properties>
or
MuleManager.getInstance.setProperty("jms.jndiInitialFactory",
"org.codehaus.activemq.jndi.ActiveMQInitialContextFactory");
For a more complete example see the Mule Cookbook: Configuring Multiple Jms Clients
• Explain briefly what you problem is. Use point form or short paragraphs as it makes it easier to read
and understand.
• Specify the Mule version, Jdk version as well as the version numbers of other technologies you are
using in your application
• If the application involves any complicated routing, it will be useful to provide a diagram of your
system (possibly generated using the visualizer tool available with Mule).
• Provide the relevant exception stack listing
• Provide your configuration file or at least the relevant parts of your configuration.
• Whenever possible, also provide a test case package that would illustrate your problem. Actually,
this is the ideal situation since this will save other people from having to replicate your error
first. We will now take a look at a problem which was actually taken from the Mule User List and
illustrate how a test case can be built to illustrate the scenario depicted here.
Case Study:
My server should be able to send a message with attachment (eg. image) to client over soap. I expect
that sending image as an attachment would be more efficient than sending it as for example a byte array.
A client should be able to receive the attachment and for example display it to the user.
Service Component:
return dataHandler;
}
Service config:
<endpoint-identifiers>
<endpoint-identifier name="AxisWSEndpoint" value="axis:http://localhost:8080/services" />
</endpoint-identifiers>
<transformers>
<transformer name="HttpRequestToSoapRequest"
className="org.mule.providers.soap.transformers.HttpRequestToSoapRequest"/>
</transformers>
<model name="soapGisSample">
<mule-descriptor name="gisService" implementation="sample.gis.Geo">
<inbound-router>
<endpoint address="AxisWSEndpoint" transformers="HttpRequestToSoapRequest">
<security-filter className="org.mule.extras.acegi.filters.http.HttpBasicAuthenticationFilter">
<properties>
<property name="realm" value="mule-realm"/>
</properties>
</security-filter>
</endpoint>
</inbound-router>
</mule-descriptor>
Client:
...
In the above scenario, the problem is evident; the Server can't send Attachments over Axis to client
application. In other cases, there may be more than one problem. In such cases you should list the
problems individually and test for each independently on any other errors. Once the problem is identified
you should build a test case in order to test for this problem and build a scenario where the problem is
replicable.
The FunctionalTestCase available in Mule not only allows you to build JUnit tests but also to define
a mule configuration file (which will be used to load Mule), so extending this class for your tests is
encouraged. An important factor to keep in mind when creating a test case is the level of detail. It is
better to cut down to the basic stuff by removing anything from the configuration that does not directly
relate to the problem. For example, in the configuration that the client provided for us above, the
security filter and the transformers can be removed. As a test component we can create a class called
org.foo.FileOperationsComponent that will implement a method that is very similar to the one provided to
us by the user. This method, once called, will create a file, create a datahandler with that file, and send it
back to the client. We must also provide an interface for this class since we're using Axis.
package org.foo;
import java.io.File;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import org.mule.impl.MuleMessage;
import org.mule.umo.UMOMessage;
public FileOperationsComponent()
{
// empty constructor
}
We build the mule configuration file for this test the same way we would build our mule configuration.
Below we configure our OperationsComponent to accept an inbound message over the Axis transport:
The test case would look something like the following. Please note that the mule-config.xml file as seen
above is referenced in the getConfigResources() method in the test case.
String getConfigResources()
{
return "mule-config.xml"
}
}
Note that there are three assertions that we are making above.
In the case of this particular problem, the test case will not meet the second two conditions and will fail
thus demonstrating that there is a problem with Attachments being received from the server over Axis in
a more clear-cut and concise way.
• English
• Japanese
Using Internationalisation
Mule uses the java ResourceBundle class to load messages from properties files on the classpath based
on the current systems locale. Mule only has full set of messages in English and Japanese but may have
translations in future.
Users will need to understand about how MUle loads messages if they want to throw any Mule exception
that extends UMOException. This is the base class of all Mule checked exceptions and can only be
constructed using internationalised messages.
throw e;
You can also pass in message parameters when creating a Message object. these will be used to embed
variable information in the message. The message constants defined in org.mule.config.i18n.Messages
uses X's to denote how many parameters the message expects. For example
throw e;
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.
To load a message from this bundle the developer just needs to pass in the resource bundle name -
This loads the message with id 2 from xxx-message.properties, formats the message with 2 parameters
"one" and "two" and prints out the message to System.out -
Mule supports internationalisation of exception messages, or any other type of string message.
• English
• Japanese
Using Internationalisation
Mule uses the java ResourceBundle class to load messages from properties files on the classpath based
on the current systems locale. Mule only has full set of messages in English and Japanese but may have
translations in future. The examples come with more localizations, though.
Users will need to understand about how Mule loads messages if they want to throw any Mule exception
that extends UMOException. This is the base class of all Mule checked exceptions and can only be
constructed using internationalised messages.
You never create instances of Message directly, instead you use subclasses of MessageFactory. Each
of Mule's modules and transports has such a messages class. Its name is equal to the module with
Messages appended e.g. for the JMS transport you will use JmsMessages to retrieve the messages specific
to the JMS transport.
The dedicated messages class per module/transport has the following advantages:
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 xxx-messages.properties where xxx is the identifying name for this bundle. This
file should then be located in your jar under META-INF/services/org/mule/i18n/xxx-messages.properties
but can be placed in any other location on the classpath.
In order to access the messages of your own resource bundle, create a subclass of MessageFactory as
follows:
To load a message from this bundle the developer just needs to pass in the resource bundle name -
This loads the message with id 2 from xxx-message.properties, formats the message with 2 parameters
"one" and "two" and prints out the message to System.out -
The following pages describe how to deploy Mule to various application servers and how to Configure App
server Resources such as Jms to be used with Mule.
These pages are works in progress, where new information is added as people submit configurations for
their particular app server. If you are using Mule with an AppServer not listed or think that we are missing
some important information please contact us with the details. It will be greatly appreciated!
Application Servers
• Geronimo Integration
• JBoss Integration
• Oracle Integration
• MULE:SeeBeyond Integration
• MULE:Sun One Integration
• Weblogic Integration
• WebSphere Integration
TODO
ActiveMQ Configuration
Geronimo uses ActiveMq as it's default Jms provider.
The specification property tells Mule to use the Jms 1.1 specification, which is the specification ActiveMQ
supports. To disable queue persistence, you'll need to specify it in ActiveMQ configuration file (see below).
To configure ActiveMQ on a specific brokerUrl or from an ActiveMQ configuration file use the following
(Spring version)
mule-config.xml
<!-- Give this container a name in case you have more than one container,
e.g. Spring, Plexus, JNDI, EJB, etc. You can safely omit it if you
don't have these requirements.
-->
<container-context className="org.mule.extras.spring.SpringContainerContext"
name="spring">
<properties>
<property name="configFile" value="classpath:/org/mule/test/activemq-spring.xml"/>
</properties>
</container-context>
activemq-spring.xml
<beans>
<bean id="activeMqConnectionFactory" class="org.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="vm://localhost"/>
<property name="brokerXmlConfig"
value="classpath:/org/mule/test/activemq-config.xml"/>
<!-- More properties you want set on ActiveMQConnectionFactory -->
</bean>
</beans>
Your ActiveMQ config is a standard one. E.g. to use in-JVM messaging without persistent queues (very
useful for testing) the file will be as follows:
activemq-config.xml
<beans>
<broker>
<connector>
<serverTransport uri="vm://localhost"/>
</connector>
<persistence>
<vmPersistence/>
</persistence>
</broker>
</beans>
Building an Ear file for the deployment of the Mule JCA Resource Adapter on
JBoss 4.0.5
Although the Mule JCA Resource Adapter could be deployed directly, the best way to deploy Mule on JBoss
is for the resource adapter to be placed inside an EAR file. The advantage of deployment using an Ear file
over using the Mule JCA Resource Adapter directly are the following:
• JBoss allows Ear, War and Sar files to have classloader isolation. This feature is not yet available
for the Rar file.
• The Mule JCA Resource Adapter contained in the Ear file is specific for JBoss deployment.
• The mule-jboss-ds.xml file has to be moved from the mule-module-jca-1.4.0-jboss.jar file up to the
ear level which makes it easier to edit.
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. Classloading isolation is important since the versions of the libraries used to load Mule
are not the same as the ones used by JBoss and so various errors may crop, the most common being
ClassCastExceptions.
Adaptation of the .rar file for use with the Ear file
The mule-jca-1.4.0-jboss.rar file needs a couple of modifications to be able to work inside an isolated Ear
file. The following are the libraries that you need to remove:
• log4j-1.2.14.jar
• mx4j-jmx-2.1.1.jar
• xercesImpl-2.8.1.jar
• xml-apis-1.3.03.jar
• the mule-jboss-ds.xml needs to be removed from the mule-modules-jca-1.4.0.jar
Package Format
If you are going to repackage the mule-jca-1.4.0-jboss.rar please note that this
should be in a simple zip file format and should not be confused with the RAR
packaging.
Xerces Parser
The xerces and xml-apis jars have to be removed because JBoss has a problem with
parsers being in an isolated package and they will conflict with JBoss' own xerces and
xml-apis files. Pending a fix for this on the JBoss' side, you'll have to use the JBoss
parsers.
The file structure of the Ear file should have the following format:
META-INF
| - application.xml
| - jboss-app.xml
| - MANIFEST.MF
mule-jca-1.4.0-jboss.rar
Below are the configuration files for the XML files shown in the above file structure:
mule-jboss-ds.xml
This mule-jboss-ds.xml file is an adaptation of the one we removed from the mule-modules-jca-1.4.0.jar
file. Note that since 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 separtated by the # symbol. This will be our datasource.
application.xml
This file is required for us to tell the .ear file to use our mule-jca-1.4.0-jboss.rar as a connector. In this
way this can be deployed as resource adapter.
jboss-app.xml
In the following configuration file, we are creating a loader-repository in which to load our classes during
the classloading operation. The java2ParentDelegation property has to be set to false in order to enable
classloader isolation. We specify our mule-jboss-ds.xml as a service to be loaded.
Deploying the JBoss-specific Ear distribution containing the Mule JCA Resource
Adapter:
Deployment is the easiest thing. Just drop the EAR file into the JBoss server deployment folder and start
up JBoss. JBoss will take care of deploying everything for you.
The resource adapter comes configured with a dummy mule-config.xml file. However, you will want to use
your own configuration file. One way to do this is to physically replace the mule-config.xml file in the Mule
JCA Resource Adapter (mule-modules-jca-1.4.0.jar) with your own. A more elagant way to do it would be
the following:
Assuming that you have your pojos bundled in a jar file you can do the following:
• put the resource files(xslt, properties, etc.) in your jar file (these should be picked up automatically
when mule starts)
• create a folder in the root of the mule-jca-1.4.0-jboss.rar file and put your mule configuration in
there. For the time being, let's call this folder "conf".
• edit the ra.xml file found in mule-jca-1.4.0-jboss.rar META-INF folder and reference your
configuration file name as seen below.
<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-1.4.0.jar.
JBoss MQ Configuration
To configure a JBoss Jms connector for Mule use the following -
Any provider-specific properties can be passed to the InitialContext for this connector using the
jndiProviderProperties attribute. Use connectionFactoryProperties to set JBoss-specific properties on the
ConnectionFactory.
Connection Credentials
If you use user creditials to connect to JBossMQ 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
(i.e. in RemoteSync calls) are used.
For this scenario the deployment is very simple; the user just needs to add his own jar files to the mule-
ear file. Since everything will be deployed in the mule-ear, then all the classes required by both the user
application and mule will be found in the same classloader and be able to communicate. However it may
not always be feasible to deploy the application in this way. For example, if mule has to use an existing
and deployed component, then Mule should be able to communicate with the application even if the
classes are deployed outside the mule-ear.
The user can literally create an ear file containing all his required classes as well as the mule-ear. This
will have the same advantages and disadvantages as the previous scenario. However, it helps to keep
the user application and the mule-ear more distinct. In addition to this, the mule-ear file requires less
modifications. However, there is a small change that needs to be done to the mule-jboss-ds.xml inside
the mule-ear. Since we now have another layer that encapsulates our resource adapter, i.e. the user ear,
we need to change the connection name of the resource adapter to the following format:
<rar-name>user-ear.ear#mule-ear.ear#mule-jca.rar</rar-name>
If the application/classes that the user wants to use do not depend on the mule code itself, then
deployment for this scenario is also relatively easy. First of all, since mule is in an isolated classloader,
the user ear file must share the same classloader. In this way the libraries become accessible to the user
application. The second issue is that if the mule configuration file inside the mule-ear.ear file refers to
some classes in the user ear, then we have to make sure that the user ear file is loaded before the mule-
ear file. The best way to do this is to enumerate the ear files in the order in which the user wants them
to be deployed. For example if the user ear file is called 1-user-ear.ear and the mule ear file is called 2-
mule-ear.ear, Jboss will load the user ear file first and mule second, ensuring that the user libraries are
already loaded in the shared classloader repository for mule to find. For more information about Jboss
Deployment Order please read the following: http://wiki.jboss.org/wiki/Wiki.jsp?page=DeploymentOrder
The situation becomes more complex when the user wants to deploy mule dependant code in a separate
ear file (for example the user has a custom transformer that extends mule's AbstractTransformer). In
such a case we have a situation of cross dependencies. 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 this you can create a shared
library (in another ear file perhaps) and make both the mule-ear and the user-ear use the classloader
repository of the shared library.
Mule as MBean | Creating a Simple MBean | Creating JBoss Service Descriptor | Deploy
MBean to JBoss | References | External References | Related
Mule as MBean
An MBean[MULE:1] is a named managed object representing a resource in an JMX environment. We can
have an MBean deployed with Mule in it easily, the steps as follows:
Just as you have not yet noticed, we are using JBoss application server in this document.
package foo.mbean;
package foo.mbean;
import org.jboss.system.ServiceMBeanSupport;
import org.mule.config.builders.MuleXmlConfigurationBuilder;
import org.mule.umo.manager.UMOManager;
import org.mule.umo.manager.UMOServerNotification;
try{
MuleXmlConfigurationBuilder builder = new MuleXmlConfigurationBuilder();
UMOManager manager = builder.configure("mule-config.xml");
manager.start();
manager.registerListener(this);
}
catch(Exception e){
e.printStackTrace();
}
this.getLog().info("MBean started");
}
}
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.
So, your distro looks like this (using the examples above):
.
./foo
./foo/FooService
./foo/FooServiceMBean
./META-INF
./META-INF/jboss-service.xml
Pack it, either as a JAR (which can then be renamed to a *.sar, and eventually you will need to extract it
as JBoss might not be picking it up for whatever reason that I have no idea about) or as a directory called
<whatever>.sar.
References
External References
1. Wikipedia - MBean
2. The Java Tutorials - Standard MBeans
Related
Durable Subscribers
When using durable subscribers Mule automatically sets the Jms clientId on the connection,
if not explicitly set. Joram complains if the clientId is set, so you need to tell Mule not to set
it by setting the clientId on the JmsConnector to "".
If you do not have Jndi set up you need to manually create a Jndi Initial Context. You can do this by
adding a Mule property factory (like the one listed below). Your configuration will look something like -
The Jndi property factory class will look like the following, though you may want to add support for other
Joram properties.
JoramInitialContextFactory.java
TODO. If you are using Mule with Oracle Application Server please contact us with your configuration and
any tips to getting Oracle Application Server and Mule working together. Thanks!
The Oracle JMS Provider extends the standard Mule Jms Provider with functionality specific to Oracle's
JMS implementation based on Advanced Queueing (Oracle AQ).
The javadoc for this transport provider can be found here. And the Source Xref can be found here.
The Oracle JMS Provider adds support for queues with ADT (Advanced Data Type) payloads, including
Oracle's native XML data type
Unlike the standard JMS Provider, the Oracle JMS Provider does not require a JNDI provider to use.
Properties
In addition to the properties available for the standard Jms Provider, the Oracle JMS Provider adds the
following properties:
The user
and
password
may be
specified
in the
URL
itself, for
example
jdbc:oracle:oci:scott/
tiger@myhost,
in which
case the
multipleSessionsPerConnection
Some versions of false no
Oracle do not support
more than one JMS
session per connection.
In this case we need to
open a new connection
for each session to
avoid the following
error:
JMS-106: Cannot
have more than one
open Session on a
JMSConnection
Transformers
In addition to the transformers available for the standard Jms Provider, the Oracle JMS Provider adds the
following transformers, found in org.mule.vendor.oracle.jms.transformers.
Transformer Description
The default transformers are the same as the standard JMS Provider (JMSMessageToObject and
ObjectToJMSMessage).
Endpoints
Oracle AQ endpoints are expressed in the same way as Jms endpoints except the protocol is different.
oaq://my.queue
or
oaq://topic:my.topic
You can define an Oracle AQ endpoint without declaring the connector (as shown above), by including all
necessary information on the endpoint uri i.e.
oaq://XML_QUEUE?url=jdbc:oracle:oci:scott/tiger@myhost
Refer to the unit tests for more examples on how to use the provider.
Dependencies
The Oracle JMS Provider requires the following Oracle libraries, which should be included in your Oracle
installation:
Unit Tests
In order to run the unit tests in tests/vendor/oracle against your Oracle database, you will need to
create a JMS user "mule" and grant it AQ rights as follows.
TODO
Jms Configuration
Before using Mule with Weblogic copy the weblogic.jar file to $MULE_HOME/lib/user.
Weblogic 9.x
For Weblogic 9.x the config 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.
JDK version
In case you are getting the following error when connecting to Weblogic 9.x
make sure Mule is started with JDK 5 and above, anything below will not work.
JBI integration
Embedding Mule in JBI - You can use Mule transports, transformers and components inside any JBI
compliant container.
Invoking JBI Components from Mule - Mule has a JBI binding allow you to invoke components form JBI
containers allow JBI components to invoke Mule components.
Mule JBI Examples - Configuration examples for using Mule in JBI containers.
Note that there is a new JBI-2 effort that has recently started. This approach seems to be recognising
that POJO services are the right way to go (you saw it here first ) so we think we made the right
choice not to adopt JBI. Also, there seems to have been very little uptake of the specification since it was
launched in 2005.
Endpoints
Endpoints are used to send or receive data via a Mule supported transports such as Jms, Jdbc, Http,
Soap, Xmpp, Ftp, Ejb, Rmi, Quartz, tcp, udp, and more.
1. MuleReceiver - will receive data over any Mule transport and deliver them as JBI messages.
2. MuleDispatcher - will send Jbi Normalised Messages over any Mule transport.
MuleReceiver
The component has a few properties that must be set. The most obvious one is the endpoint on which it
will receive events. This endpoint is a Mule endpoint and is independent of the JBI container being used.
The other required property is the name of the target service that this component will foward the event
to.
muleEndpoint org.mule.impl.endpoint.MuleEndpoint
This allows you to No
specify a Mule endpoint
object instead of an
EndpointURI string.
This gives you greater
flexibility to specify
filters, transactions and
transformers on the
endpoint.
targetService javax.xml.namespace.QName
The target service to Yes
be invoked after this
component
workManager javax.resource.spi.work.WorkManager
The manager that No
will manage threads
MuleDispatcher
Again the most obvious one is the endpoint on which it will dispatch events. This endpoint is a Mule
endpoint and is independent of the JBI container being used.
muleEndpoint org.mule.impl.endpoint.MuleEndpoint
This allows you to No
specify a Mule endpoint
object instead of an
EndpointURI string.
This gives you greater
flexibility to specify
filters, transactions and
transformers on the
endpoint.
Components
//Todo
Transformers
The Mule transformer component allows any Mule transformer to run inside JBI. To configure it you must
add an instance of the org.mule.providers.jbi.components.TransformerComponent. This expects to have
a Mule transformer instance set on it that will be invoked when the component receives the message. The
way in which the transformer is set varies from the Jbi container you are using. See Mule JBI Examples
for details.
The following are examples of how to use Mule inside any JBI container. They provide configuration
examples for each of the open source JBI containers.
File Binding
This reads a file from one directory 'inbox' and writes it to an 'outbox' directory. The example shows how
it can be configured in Mule-JBI, ServiceMix and Celtix.
Mule JBI
<!-- Mule Reciever that looks for files in the inbox directory -->
<mule-component name="foo:fileReceiver" className="org.mule.providers.jbi.components.MuleReceiver">
<inbound-router>
<endpoint address="file://./inbox?pollingFrequency=1000"/>
</inbound-router>
<outbound-router>
<endpoint address="container://foo:fileSender"/>
</outbound-router>
</mule-component>
<!-- Mule Dispatcher that Writes files to the outbox directory -->
<mule-component name="foo:fileSender" className="org.mule.providers.jbi.components.MuleDispatcher">
<inbound-router>
<endpoint address="container://foo:fileSender"/>
</inbound-router>
<outbound-router>
<endpoint address="file://./outbox?outputPattern=$[MULE:ORIGINALNAME]"/>
</outbound-router>
</mule-component>
</jbi-container>
ServiceMix
<components>
<!-- Mule Reciever that looks for files in the inbox directory -->
<component id="filePoller" service="foo:filePoller"
class="org.mule.providers.jbi.components.MuleReceiver" destinationService="foo:fileSender">
<property name="workManager" ref="workManager"/>
<property name="endpoint" value="file://./inbox?pollingFrequency=1000"/>
<property name="targetServiceName" value="fileSender"/>
</component>
<!-- Mule Dispatcher that Writes files to the outbox directory -->
<component id="fileSender" service="foo:fileSender"
class="org.mule.providers.jbi.components.MuleDispatcher">
<!-- the work manager (thread pool) for this container -->
<bean id="workManager" class="org.jencks.factory.WorkManagerFactoryBean">
<property name="threadPoolSize" value="30"/>
</bean>
</beans>
Configuring Jms - A guide for configuring various JMS servers with Mule. These include ActiveMQ
JBoss MQ, Joram OpenJms, Oracle AQ, SeeBeyond, Sun JMS Grid, UberMQ, Weblogic Jms and IBM
WebSphere MQ.
Examples
Configuring Multiple Jms Clients - How to configure more than one Jms Connection in a single Mule
instance.
Configuring a Component Exception Queue - configuring a Jms error queue for your components.
Jms Provider Bridging - Moving jms messages between Jms servers from different vendors.
Spring Events - An example of how to Have you Spring Beans use Mule transports without configuring the
Mule Server. The example demonstates using JMS, Axis web services and Email.
This page descibes the specifics for setting up various Jms Servers in Mule. For more information about
all Mule Jms configuration go here.
• ActiveMQ
• JBoss MQ
• Joram
• OpenJms
• Oracle AQ
• SeeBeyond
• SonicMQ
• Sun JMS Grid
• Tibco EMS
• UberMQ
• Weblogic Jms
• IBM WebSphere MQ
• SwiftMQ
• FioranoMQ
If you have configuration for a Jms server not listed here or there is a mistake on this page please raise a
JIRA to get the document updated. Thanks.
Some JNDI implementations treat dot (.) and forward slash symbols differently in
destination names, so jms://order/incoming may not be the same as jms://order.incoming,
but the former will not give you the order/incoming destination, but incoming. If you are
dealing with such a server (JBoss is known to behave this way), here is a trick to help you:
jms:////order/incoming
For topics, add the standard prefix, so it takes the following form:
jms:////topic:order/incoming
Note: If using JBoss, remember to omit the queue/ and topic/ from the full JNDI name.
See Mule Endpoint URIs for reference. and JmsEndpointTestCase for some more examples.
The following are just examples and configuration values will change depending on your
application environment.
ActiveMQ
To configure a default embedded broker.
The specification property tells Mule to use the Jms 1.1 specification, which is the specification ActiveMQ
supports. To disable queue persistence, you'll need to specify it in ActiveMQ configuration file (see below).
To configure ActiveMQ on a specific brokerUrl or from an ActiveMQ configuration file use the following
(Spring version)
mule-config.xml
<!-- Give this container a name in case you have more than one container,
e.g. Spring, Plexus, JNDI, EJB, etc. You can safely omit it if you
don't have these requirements.
-->
<container-context className="org.mule.extras.spring.SpringContainerContext"
name="spring">
<properties>
<property name="configFile" value="classpath:/org/mule/test/activemq-spring.xml"/>
</properties>
</container-context>
activemq-spring.xml
<beans>
<bean id="activeMqConnectionFactory" class="org.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="vm://localhost"/>
<property name="brokerXmlConfig"
value="classpath:/org/mule/test/activemq-config.xml"/>
<!-- More properties you want set on ActiveMQConnectionFactory -->
</bean>
</beans>
Your ActiveMQ config is a standard one. E.g. to use in-JVM messaging without persistent queues (very
useful for testing) the file will be as follows:
activemq-config.xml
<persistence>
<vmPersistence/>
</persistence>
</broker>
</beans>
JBoss MQ
To configure a JBoss Jms connector for Mule use the following -
Any provider-specific properties can be passed to the InitialContext for this connector using the
jndiProviderProperties attribute. Use connectionFactoryProperties to set JBoss-specific properties on the
ConnectionFactory.
Connection Credentials
If you use user creditials to connect to JBossMQ 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
(i.e. in RemoteSync calls) are used.
OpenJms
The following example configuration describes how to configure a MUle JmsConnector for OpenJms.
You will probably need to change the connectionFactoryJndiName to one that is configured from your
OpenJms configuration.
UberMQ
Todo. If you are using Mule with Uber MQ please contact us with your configuration and any tips to
getting Uber MQ and Mule working together. Thanks!
WebLogic Jms
Before using Mule with Weblogic copy the weblogic.jar file to $MULE_HOME/lib/user.
Weblogic 9.x
For Weblogic 9.x the config 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.
JDK version
In case you are getting the following error when connecting to Weblogic 9.x
org.mule.MuleServer: A Fatal error has occurred while the server was running: class
weblogic.utils.classloaders.GenericClassLoader overrides final method ?.?
java.lang.VerifyError: class weblogic.utils.classloaders.GenericClassLoader overrides final
method ?.?
make sure Mule is started with JDK 5 and above, anything below will not work.
The Oracle JMS Provider extends the standard Mule Jms Provider with functionality specific to Oracle's
JMS implementation based on Advanced Queueing (Oracle AQ).
The javadoc for this transport provider can be found here. And the Source Xref can be found here.
The Oracle JMS Provider adds support for queues with ADT (Advanced Data Type) payloads, including
Oracle's native XML data type
Unlike the standard JMS Provider, the Oracle JMS Provider does not require a JNDI provider to use.
Properties
In addition to the properties available for the standard Jms Provider, the Oracle JMS Provider adds the
following properties:
The user
and
password
may be
specified
in the
URL
itself, for
example
jdbc:oracle:oci:scott/
tiger@myhost,
in which
case the
(standard
JMS
Provider)
properties
username
and
password
are not
required.
multipleSessionsPerConnection
Some versions of false no
Oracle do not support
more than one JMS
session per connection.
In this case we need to
open a new connection
Transformers
In addition to the transformers available for the standard Jms Provider, the Oracle JMS Provider adds the
following transformers, found in org.mule.vendor.oracle.jms.transformers.
Transformer Description
The default transformers are the same as the standard JMS Provider (JMSMessageToObject and
ObjectToJMSMessage).
Example Configuration
The following is an example configuration using the Oracle JMS Provider:
Endpoints
Oracle AQ endpoints are expressed in the same way as Jms endpoints except the protocol is different.
oaq://my.queue
or
oaq://topic:my.topic
You can define an Oracle AQ endpoint without declaring the connector (as shown above), by including all
necessary information on the endpoint uri i.e.
oaq://XML_QUEUE?url=jdbc:oracle:oci:scott/tiger@myhost
Refer to the unit tests for more examples on how to use the provider.
Dependencies
The Oracle JMS Provider requires the following Oracle libraries, which should be included in your Oracle
installation:
• ojdbc14.jar
• aqapi13.jar
• jmscommon.jar
• xdb.jar (only required for native XML support)
• xmlparserv2.jar (only required for native XML support)
Unit Tests
In order to run the unit tests in tests/vendor/oracle against your Oracle database, you will need to
create a JMS user "mule" and grant it AQ rights as follows.
SonicMQ
Configuration tested with versions 6.1 and 7.0.
<map name="jndiProviderProperties">
<property name="com.sonicsw.jndi.mfcontext.domain" value="Domain1"/>
<property name="java.naming.security.principal" value="Administrator"/>
<property name="java.naming.security.credentials" value="Administrator"/>
<!-- optional, default is 30sec -->
<property name="com.sonicsw.jndi.mfcontext.idleTimeout" value="5000"/>
</map>
</properties>
</connector>
SeeBeyond
The configuration provided is for the SeeBeyond ICAN IQManager JMS Server. Note the values in [ ]
(square brackets), these should be replaced by values relevant to your installation.
You will need the following jars and files from the Java ApiKit on your classpath:
• com.stc.jmsis.jar
• fscontext.jar
• providerutil.jar
• jms.jar
• jta.jar
• log4j.jar
• log4j.properties
IBM WebSphere MQ
To configure a WebSphere MQ Jms connector for Mule you will need to do the following -
Mule Configuration
The hostName property is mandatory and refers to a name that will be used for this connection. This
is different to the host property which refers to an IP address or network name of the server hosting
WebSphere MQ. Apart from the name attribute for the connector, WebSphere mandates a name property.
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
• dhbcore.jar
If you are using WAS, refer to this discussion for some known limitations.
Tibco EMS
The following demonstrates how to configure Mule to use the Tibco Enterprise Message Server (EMS) with
authentication in place.
</properties>
</connector>
For XA Transactions you will have to create an XA Connection Factory from TIBCO administration-tool
(tibemsadmin) in the following way:
Joram Jms
Using Joram with Mule is a little less straight forward that the other Jms servers if you do not have a Jndi
context set up for your connections and destinations. If you have Jndi set up you can use the following-
Durable Subscribers
When using durable subscribers Mule automatically sets the Jms clientId on the connection,
if not explicitly set. Joram complains if the clientId is set, so you need to tell Mule not to set
it by setting the clientId on the JmsConnector to "".
If you do not have Jndi set up you need to manually create a Jndi Initial Context. You can do this by
adding a Mule property factory (like the one listed below). Your configuration will look something like -
The Jndi property factory class will look like the following, though you may want to add support for other
Joram properties.
JoramInitialContextFactory.java
FioranoMQ
• 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:
<endpoint address="jms://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.
The specification property tells Mule to use the Jms 1.1 specification, which is the specification ActiveMQ
supports. To disable queue persistence, you'll need to specify it in ActiveMQ configuration file (see below).
To configure ActiveMQ on a specific brokerUrl or from an ActiveMQ configuration file use the following
(Spring version)
mule-config.xml
<!-- Give this container a name in case you have more than one container,
e.g. Spring, Plexus, JNDI, EJB, etc. You can safely omit it if you
don't have these requirements.
-->
<container-context className="org.mule.extras.spring.SpringContainerContext"
name="spring">
<properties>
<property name="configFile" value="classpath:/org/mule/test/activemq-spring.xml"/>
</properties>
</container-context>
activemq-spring.xml
<beans>
<bean id="activeMqConnectionFactory" class="org.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="vm://localhost"/>
Your ActiveMQ config is a standard one. E.g. to use in-JVM messaging without persistent queues (very
useful for testing) the file will be as follows:
activemq-config.xml
<beans>
<broker>
<connector>
<serverTransport uri="vm://localhost"/>
</connector>
<persistence>
<vmPersistence/>
</persistence>
</broker>
</beans>
Many thanks to Ed Narayanan for submitting the following configuration info. for Mule!
• 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:
<endpoint address="jms://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:
Copy swiftmq.jar into Mule's "lib/user" directory and start the SwiftMQ Router. Now you can use SwiftMQ
from Mule.
The only change necessary in both example configuration files loan-broker-esb-mule-config.xml and loan-
broker-esb-mule-config-container.xml is the JMS connector. With a SwiftMQ Router running on the local
host it is:
The LoanBroker 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 we 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 LoanBroker ESB example's JMS queue names, we 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>
That's it! The LoanBroker ESB example must be rebuild with Ant or Maven in order that the configuration
changes take effect. Then start the SwiftMQ Router and the LoanBroker ESB example.
The @ sign can be escaped with the %40 in Mule URI so for an alternate configuration you can use the
following:
<endpoint-identifiers>
<endpoint-identifier name="LoanBrokerRequestsREST" value="jetty:rest://localhost:8080/loanbroker"/>
<endpoint-identifier name="LoanBrokerRequests" value="vm://loan.broker.requests"/>
<endpoint-identifier name="LoanQuotes" value="jms://esb_loan_quotes%40router1"/>
<endpoint-identifier name="CreditAgencyGateway" value="jms://esb_credit_agency%40router1"/>
<!-- here we're telling Mule to invoke a remote Ejb directly (not host a
proxy service for the remote object as with the other example in mule-config-with-ejb-
container.xml example)
-->
<endpoint-identifier name="CreditAgency" value="ejb://localhost:1099/local/CreditAgency?
method=getCreditProfile"/>
<endpoint-identifier name="LenderGateway" value="jms://esb_lender_service%40router1"/>
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 recommended to avoid physical queue
names.
Any provider-specific properties can be passed to the InitialContext for this connector using the
jndiProviderProperties attribute. Use connectionFactoryProperties to set JBoss-specific properties on the
ConnectionFactory.
Connection Credentials
If you use user creditials to connect to JBossMQ 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
(i.e. in RemoteSync calls) are used.
The following example configuration describes how to configure a MUle JmsConnector for OpenJms.
You will probably need to change the connectionFactoryJndiName to one that is configured from your
OpenJms configuration.
There are some tricks to getting Oracle AQ working with Mule because the AQ implementation veers from
the Jms specification when creating Connection Factories. The big difference is that Oracle uses a db-
centric queue model meaning that really when you create a Connection you are creating a Oracle Jdbc
connection. This connector will let Mule talk via the Jms API to a queue in an oracle database without
using Jndi. (oracle standard edition disables exporting a queue to a repository).
This connector can be used to send a jms message when table data changes.
The Oracle JMS Provider extends the standard Mule Jms Provider with functionality specific to Oracle's
JMS implementation based on Advanced Queueing (Oracle AQ).
The javadoc for this transport provider can be found here. And the Source Xref can be found here.
The Oracle JMS Provider adds support for queues with ADT (Advanced Data Type) payloads, including
Oracle's native XML data type
Unlike the standard JMS Provider, the Oracle JMS Provider does not require a JNDI provider to use.
Properties
In addition to the properties available for the standard Jms Provider, the Oracle JMS Provider adds the
following properties:
The user
and
password
may be
specified
in the
URL
itself, for
example
jdbc:oracle:oci:scott/
tiger@myhost,
in which
case the
(standard
JMS
Provider)
properties
username
and
password
are not
required.
Transformers
In addition to the transformers available for the standard Jms Provider, the Oracle JMS Provider adds the
following transformers, found in org.mule.vendor.oracle.jms.transformers.
Transformer Description
The default transformers are the same as the standard JMS Provider (JMSMessageToObject and
ObjectToJMSMessage).
Example Configuration
The following is an example configuration using the Oracle JMS Provider:
Endpoints
Oracle AQ endpoints are expressed in the same way as Jms endpoints except the protocol is different.
oaq://my.queue
or
oaq://topic:my.topic
You can define an Oracle AQ endpoint without declaring the connector (as shown above), by including all
necessary information on the endpoint uri i.e.
oaq://XML_QUEUE?url=jdbc:oracle:oci:scott/tiger@myhost
Refer to the unit tests for more examples on how to use the provider.
Dependencies
The Oracle JMS Provider requires the following Oracle libraries, which should be included in your Oracle
installation:
• ojdbc14.jar
• aqapi13.jar
• jmscommon.jar
• xdb.jar (only required for native XML support)
• xmlparserv2.jar (only required for native XML support)
Unit Tests
In order to run the unit tests in tests/vendor/oracle against your Oracle database, you will need to
create a JMS user "mule" and grant it AQ rights as follows.
The configuration provided is for the SeeBeyond ICAN IQManager JMS Server. Note the values in [ ]
(square brackets), these should be replaced by values relevant to your installation.
You will need the following jars and files from the Java ApiKit on your classpath:
• com.stc.jmsis.jar
• fscontext.jar
• providerutil.jar
• jms.jar
• jta.jar
• log4j.jar
• log4j.properties
<map name="jndiProviderProperties">
<property name="com.sonicsw.jndi.mfcontext.domain" value="Domain1"/>
<property name="java.naming.security.principal" value="Administrator"/>
<property name="java.naming.security.credentials" value="Administrator"/>
<!-- optional, default is 30sec -->
<property name="com.sonicsw.jndi.mfcontext.idleTimeout" value="5000"/>
</map>
</properties>
</connector>
The following demonstrates how to configure Mule to use the Sun JMS Grid server.
The following demonstrates how to configure Mule to use the Tibco Enterprise Message Server (EMS) with
authentication in place.
</properties>
</connector>
For XA Transactions you will have to create an XA Connection Factory from TIBCO administration-tool
(tibemsadmin) in the following way:
Before using Mule with Weblogic copy the weblogic.jar file to $MULE_HOME/lib/user.
Weblogic 9.x
For Weblogic 9.x the config 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.
JDK version
In case you are getting the following error when connecting to Weblogic 9.x
org.mule.MuleServer: A Fatal error has occurred while the server was running: class
weblogic.utils.classloaders.GenericClassLoader overrides final method ?.?
java.lang.VerifyError: class weblogic.utils.classloaders.GenericClassLoader overrides final
method ?.?
make sure Mule is started with JDK 5 and above, anything below will not work.
To configure a WebSphere MQ Jms connector for Mule you will need to do the following -
Mule Configuration
The hostName property is mandatory and refers to a name that will be used for this connection. This
is different to the host property which refers to an IP address or network name of the server hosting
WebSphere MQ. Apart from the name attribute for the connector, WebSphere mandates a name property.
If you're using IBM's connection factory, you may additionally need the following configuration - the
connection factory is configured in Spring here:
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
• com.ibm.mq.jar
• com.ibm.mqjms.jar
• connector.jar
• dhbcore.jar
If you are using WAS, refer to this discussion for some known limitations.
<agents>
<agent name="JmxAgent" className="org.mule.management.agents.JmxAgent"/>
</agents>
domain The JMX domain for this Mule Mule.<Mule ID> from XML
server (no longer available since config or an autogenerated
Mule 1.3) Mule.<UUID> otherwise
Remote Management
It's also possible to configure the Mule JMX subsystem for remote management with 3rd-party tools like
MC4J:
<agents>
<!-- starts an RMI registry on the default port 1099. -->
If you are using JDK1.4 and running the RMI Registry externally using rmiregistry.exe (Bundled with
JDK 1.4) you will need to add the JMX remoting Jar to your JDK classpath in order for the external RMI
registry to serve Remote JMX clients.
This isn't an issue if running with JDK 1.5 as the JMX remoting classes are now part of the JDK.
Mx4j Configuration
<agents>
<agent name="JmxAgent" className="org.mule.management.agents.JmxAgent"/>
<agent name="Mx4jAgent" className="org.mule.management.agents.Mx4jAgent">
<properties>
<property name="jmxAdaptorUrl" value="http://localhost:9999"/>
</properties>
</agent>
</agents>
http://localhost:9999 _is the default URL and can be ommitted if there's no need to change it._
For security's sake, the management console is only accesible from the localhost. If you
wish to loosen this restriction, change "localhost" to "0.0.0.0". This will allow access from
any machine in the LAN. Refer to the MX4J docs for more details.
Mx4j Security
As of Mule 1.3 it is possible to protect the JMX web console with a login and password. If the login
property has been specified, the protection scheme kicks in:
<agents>
<agent name="jmxAgent" className="org.mule.management.agents.JmxAgent"/>
<agent name="mx4jAgent" className="org.mule.management.agents.Mx4jAgent">
<properties>
<property name="login" value="user"/>
<agents>
<agent name="jmxAgent" className="org.mule.management.agents.JmxAgent"/>
<agent name="mx4jAgent" className="org.mule.management.agents.Mx4jAgent">
<properties>
<map name="socketFactoryProperties">
<property name="keyStoreName" value="serverKeystore"/>
<property name="keyStorePassword" value="mulepassword"/>
</map>
</properties>
</agent>
</agents>
The above config protects the data in transit, while still allowing anybody to access the
console. It is recommended both approaches are combined for tighter control over the
environment.
If socketFactoryProperties contains at least one entry, the agent will switch to HTTPS connections.
The jmxAdaptorUrl scheme is not important here, the choice of either HTTP or HTTPS will
be made based on the availability of the socketFactoryProperties map. If this config is
omitted, it will always use HTTP, even if you specify https:// connection scheme in the
jmxAdaptorUrl property.
Viewing Statistics
Mule traps many different statistics about the running state of a server and number of events processed.
With the JMX Management Console you can view the Mule statistics report. To view the statistics report
shown below using the above configuration go to the following url -
http://localhost:9999/
then click on any JMX domain name (except for JMImplementation), or go to 'Statistics' tab and query
JMX domain for statistics from there -
Log4J Agent
The log4j Agent exposes the configuration of the Log4J instance used by Mule for Jmx management.
<agents>
<agent name="JmxAgent" className="org.mule.management.agents.JmxAgent"/>
<agent name="Log4jAgent" className="org.mule.management.agents.Log4jAgent"/>
</agents>
All Jmx Agents can be used together if desired and you can register your own custom ones
as well. Just ensure the org.mule.management.agents.JmxAgent is registered.
Starting with Mule 1.4, the following properties can be additionally customized:
The agent does a lot of useful plumbing for JMX, however at the expense of defaulting many parameters.
If you find a need to customize some subsystems you could either:
Starting with Mule 1.4, the following properties can be additionally customized:
• port - the port to run RMI registry on, also used for remote JMX management (defaults to 1099)
• host - host to bind to. Normally one would override this only for multi-NIC servers (defaults to
localhost)
• credentials - a Map of username/password properties for remote JMX access. The configuration
option delegates to the JmxAgent, consult its documentation for more details.
The agent does a lot of useful plumbing for JMX, however at the expense of defaulting many parameters.
If you find a need to customize some subsystems you could either:
Jdmk Configuration
<agents>
<agent name="JmxAgent" className="org.mule.management.agents.JmxAgent"/>
<agent name="JdmkAgent" className="org.mule.management.agents.JdmkAgent">
<properties>
<property name="jmxAdaptorUrl" value="http://localhost:9998"/>
</properties>
</agent>
</agents>
Message routers are used to control how events are sent and received by components in the system.
Mule defines Inbound routers that apply to events as they are received and outbound routers that are
invoked when an event is being dispatched.
Quick Reference
Aggregator Multicasting
Router
Filtering Xml
Message Splitter
Exception Based
Router
Message Chunking
Router
Mule provides flexible message routing support for your components. Routing features are based on the
enterprise routing requirements described in EIP.
There are a few elements to Mule's routing system -
Inbound Routers
A single event is received via a endpoint and the router controls how and if this event gets routed into the
system.
Outbound Routers
Once a message has been processed by a component and outbound router can used to determine which
components get the result event.
Response Routers
Are used in request/response scenarios where event traffic is triggered by a request and the traffic needs
to be consolidated before a response is given. The classic example of this is where a request is made
and tasks are executed in parallel. Each task must finish executing and the results processed before a
response can be sent back to the callee.
Filters provide the logic by which to invoke a particular router. An example would be the XPathFilter, or
PayloadTypeFilter. 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 Filters for information.
CatchAll Strategies
A catch all strategy can be configured on a router and will be invoked if no routing path can be found for
the current event. A endpoint can be associated with a catch all strategy so that any events that 'slip
through the net' can be caught and routed to a common location.
Configuring Routers
Inbound Router configuration
Inbound routers can be used to control and manipulate events received by a component. Typically, an
inbound router can be used to filter incoming event, aggregate a set of incoming events or re-sequence
events when they are received. Inbound routers are also used to register multiple inbound endpoints for
a component. You can chain inbound routers together, in this scenario each router is matched before the
event is dispatched to a mule component. Inbound routers are different to outbound routers in that the
endpoint is already known (as the message has already been recieved) so the purpose of the router is
to control how messages are given to the component. You can specify a catch-all strategy which will be
invoked if any of the routers do not accept the current event. An Inbound Router can be configured on a
mule-descriptor element in the mule-config.xml -
<inbound-router>
<catch-all-strategy className="org.mule.routing.ForwardingCatchAllStrategy">
<endpoint address="jms://failure.queue"/>
</catch-all-strategy>
<router className="org.mule.routing.inbound.SelectiveConsumer">
<filter expression="(msg/header/resultcode)='success'"
className="org.mule.routing.filters.xml.JXPathFilter"/>
</router>
</inbound-router>
There is router configured for this inbound-router. The first is a selective consumer and will accept the
event if a nested field in the payload is set to resultcode='success'. If this filter matches, the event will be
passed to the component. If either router does not match the Catch all strategy is invoked, which sends
all events via its configured endpoint endpoint, in this case a jms queue called 'failure.queue'.
<outbound-router>
<catch-all-strategy className="org.mule.routing.ForwardingCatchAllStrategy">
<endpoint address="jms://default.queue"/>
</catch-all-strategy>
<router className="org.mule.routing.outbound.FilteringOutboundRouter">
<endpoint address="smtp://exceptions@muleumo.org" transformers="ExceptionToEmail">
<properties>
<property name="subject" value="Exception!"/>
<property name="fromAddress" value="mule@mycompany.com!"/>
</properties>
</endpoint>
<filter expectedType="java.lang.Exception"
</filter>
</router>
</outbound-router>
This outbound router defines two routers. The first checks to see if the payload type is
java.lang.exception, and end the messge via the endpoint; in this case over smtp to
exceptions@muleumo.org. There is a transformer on this endpoint ExceptionToEmail which will convert
the exception into a javax.mail.Message before sending the event. Note the properties on the endpoint,
these will be used to override the Smtp Connector behaviour for this endpoint instance. If the event
payload is not an Exception, the second router is invoked which checks to see if the payload type is String
and then also checks that the payload matches a regular expression. If both filters match the event is
routed to a component listening on vm://my.component. If neither routers match the Catch all strategy is
invoked which sends all events to a jms queue called 'default queue'.
It is possible to configure an outbound router to invoke all of the matching routers, rather than just the
first. For example, in the situation where you always want to send a confirmation of a deposit back to the
original depositor, and, if the deposit was above $100,000, send a notification message to the 'high net
worth client manager' for possible follow-up, you can utilise the matchAll property on the router definition
as follows:
<outbound-router matchAll="true">
<router className="org.mule.routing.outbound.FilteringOutboundRouter">
<endpoint address="jms://deposit.queue"/>
</router>
<router className="org.mule.routing.outbound.FilteringOutboundRouter">
<endpoint address="endpoints="jms://large.deposit.queue"/>
<filter expression="deposit/amount >= 100000"
className="org.mule.routing.filters.xml.JXPathFilter"/>
</router>
</router>
</outbound-router>
Here, the first router will always match as there is no filter on it and the second router will only match of
the deposit amount is >= $100000 - if this is the case then both routers will be invoked.
<response-router>
<endpoint address="jms://bank.quotes"/>
<router className="org.mule.samples.loanbroker.routers.BankQuotesResponseAggregator"/>
</response-router>
The endpoint is the address that responses should be sent to be processed. The router in this case is
responsible for aggregating Bank quotes into a single quote for the customer. Consider the LoanBroker
component configuration below-
<mule-descriptor name="LoanBroker"
<outbound-router>
<router className="org.mule.routing.outbound.StaticRecipientList">
<reply-to address="jms://Loan.Quotes"/>
<filter expression="recipients!=null"
className="org.mule.routing.filters.MessagePropertyFilter"/>
</router>
</outbound-router>
<response-router>
<endpoint address="jms://Loan.Quotes"/>
<router className="org.mule.samples.loanbroker.routers.BankQuotesResponseAggregator"/>
</response-router>
</mule-descriptor>
Don't worry too much about the filters and routers as these are described in detail below. What this
configuration demonstrates is that our 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' that is a property on the outbound message (See the Loan Broker Example for
more information). The important setting on the outbound router is the <reply-to> endpoint, this tells
Mule to route all responses to the jms://Loan.Quotes endpoint which is the endpoint that the response
router is listening on. When all responses are received the BankQuotesResponseAggregator selects the
cheapest quotes and returns it. Mule then handles returning this back to the callee. The <reply-to>
Endpoint is applied to the next component invoked, i.e. 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.
Response Transformers
Sometimes you will want to transform response event without doing any other work on the response. To
do this just set the transformers attribute on the response router without any other routing configuration.
Next, the Nested Router is used to bind the aforementioned interface to the external service.
Note that the call to the external service is synchronous because component workflow is blocked until
the call is finished. Consequently the endpoint bound to the interface should be synchronous (for VM
transport "synchronous" attribute should be used instead of "remoteSync").
Idempotent Receiver
An IdempotentReceiver is an Inbound router that ensures only unique messages are received by a
component. It ensures that each message is unique by checking and storing the unique id of each
message it receives. Note that this unique id often comes from the underlying technology and that some
endpoints do not support unique ids. If the endpoint being used doesn't support unique ids an exception
will be thrown.
Configuration
<inbound-router>
<router className="org.mule.routing.inbound.IdempotentReceiver">
<properties>
<property name="disablePersistence" value="false"/>
<property name="storePath" value="./idempotent"/>
</properties>
</router>
</inbound-router>
disablePersistence - Determines whether received message ids are stored to disk so that the router can
remember state between restarts. The default value is false;
storePath - Determines where to store the received ids file. The mule working directory is set in the
Muleconfiguration.setWorkingDir(...). The default working directory for is ./.mule. The file created will
be in the form of muleComponent_<componentName>. The default value for this property is ./.mule/
idempotent/.
Selective Consumer
A selective consumer is an Inbound Router that can apply one or more filters to the incoming event
payload. If the filters match the event will get forwarded to the component otherwise the event will get
Configuration
<inbound-router>
<catch-all-strategy className="org.mule.routing.ForwardingCatchAllStrategy">
<endpoint address="jms://topic:error.topic"/>
</catch-all-strategy>
<router className="org.mule.routing.inbound.SelectiveConsumer">
<filter expression="msg/header/resultcode = 'success'"
className="org.mule.routing.filters.xml.JXPathFilter"/>
</router>
</inbound-router>
There are no properties associated with this router, however see Filters for more information about the
how filters can be used and what filters are available.
Note that by default the filter is applied to the event payload after the transformers configured for the
inbound endpoint are applied to the event. There may be situations where the developer may need
to execute filters on the event payload without any transformation being applied. You can set the
transformFirst property on this router to control if transformations are applied.
<inbound-router>
<catch-all-strategy className="org.mule.routing.ForwardingCatchAllStrategy">
<endpoint address="jms://topic:error.topic"/>
</catch-all-strategy>
<router className="org.mule.routing.inbound.SelectiveConsumer">
<filter expression="msg/header/resultcode = 'success'"
className="org.mule.routing.filters.xml.JXPathFilter"/>
<properties>
<property name="transformFirst" value="false"/>
</properties>
</router>
</inbound-router>
Aggregator
The Aggregator pattern stipulates that two or more messages are combined into a single result message.
Mule provides an abstract implementation that has a template method that actually does 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 filters can also be applied to messages.
Configuration
<inbound-router>
<router className="org.mule.routing.inbound.CorrelationAggregator">
<filter expectedType="org.foo.some.Object"
className="org.mule.routing.filters.PayloadTypeFilter"/>
</router>
</inbound-router>
The CorrelationAggregator can be used to match messages with a given CorrelationId. Correlation
Ids are set on messages when they are dispatched for certain outbound routers such as the Recipient
List and Message Splitter routers. These messages can be aggregated back together again using the
CorrelationAggregator router.
You can easily write custom Aggregator routers to aggregate on some other criteria if your messages.
There is an AbstractEventAggregator that provides a thread-safe implementation for custom Aggregators.
Configuration
<inbound-router>
<router className="org.mule.routing.foo.SimpleEventResequencer">
<filter expression="msg/header/resultcode = 'success'"
className="org.mule.routing.filters.xml.JXPathFilter"/>
<properties>
<property name="comparator"
value="org.mule.routing.foo.EventPayloadComparator"/>
<property name="eventThreshold" value="5"/>
</properties>
</router>
</inbound-router>
The EventPayloadComparator is used to re-order the events. If a comparator is not set the events will not
be resequenced.
There is also a CorrelationEventResequencer that will reseguence a group of messages (grouped by their
correlation Id) depending on the order the messages were sent. This is useful where you configure a
Message Splitter to send out multiple events and then you want to process all the split message parts in a
particular order.
<inbound-router>
<router className="org.mule.routing.inbound.CorrelationEventResequencer"/>
</inbound-router>
There is no need for any further configuration as the router uses standard properties on the
MuleMessage.
Forwarding Consumer
This router allows for events to be forwarded to an outbound endpoint without first being processed by a
component. It essentially acts as a bridge between an inbound and an outbound endpoint. This is useful
in situations where the developer does not need to execute any logic on the inbound event but does need
to foward it on to a component residing on another destination (i.e. a remote Mule node or application)
over the network.
Configuration
<mule-descriptor name="FileReader"
inboundEndpoint="file:///temp/myfiles/in"
outboundTransformer="ObjectToByteArray"
outboundEndpoint="tcp://192.168.0.6:12345"
implementation="org.mule.components.simple.NullComponent">
<inbound-router>
<router className="org.mule.routing.inbound.ForwardingConsumer"/>
</inbound-router>
</mule-descriptor>
When the event is triggered by a file on the local file system becoming availiable the event is
automatically forwarded via tcp to 192.168.0.6. Notice that there is a outboundTransfrmer configured.
This will be used to transform the event's payload before it is dispatched over tcp. Also, the
implementation of this component is the NullComponent. This component doesn't do anything as is just
acts as a place holder. However, you could mix and match the routers so that some events are forwarded
while others are processed by the component.
BridgeComponent
As of Mule 1.1 the Forwarding consumer can be automatically configured using the BridgeComponent.
This is a component that automatically configures the Forwarding consumer and replaces the need for the
NullComponent in the above example. The same example using the the BridgeComponent would look like
-
<mule-descriptor name="FileReader"
inboundEndpoint="file:///temp/myfiles/in"
outboundTransformer="ObjectToByteArray"
outboundEndpoint="tcp://192.168.0.6:12345"
implementation="org.mule.components.simple.BridgeComponent">
</mule-descriptor>
All Mule outbound routers extend FilteringOutboundRouter which means you can always apply a filter to
an outbound router. A notable exception is the OutboundPassThroughRouter, which obviously does not
allow filters.
Configuration
<outbound-router>
<catch-all-strategy className="org.mule.routing.ForwardingCatchAllStrategy">
<endpoint="jms://error.queue"/>
</catch-all-strategy>
<router className="org.mule.routing.outbound.FilteringOutboundRouter">
<endpoint address="smtp://ross@muleumo.org"/>
<filter expectedType="java.lang.Exception"
className="org.mule.routing.filters.PayloadTypeFilter"/>
</router>
<router className="org.mule.routing.outbound.FilteringOutboundRouter">
<endpoint address="jms://string.queue"/>
<filter className="org.mule.routing.filters.logic.AndFilter">
<left-filter expectedType="java.lang.String"
className="org.mule.routing.filters.PayloadTypeFilter"/>
<right-filter pattern="the quick brown (.*)"
className="org.mule.routing.filters.RegExFilter"/>
</filter>
</router>
</outbound-router>
<outbound-router>
<router className="org.mule.routing.outbound.FilteringOutboundRouter">
<endpoint address="smtp://ross@muleumo.org"/>
<filter expectedType="java.lang.Exception"
className="org.mule.routing.filters.PayloadTypeFilter"/>
<properties>
<property name="transformer" value="aTransformer"/>
</properties>
</router>
</outbound-router>
Recipient List
the Recipient list router can be used to send the same event to multiple endpoints over the same
endpoint or to implement routing-slip behaviour where the next destination for the event is determined
from the event properties or payload. Mule provides an abstract Recipient list implementation
org.mule.routing.outbound.AbstractRecipientList that provides a thread-safe base for specialised
implementations. Mule also provides a Static recipient list that takes a configured list of endpoints from
the current event or statically declared on the endpoint.
Configuration
<outbound-router>
<router className="org.mule.routing.outbound.StaticRecipientList">
<filter expectedType="javax.jms.Message"
className="org.mule.routing.filters.PayloadTypeFilter"/>
<properties>
<list name="recipients">
<entry value="jms://orders.queue"/>
<entry value="jms://tracking.queue"/>
</list>
</properties>
</router>
</outbound-router>
ReplyTo
You can use the reply-to endpoint of the outbound router to ensure all messages sent got sent back to
the same destination.
<outbound-router>
<router className="org.mule.routing.outbound.StaticRecipientList">
<reply-to address="vm://component4"/>
<filter expectedType="javax.jms.Message"
className="org.mule.routing.filters.PayloadTypeFilter"/>
<properties>
<list name="recipients">
<entry value="jms://orders.queue"/>
<entry value="jms://tracking.queue"/>
</list>
</property>
</router>
</outbound-router>
This configuration will first check that the payload type is a Jms Message and will then send the message
to the orders.queue and tracking.queue.
Configuration
<outbound-router>
<router className="org.mule.routing.outbound.MulticastingRouter">
<endpoint address="jms://test.queue" transformers="StringToJmsMessage"/>
<endpoint address="http://10.192.111.11" transformers="StringToHttpClientRequest"/>
<endpoint address="tcp://10.192.111.12" transformers="StringToByteArray"/>
<filter expectedType="java.lang.String"
className="org.mule.routing.filters.PayloadTypeFilter"/>
</router>
</outbound-router>
Remember that care should be taken to ensure that the message being routed is transformed to a format
that the endpoint understands.
ReplyTo
Again, you can use the reply-to property of the outbound router to ensure all messages sent got sent
back to the same destination.
<outbound-router>
<router className="org.mule.routing.outbound.MulticastingRouter">
<endpoint address="jms://test.queue" transformers="StringToJmsMessage"/>
<endpoint address="http://10.192.111.11" transformers="StringToHttpClientRequest"/>
<endpoint address="tcp://10.192.111.12" transformers="StringToByteArray"/>
<reply-to address="vm://component4"/>
<filter expectedType="java.lang.String"
className="org.mule.routing.filters.PayloadTypeFilter"/>
</router>
</outbound-router>
Configuration
<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>
Message Splitter
A message splitter can be used to breakdown an outgoing message into parts and dispatch those
parts over different endpoints configured on the router. Mule provides an abstract implementation of
Configuration
<outbound-router>
<router className="org.foo.ConcreteMessageSplitter">
<endpoint address="vm://component1"/>
<endpoint address="vm://component2"/>
<endpoint address="vm://component3"/>
</router>
</outbound-router>
Note as with all router configurations you can define properties elements to set bean properties on the
router. For example, you may want to define a list of XPath expressions that would be used to extract the
different message parts. See Configuring Properties for more information.
By default the AbstractMessageSplitter sets a Correlation Id and Correlation Sequence to the outbound
events so that inbound routers such as the Aggregator or Resequencer are able to resequence or combine
the split messages.
ReplyTo
You can use the reply-to property of the outbound router to ensure all messages sent got sent back to
the same destination.
<outbound-router>
<router className="org.foo.ConcreteMessageSplitter">
<endpoint address="vm://component1"/>
<endpoint address="vm://component2"/>
<endpoint address="vm://component3"/>
<reply-to address="vm://component4"/>
</router>
</outbound-router>
The router configuration below expects the message payload to be a java.util.List and will route objects
in the list that are of type com.foo.Order, com.foo.Item and com.foo.Customer. The router will allow any
number and combination of these objects.
Configuration
<outbound-router>
<router className="org.mule.routing.outbound.FilteringListMessageSplitter">
<endpoint address="jms://order.queue">
<filter expectedType="com.foo.Order" className="org.mule.routing.filters.PayloadTypeFilter"/>
</endpoint>
<endpoint address="jms://item.queue">
<filter expectedType="com.foo.Item" className="org.mule.routing.filters.PayloadTypeFilter"/>
</endpoint>
<endpoint address="jms://customer.queue">
<filter expectedType="com.foo.Customer" className="org.mule.routing.filters.PayloadTypeFilter"/>
</endpoint>
<filter expectedType="java.util.List" className="org.mule.routing.filters.PayloadTypeFilter"/>
</router>
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
will be written to the log and processing will continue. To route any non-matching object types to another
endpoint just add the endpoint at the end of the list without a filter.
• org.dom4j.Document objects
• byte[]
• java.lang.String
The router will split 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.
The router can optionally perform a validation against an external XML Schema document. Point
externalSchemaLocation to XSD file in your classpath. Note in this case you override whatever schema
document you declare in XML header.
Configuration
<outbound-router>
<router className="org.mule.routing.outbound.FilteringXmlMessageSplitter">
<endpoint address="vm://order">
<filter expectedType="com.foo.Order" className="org.mule.routing.filters.PayloadTypeFilter"/>
</endpoint>
<endpoint address="vm://item">
<filter expectedType="com.foo.Item" className="org.mule.routing.filters.PayloadTypeFilter"/>
</endpoint>
<endpoint address="vm://customer">
<filter expectedType="com.foo.Customer" className="org.mule.routing.filters.PayloadTypeFilter"/>
</endpoint>
<filter expectedType="org.dom4j.Document" className="org.mule.routing.filters.PayloadTypeFilter"/>
<properties>
<property name="splitExpression" value="/root/nodes"/>
<property name="validateSchema" value="true"/>
<property name="externalSchemaLocation" value="/com/example/TheSchema.xsd"/>
</properties>
</router>
</outbound-router>
Chaining Router
The Chaining router can be used to send the event through multiple endpoints using the result of the
first invocation as the input for the next. This can be useful where you want to send the results of a
synchronous request-response invocation, say, a Web Services call, to a jms queue.
Configuration
<outbound-router>
<router className="org.mule.routing.outbound.ChainingRouter">
<endpoint address="axis:http://localhost:8081/services/xyz?
method=getSomething"/>
All outbound routers can have a <reply-to> endpoint that defines where the event should be routed to
after the recipient of the event being dispatched has finished with it. The <reply-to> Endpoint is applied
to the next component invoked, i.e. 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 will be sent with the outgoing message.
If the underlying transport supports the notion of replyTo, such as Jms, this will be utilised for replyTo
endpoints that use Jms.
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 chunkSize that you configure for the router. If you configure a chunkSize of zero, then
the entire message will not be split up and 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.
You would use this mechanism 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 Message Splitter router instead.
The destination needs to know how to put these items back together again - typically, you would use a
Message Chunking Aggregator inbound router for this.
Sample Configuration
<mule-descriptor name="chunkingService"
implementation="org.mule.components.simple.BridgeComponent">
<inbound-router>
<endpoint address="vm://fromClient"/>
</inbound-router>
<outbound-router>
<router className="org.mule.routing.outbound.MessageChunkingRouter">
<endpoint address="vm://toClient"/>
<properties>
<property name="chunkSize" value="4"/>
</properties>
</router>
</outbound-router>
</mule-descriptor>
In the example above, any data received on the vm://fromClient is chunked into messages 4 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 vm://toClient will receive the following messages (The
spaces have been replaced with underscore signs for ease of reading):
Message # Contents
1 The_
2 quic
3 k_br
4 own_
5 fox_
6 jump
7 ed_o
8 ver_
9 the_
10 lazy
Properties
Name Description
If you wish to copy all messages that are sent to a specific component, you just need to set the endpoint
property of the WireTap router:
<inbound-router>
<endpoint address="vm://FromUser"/>
<router className="org.mule.routing.inbound.WireTap">
<properties>
<property name="endpoint" value= "vm://tapped.channel"/>
</properties>
</router>
</inbound-router>
In the following scenario, I am merely copying any data from the inbound VM channel to the outbound
endpoint using a BridgeComponent. However, I wish to forward some of the input based upon a filter
to another component called WireTapReceiver. For simplicities' sake, I have coded this component to do
nothing more than pre-pend the message with "INTERCEPTED:" before sending it to the FromTapper VM
channel. The code for the WireTapReceiver is as follows:
<description>
Experiment to demonstrate how the wiretap router works
</description>
<connector name="vmQueue" className="org.mule.providers.vm.VMConnector">
<properties>
<property name="queueEvents" value="true"/>
</properties>
</connector>
<model name="default">
<mule-descriptor name="StdComp" implementation="org.mule.components.simple.BridgeComponent">
<inbound-router>
<endpoint address="vm://In"/>
<router className="org.mule.routing.inbound.WireTap">
<properties>
Using Filters
The StdComp component receives events from the In endpoint. The router passes the event to the
component and copies it to the vm://ToTapper endpoint too. The WireTapper component listens on this
channel and forwards the event, after processing, to the FromTapper endpoint.
The WireTap router is based upon the SelectiveConsumer router and it therefore can take filters. In this
example, only messages that match the filter expression are copied to the vm://ToTapper endpoint
<router className="org.mule.routing.inbound.WireTap">
<filter className="org.mule.routing.filters.WildcardFilter" pattern="the quick brown*"/>
<properties>
<property name="endpoint" value="vm://tapped.channel"/>
</properties>
</router>
Any filter that can be used with the SelectiveConsumer router can be used here too.
Multiple WireTapping
You can also have multiple WireTap routers, for the same component:
<inbound-router>
<endpoint address="vm://In"/>
<router className="org.mule.routing.inbound.WireTap">
<filter className="org.mule.routing.filters.WildcardFilter" pattern="the quick brown*"/>
<properties>
<property name="endpoint" value="vm://ToTapper"/>
</properties>
</router>
<router className="org.mule.routing.inbound.WireTap">
<filter className="org.mule.routing.filters.WildcardFilter" pattern="*the slow green*"/>
<properties>
<property name="endpoint" value="vm://ToOtherTapper"/>
</properties>
</router>
</inbound-router>
As you can see input is passed to the component and also copied to one of two destinations depending on
the filter.
If you are calling the endpoint with a specified method to invoke, for instance, if:
The web service and its method foo() can be invoked via:
• http\://localhost\:8080/services/StdComp?method=foo¶m=bar
When this event is wiretapped to the receiving component (in our first example, the component of
org.ricston.experiments.WireTapReceiver), Mule might fail with a ComponentException as the
receiving component might not have the method foo().
To avoid this and to ensure that the desired method is invoked, you will have to overwrite the method of
the event, by specifying:
• ?method=methodName, or,
• ?method=, so that the onCall() will be called instead
For instance,
<router className="org.mule.routing.inbound.WireTap">
<properties>
<property name="endpoint" value="vm://inboundEndpoint3?connector=vm2"></property>
...
<mule-descriptor name="serviceComponent3" implementation="org.mule.components.simple.LogComponent">
<inbound-router>
<endpoint address="vm://inboundEndpoint3?connector=vm2&method=" synchronous="false"/>
</inbound-router>
Features
• Transactions are supported so the forwarding of events can either start or join a transaction
provided that the endpoint supports transactions.
• Reply-To can be used to route replies from this endpoint.
• The container-property, factory-property, file-property, list, map, system-property and text-property
tags can all be used.
Uses
The Wiretap router is useful both with and without filtering. If filtered, it can be used to record or take
note of particular events or to copy events that require additional processing to a different component. If
filters aren't used, you can take a backup copy of all events received by a component. The behaviour 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.
References
http://svn.mule.codehaus.org/browse/mule/trunk/mule/tests/integration/src/test/resources/org/mule/
test/integration/routing/wire-tap.xml?r=3468
http://mule.mulesource.org/wiki/display/MULE/Message+Routers
Mule Models
A Mule model manages the runtime behaviour 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. By default, Mule uses the SEDA model but it ships with a number of other models too.
You can indicate which model to use for your components by using the type attribute in the <model>
tags. You can also have multiple models within a single Mule instance.
• Name - This is a string value that refers to the name of the model and is set as an attribute within
the <model> tags. It is required when multiple models exist in a single configuration file.
• EntryPointResolver - This refers to a class that implements the UMOEntryPointResolver interface.
This class will be used to determine the entry point for any hosted component when a message is
received.
• ExceptionListener - The exception strategy to use for the entire model. The exception strategy is
used to handle any exceptions that occur when a component is processing a message.
• lifecycleAdapterFactory - This is used by the model to create lifecycle adapters which are needed
to translate Mule lifecycle event into events that UMO components registered with the model
understand.
• registerComponent() - This method accepts a UMODescriptor and registers that component with
the Mule manager. The Mule manager handles constructing the component at run time. There is a
complementary method called unregisterComponent() that performs the opposite task and there is
a helper method called isComponentRegistered() that checks to see if a component with a particular
name is registered or not.
• getDescriptor() - returns a UMODescriptor for a specific component.
• stopComponent() - stops the specified component from processing.
• startComponent() - starts the specified component and allows it to continue processing
• pauseComponent() - allows you to temporarily halt a component's processing. Unlike
stopComponent(), messages from the inbound endpoints will still be consumed as the inbound flow
stage will be able to queue these messages for processing.
• resumeComponent() - resumes a component that had been paused.
Of course there are many scenarios where the DynamicEntryPointResolver is suitable. For
example, if you are migrating from another framework you may want to restrict (such
as org.mule.model.CallableEntryPointResolver that only accepts components that extend
org.mule.umo.lifecycle.Callable ) or change the way the entry point is resolved. To implement a custom
Entry Point Resolver the org.mule.model.EntryPointResolver must be implemented.
Lifecycle Adapter
Mule Models
Mule provides the following models:
Since this model assumes that SEDA (and therefore asynchronous processing) will be used throughout,
both reply-to properties and response-routers are ignored.
The org.mule.impl.model.direct.DirectModel model does not have any of the advantages of the SEDA
model. There is no thread management and components are not pooled to service incoming messages,
even if the message flow is asynchronous.
Parts of this model can be simulated when using the SEDA model; e.g., if you want to eliminate the
component pool, you can set a <mule-descriptor>'s singleton attribute to true to make sure that only one
instance of your component is loaded at run time.
The org.mule.impl.model.pipeline.PipelineModel class enhances the Direct model by assuming that all
the components which it hosts implement the Callable interface. This avoids the need for the costly
reflection and introspection on hosted beans. If a hosted component does not implement Callable, then a
org.mule.umo.lifecycle.InitialisationException is raised.
Streaming allows you to stream data through Mule, or through service components rather than having
to read the whole item into memory, leading to more efficient processing of large files or records. This
technique is supported across TCP, File, HTTP and SOAP (Xfire) although support for FTP will be available
shortly.
As of 1.4, "streaming" has been added as a type to the Mule model. Your Mule endpoints will need to
understand how to stream data - you can configure this by setting the "streaming" attribute to true for
each endpoint.
The "inherited" type is not really a model but an indication to Mule that the model type was defined in a
previous configuration file.
Inside the first configuration file, you can define your model and all it's properties, etc. Inside secondary
configuration files, you can either declare separate and independent models or else you can simply inherit
the model used in the first configuration file. This allows you to split your Mule configuration into multiple
files. The root element will still be <mule-configuration> as is shown in the next slide.
Note that configuration files are loaded sequentially, so the master configuration has to be passed to the
configuration builder class first, e.g.,
The "custom" type allows you to use a model of your own, should you wish to implement one of your
own. You will need to set the className attribute to point to your model, or you can use the ref attribute
if your model is declared inside some other container, like Spring. If you do not set the className
attribute, an IllegalArgumentException will be raised.
You can implement your own model by inheriting from the AbstractModel class which handles certain
default behaviour, or you can code your own and implement the UMOModel interface instead.
Agents are services that are associated or used by Mule but not a Mule managed component. For
example Mule's Jmx support is implemented and configued using agents. The useful thing about agents
is they have the same lifecycle as the Mule instance they are registered with, so you can initialise and
destroy resources when the Mule instance starts or is disposed.
To write your own agent you need to implement org.mule.umo.UMOAgent and register your agent with
the UMOManager. In the Mule xml configuration use the 'agents' element to register an agent -
<agents>
<agent name="My Agent" className="org.foo.MyAgent"/>
</agents>
or programmatically -
The request and paramters used to access a .NET Web Service have to be sent as SOAP messages. For
this reason you can generally use either Axis or Xfire transports to do so. View the following cookbook
entry to view how this can be done.
http://mule.mulesource.org/display/MULE/Calling+.NET+web-service+using+Axis
http://mule.mulesource.org/display/MULE/Calling+.NET+Web+Services+using+XFire
How does mule handle the authentication for each of the described methods
above?
If you are running Mule on a Web App you could literally configure the web server to use security, i.e. by
setting security configuration on the web.xml and in the server's configuration file.
Alternatively, to secure a Web Service running on Mule (with Mule being the Server), you could set the
HttpBasicAuthenticationFilter on the web service component. Any call made to the web service would
have to pass through the filter which delegates the authentication to Acegi.
See: http://mule.mulesource.org/display/MULE/Mule+Security
Another alternative would be to use Https where certificates are used for authentication.
Sending authentication tokens through SOAP headers shouldn't be problematic provided that there
is an authentication provider established that is able to understand the headers and perform the
authentication.
3. Mule uses Apache's WSS4J classes (and Xfire's adaptations) for WS-Security simply by
setting the required handlers on the connector.
For more details please look at the doc about how to configure Mule to use WS-Security on the following
link:
http://mule.mulesource.org/display/MULE/Web+Service+Security\\
Method 2: set the authentication items as properties when using the MuleClient
Method 3: create headers containing the authentication items and send them as properties when using
the MuleClient
The Mule Client is a simple interface for java clients to send and receive events from a Mule Server and
other applications. The client serves the following functions -
In most Mule applications events are triggered by some external occurrence such as a message
being received on a queue or file being copied to a directory. The Mule client allows the user to send
and receive events programmatically. For example, to send a Jms message to any application, Mule
component or otherwise, listening on my.queue -
To make a regular client/server synchronous call the send() method can be used -
Mule Client allows you to make synchronous calls without blocking using the sendAsync() method.
if(result.isready()) {
Object payload = result.getMessage().getPayload();
}
1. The mule url endpoint - This is any valid Mule Endpoint used to determine the transport, endpoint
and other information about delivery of the event
2. The event payload - this can be any object
3. Properties - any properties or meta-data to associate with the event
The Mule client can be used as a web services client to make soap requests using popular soap
implementations such as Web Methods Glue and Apache Axis.
System.out.println(person.toString());
Soap Provider
The Mule Soap Provider supports Web Methods Glue and Apache Axis. For more information
about Mule Axis support go here, for more information about MUle Glue support go here.
This will attempt to receive a message from a mailbox called ross on mail.muleumo.org and will return
after 5 seconds if no message was received.
Tip
Calling receive() will work for all Mule supported transports, but it is more usual to make
request-response calls where there is a store to be queried such as a queue, file directory,
or some other repository or where a call will be executed based on the receive and a result
returned such as making a soap call.
The client also provides a convenient way to send an event directly to a component without needing to
use a provider, this can be very useful in testing, but also when triggering events from a Jsp page or
script. To dispatch an event directly to your stock quote component called StockManager you would do
the following -
StockQuote sq = (StockQuote)result.getPayload();
Note that the call is sendDirect, this tells the client to go directly to the component and not through
a provider. As such there will be no transformers configured for this call. You can specify a comma-
separated list of transformers to use in the second argument of this call.
StockQuote sq = (StockQuote)result.getPayload();
The Mule client will execute 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 a optional string of comma
separated transformers to use on the result message. The second null argument is properties associated
with the request.
Often you will not want to wait for the result to be returned from the remote server, so you can use the
asyncRemote() method that returns a FutureMessageResult.
StockQuote sq = (StockQuote)result.getMessage(1000).getPayload();
The result 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 (shown in the example).
You can also check if the call has returned using result.isReady().
By default, the Mule server will listen on tcp://localhost:60504, if you want the client to use a different
server location you can specify it when you create the remote dispatcher-
When the manager is running asynchronous, making a synchronous client call i.e. client.send(..)
the result event will always be null, as internally, Mule will be making all calls asynchronously. You can
determine if Mule is running synchronously by calling -
So far in all the examples we have set the properties argument to null. Properties can be arbitrary,
i.e. to pass around custom meta-data with your events or they can be transport specific. The following
example demonstrates an asynchronous request/response using Jms and the Jms specific JMSReplyTo
property.
//Set the JMSReplyTo property, this is where the response message will be sent
props.put("JMSReplyTo", "replyTo.queue");
//This the message sent back from the first component to process our event
System.out.println(message.getPayload());
This example demonstrates how to send a mail message using the client and setting the subject and and
from address as properties on call.
Tip
The Mule Client doesn't have to be used to talk to a Mule Server. It doesn't matter what
application is receiving requests made by the client.
Or to omit the smtp connection information from the url you can configure an smtp connector in Mule and
just use -
Mule's configuration is extensible in that there is no mandate about how the configuration of Mule should
be stored or the format of the configuration. The only requirement is that once mule is configured an
instance of UMOManager should be available by calling MuleManager.getInstance().
Quick Start
To start a Mule instance from the command line or script using a Mule XML configuration file, use the
following -
This will use the default org.mule.config.MuleXmlconfigurationBuilder to process a configuration file called
../conf/mule-config.xml.
Developers can specify a comma-separated list of XML configuration files to load i.e.
The configuration files are loaded in sequence so global configuration files should be loaded first.
Configuration Builders
To configure Mule a Configuration builder is used. This is a simple interface that the Mule server can
invoke on start up. You can define your own configuration depending on how you want to configure Mule.
Mule currently comes with three configuration builders, the default Mule xml Configuration builder, Spring
and Groovybuilders. However, it would be straight forward to implement other builders, say a Pico builder
or BeanShell builder.
To tell Mule to use a particular builder you must specify the fully qualified class name as a command line
argument using the -builder token and define the configuration resources for the builder using the -
config token. For example to use the Spring builder, you would define your command something like this
-
By default Mule's configuration is an XML file, usually called mule-config.xml. This file has a
corresponding DTD called mule-configuration.dtd which is included in the distribution.
Spring Configuration
As well as the default Mule XML configuration, a Spring configuration builder is also included with the
Mule distribution. This builder enables the developer to configure all Mule elements through Spring, which
means any Mule objects can leverage Spring's AOP and transaction interceptors, DAO support, etc.
For more information about configuring Mule with Spring see the Spring chapter.
where configResources can be anything from a JNDI location, a URL or a filename (or comma separated
list of filenames) on the classpath or file system. It's up to the Configuration Builder how it uses the
configResources to construct an instance of UMOManager and pass it back to the server.
Some future Configuration Builders may include a PicoContainer assembler, a Bean Shell builder and JNDI
builder.
See also Configuration Options for details about how to configure the actual Mule instance.
1. Set the VM parameter to a fully qualified class name of the UMOManager you want to use, i.e. -
Dorg.mule.umo.UMOManager=com.foo.MyManager.
2. Use the MuleManager.setInstance(...) method. This method is useful when defining your own
ConfigurationBuilder; this is discussed more in the next section.
Mule Endpoint URIs are any valid URI and describes 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, though other provider implementations
can introduce their own schemes.
scheme://[MULE:host][MULE::port]/[MULE:endpoint name]/[MULE:address]?
[MULE: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
If host and port are set it is unlikely that a provider would be set, though by setting the provider name
would cause a specific provider to be used with the host and port.
tcp://localhost:3212/myTcpEndpoint
This would use the pre-configured endpoint "myTcpEndpoint" using tcp://localhost:3212 as the endpoint
URI.
scheme://[MULE:endpoint name]/[MULE:address]?[MULE:params]
The endpoint name is a pre-configured endpoint to use. Endpoints can be local to the component or
global and visible to all components in the container. Endpoints are configuration objects that group a
connector, transformers and an endpoint URI together along with filter and transaction information. For
more information see Mule Endpoints.
jms://jmsEndpoint/test.queue
The URI specifies that a pre-configured endpoint called jmsEndpoint should be used and the address on
the endpoint should be set to 'test.queue'. If you want to use the endpoint 'as is' just omit the address
but leave the tailing forward slash i.e.
jms://jmsEndpoint/
scheme://[MULE:username][MULE::password]@[MULE:host][MULE::port]?
[MULE:params]
The user name and password are used to log in to the remote server specified by the host and port
params. The pop3 and SMTP connectors use this format or URI.
pop3://ross:secret@pop3.muleumo.org
smtp://ross:secret@smtp.muleumo.org
Here we only define a protocol and an address. This tells Mule to go and get a connector that handles the
specified scheme or create one if needed, create a new endpoint and use the specified address.
vm://my.queue
URI Parameters
So far we haven't talked about the "params" part on the URI. There are two types of params that can be
set -
1. Known Mule params that control the way the endpoint is configured, such as whether to force a
connector to be created or to specify transformers for the endpoint.
2. Properties to be set on the connector or to be associated with the provider. This allows you to set
properties on a connector used by this endpoint. Additionally, all properties will be associated with
the provider, so you can mix connector and provider properties. If you haven't already, I recommend
having a look at Mule Endpoints for more information.
Known Parameters
Property Description
file:///C:/temp?endpointName=myFileEndpoint&transformers=FileToString,XmlToDom
udp://localhost:38543?createConnector=ALWAYS
jms://jmsEndpoint/topic:my.topic?createConnector=NEVER
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.
Custom Endpoints
Each connector can define its own EndpointBuilder. This builder is used by the MuleEndpointURI to
compose the URI into an endpoint that the connector understands. There are default EndpointBuilder
implementations that most connectors can use, such as socket, resource name and URL builders, plus
there are special cases such as file URLs where the provider cannot be expressed in the URI path.
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 > < " % # that notation will be resolved and cause the constructor for the URI to
throw an exception. To use one of ><"%#, a user can specify %HEXNUMBER
Endpoints are used to connect to components in the server and external systems or to each other locally
or over the network. An Endpoint is a specific channel through which two parties can communicate.
A provider can be used to send or receive events from disparate systems, 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 response sent back
over Http.
1. Endpoint URI - at the very least an endpoint will have an Endpoint URI; an address that is used to
reference a resource or service either locally or remotely. This must be a valid URI.
2. Connector - used to connect to the underlying transport. Often the connector is not explicitly set,
instead the connector for the endpoint is found based on the scheme of the Endpoint URI.
3. Filter - a filter to apply to messages being recieved on the endpoint. See the Transports Guide for
information about filtering support for a specific transport.
4. Transaction - Transactions can be begun or committed when an event is received or sent. See the
Transports Guide for information about transaction support for a specific transport.
5. Properties - These can be set to override certain properties on the connector for this endpoint
instance. For example, when using a smtp endpoint you may want to overload the from address.
Essentially, an endpoint is a configuration entity used to control how events are sent and received in
Mule. Mule also has a notion of 'Transport Providers' or 'Providers' that do the actual work of sending a
recieving events over various protocols.
Transport Elements
A Transport Provider is in fact a composite of a set of objects used to connect and communicate with the
underlying system. The elements of a Transport Provider are -
The following shows how an endpoint and underlying Transport components fit together. Cannot resolve
external resource into attachment.
Endpoint Usage
Endpoints can be configured on various objects in Mule -
• Inbound Routers - configured on Components and allow one or more endpoints to be registered on a
component.
• Outbound Routers - configured on components and allow one or more outbound endpoints to be
configured (with additional logic for controlling which endpoints are used for an event. See Message
Routers)
• Catch all strategies - allow a single 'catch-all' endpoint to be configured for a router.
• Components - for convenience a single inbound and outbound endpoint can be set on the
component directly, which is a little eaiser than configuring routers.
• Exception Strategies - A single endpoint can be configured on an exception strategy to all events to
be sent to an error endpoint.
Endpoints Scope
Endpoints can have two scopes; Global scope and local scope.
An Endpoint is considered to have Global scope when it is registered on the MuleManager instance or set
in the Mule configuration as a <global-endpoint>.
Global endpoints can be referenced anywhere in your code. It's important to note that when an endpoint
is requested from the UMOManager using the lookupEndpoint() method, Mule actually returns a clone
of the Endpoint. This allows client code to change any attibutes on the endpoint without affecting other
objects in the system that also use the endpoint. The exception to this is the connector which is not
cloned and setting properties on the connector at run-time may cause unpredictable results and is not
recommended unless the documentation for the Transport says otherwise.
Local Scope
These are endpoints that are configured or set on the objects that have Endpoints, but are not registered
with the MuleManager.
More Information
For more information about configuring endpoint see Configuring Endpoints. For reference about
Transport Provider implementations see the Transports Guide.
Mule allows you to authenticate requests via endpoints using transport specific or generic authentication
methods. It also allows you to control method-level authorisation on your Service Components. This
section covers the following topics -
Once you've read this page the following will also be of interest for people wanting to enable
authorisation on Service components or use security technologies such as JAAS, PGP or CAS -
• Jaas Security
• PGP Security
• Acegi Security
• Component Authorization Using Acegi
• Setting up LDAP Provider for Acegi
Security Manager
The Security Manager responsible for Authenticating requests based on one or more Security Providers
configured on the security Manager. A Security Provider can authenticate against a variety of repositories
such as Ldap, JAAS, database (dao) and third-party security frameworks such as CAS (Yale Central
Authentication Service).
Mule has a default security implementation that uses Acegi Security. It provides a number of Security
providers out of the box including the ones listed above. Acegi is a Spring-based implementation and also
provides interceptors that can enable method-level authorisation on your service components. For spring
users this means a unified approach to their application security. For Mule users not using Spring, using
Acegi will impose no spring requirements on your application code. All security is provided via the Mule
security API, so custom implementations can easily be plugged in.
Configuration
The following describes how to configure a single Security provider on Mule, in this case an in-memory
DAO.
<mule-configuration>
<security-manager>
<security-provider name="memory-dao"
className="org.mule.extras.acegi.AcegiProviderAdapter">
<properties>
<container-property name="delegate" reference="daoAuthenticationProvider"/>
</properties>
</security-provider>
</security-manager>
....
</mule-configuration>
Note that the 'delegate' property is a container property meaning we need a container to get it from.
Here we configure a Spring Container Context to load our Security Providers from. you can set multiple
security-provider elements.
<container-context
className="org.mule.extras.spring.SpringContainerContext">
<properties>
<property name="configFile" value="securityContext.xml"/>
</properties>
</container-context>
The Spring Acegi configuration is where the real Security Provider configuration occurs.
Here we have a static DAO Security Provider that allows user credentials to be set in memory with two
users; ross and anon.
Encryption strategies
The Security Manager can be configured with one or more Encryption strategies that can then be used
by encryption transformers, Security filters or secure Transport providers such as ssl or https. These
Encryption strategies can greatly simplify configuration for secure messaging as they can be shared
across components.
<security-manager>
<encryption-strategy name="PBE"
className="org.mule.impl.security.PasswordBasedEncryptionStrategy">
<properties>
<property name="password" value="mule"/>
</properties>
</encryption-strategy>
</security-manager>
This strategy can then be referenced by other components in the system such as filters or transformers.
<transformers>
<transformer name="EncryptedToByteArray"
className="org.mule.transformers.encryption.DecryptionTransformer">
<properties>
<property name="strategyName" value="PBE"/>
</properties>
</transformer>
</transformers>
Security Filters
Security filters can be configured on an object to either authenticate inbound requests or attach
credentials to outbound requests.
As the name suggests, these types of filters are configured on endpoints. To configure a Http Basic Auth
filter on a http endpoint use the following -
<endpoint address="http://localhost:4567">
<security-filter
className="org.mule.extras.acegi.filters.http.HttpBasicAuthenticationFilter">
<properties>
When a request is received the Authentication header will be read from the request and authenticated
against all Security Providers on the Security Manager. If you only want to validate on certain ones you
can supply a comma-separated list of Security Provider names.
<endpoint address="http://localhost:4567">
<security-filter useProviders="default,another"
className="org.mule.extras.acegi.filters.http.HttpBasicAuthenticationFilter"/>
</endpoint>
This section describes how you can configure method level authorization on your components so that
users with different roles can only invoke certain service methods.
Apart from the daoAuthenticationProvider and inMemoryDaoImpl beans configured above, the following
beans must be configured:
• MethodSecurityInterceptor
• AuthenticationManager
• AccessDecisionManager
• AutoProxyCreator
• RoleVoter
The MethodSecurityInterceptor
• AuthenticationManager
• AccessDecisionManager
The following is a Security Interceptor for intercepting calls made to the methods of a component called
myComponent. myComponent has an interface (myComponentIfc) that defines two methods: delete and
writeSomething. Roles are set on these methods as seen below in the property objectDefinitionSource.
<bean id="myComponentSecurity"
class='org.acegisecurity.intercept.method.aopalliance.MethodSecurityInterceptor'>
<property name="authenticationManager">
<ref bean="authenticationManager"/>
</property>
<property name="accessDecisionManager">
<ref bean="accessDecisionManager"/>
</property>
<property name="objectDefinitionSource">
<value>
com.foo.myComponentIfc.delete=ROLE_ADMIN
com.foo.myComponentIfc.writeSomething=ROLE_ANONYMOUS
</value>
</property>
</bean>
The AuthenticationManager
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.
• It will vote to grant access if there is a GrantedAuthority which returns a String representation (via
the getAuthority() method) exactly equal to one or more ConfigAttributes starting with ROLE_.
• If there is no exact match of any ConfigAttribute starting with ROLE_, the RoleVoter will vote to
deny access.
• If no ConfigAttribute begins with ROLE_, the voter will abstain.
MODE_THREADLOCAL which allows the authentication to be set on the current thread (this is the defualt
strategy used by Acegi).
MODE_INHERITABLETHREADLOCAL which allows authentication to be inherited from the parent thread
MODE_GLOBAL which allows the authentication to be set on all threads
The use of Acegi's security strategies is particularly useful when using an asynchronous system since we
have to add a property on the Security Provider in order for the authentication to be set on more than
one thread.
In this case we would use the MODE_GLOBAL as seen in the example below.
In the Mule Security page, we discuss about how you can configure an in-memory DAO provider. In this
documentation, we will talk about how you can configure an Acegi's LDAP provider, which can be:
Basically, you will need to setup two beans in Spring, an InitialDirContextFactory and an
LdapAuthenticationProvider. The InitialDirContextFactory is the access point for obtaining an
LDAP context where the LdapAuthenticationProvider provides integration with the LDAP server. As an
example:
<bean id="authenticationProvider"
class="org.acegisecurity.providers.ldap.LdapAuthenticationProvider">
<constructor-arg>
<bean class="org.acegisecurity.providers.ldap.authenticator.BindAuthenticator">
<constructor-arg>
<ref local="initialDirContextFactory" />
</constructor-arg>
<property name="userDnPatterns">
<list>
<value>uid={0},ou=people</value>
</list>
</property>
</bean>
</constructor-arg>
<constructor-arg>
<bean class="org.acegisecurity.providers.ldap.populator.DefaultLdapAuthoritiesPopulator">
<constructor-arg>
<ref local="initialDirContextFactory" />
</constructor-arg>
<constructor-arg>
<value>ou=groups</value>
</constructor-arg>
<property name="groupRoleAttribute">
<value>cn</value>
</property>
<property name="searchSubtree">
<value>true</value>
</property>
<property name="rolePrefix">
<value>ROLE_</value>
</property>
<property name="convertToUpperCase">
<value>true</value>
</property>
</bean>
</constructor-arg>
</bean>
<security-manager>
<security-provider name="acegi-ldap" className="org.mule.extras.acegi.AcegiProviderAdapter">
<properties>
<container-property name="delegate" reference="authenticationProvider" />
</properties>
</security-provider>
</security-manager>
With the above configuration, you can achieve endpoint-level security and other security features in Mule
which require one or more security providers.
Configuring MethodSecurityInterceptor
The configuration for component authorization is similar with the one that we have discussed in this page.
The one worth mentioning is the configuration of ObjectDefinitionSource, e.g.
<property name="objectDefinitionSource">
<value>org.mule.components.simple.EchoService.*=ROLE_MANAGERS</value>
</property>
The roles are looked up by the DefaultLdapAuthoritiesPopulator which you configured in previous
section. By default, a role is prefixed with ROLE_ and its value is extracted (and turned uppercase) from
the LDAP attribute defined by the groupRoleAttribute.
Mule has an internal notification mechanism which can be used to tap into server notification such as a
Component being added, the Model being initialised or the Manager being started. These notifications can
be useful to allow custom components such as Agents or Mule managed components to react to change in
the server.
Don't confuse these notifications with service events that mule manages between your
components and external applications. These Server Notifications provide notifications
between objects that comprise the Mule Server, where as service events are the business
operations that your business services process.
1. Manager Notification - is fired when state changes on the Mule manager such as initialising, starting
and stopping.
2. Model Notification - is fired when state changes on the Mule Model such as initialising, starting and
stopping or components being registered or unregistered.
3. Component Notification - is fire when a particular component is started, stopped, paused, resumed.
4. Management Notification - is fired when monitored resources are low (not yet implemented)
5. Custom Notification - can be fired by objects themselves to custom notification listeners, and can be
used to customise notifications on Agents, Components, connectors etc.
6. Admin Notification - is fired when requests are received by the Mule Admin agent. These are usually
trigged by MuleClient calls using the RemoteDispatcher, which proxies calls to a remote server.
7. Connection Notification - happen when a connector attempts to connect to its underlying resource.
Notifications are fired when a connection is made, released or the connection attempt fails.
8. Message Notification - These notifications are fire when an event is sent or received in the system.
These are very good for tracing, but are not enabled by default as there is a performance impact
when using these. Read below to find out how to enable them.
9. Security Notification - is fired when a request is denied security access.
10. Space Monitor Notification - is fired from space implementations such as JavaSpaces, JCache
or the Mule internal space implementation when events are fired into or out of a space. See
[MULE:Spaces] for more information.
11. Exception Notification - is fired when an exception is thrown. (since 1.4.2)
12. Transaction Notification - happens during transaction life cycle. Notifications are fired after
transaction has begun, committed or rolled back. (since 1.4.2)
To become a server event listener objects can implement one of the following interfaces-
1. org.mule.impl.internal.notifications.ManagerNotificationListener
2. org.mule.impl.internal.notifications.ModelNotificationListener
3. org.mule.impl.internal.notifications.ComponentNotificationListener
4. org.mule.impl.internal.notifications.ManagementNotificationListener
5. org.mule.impl.internal.notifications.CustomNotificationListener
6. org.mule.impl.internal.notifications.AdminNotificationListener
7. org.mule.impl.internal.notifications.ConnectionNotificationListener
8. org.mule.impl.internal.notifications.MessageNotificationListener
9. org.mule.impl.internal.notifications.SecurityNotificationListener
10. org.mule.impl.internal.notifications.SpaceMonitorNotificationListener
11. org.mule.impl.internal.notifications.ExceptionNotificationListener
12. org.mule.impl.internal.notifications.TransactionNotificationListener
Depending on the listener implemented only certain events will be received, for example the object
implements ManagerNotificationListener only events of type ManagerNotification will be received. Objects
can implement more than one listener to receive more types of event.
Each event has an action code that determines the type of event. The action code can be queried in the
onEvent method to determine its type. To have an object do something when the Model initialises -
MyObject.java
Enabling MessageNotifications
Message Notifications are very useful as they provide a snapshot of all information sent into and out of
the the Mule Server. These notifications are fired when ever a message is received or sent. As you can
imagine, these additional events will have some impact on performance so they are turned off by default.
To enable these events you need to set the enableMessageEvents to true on the <mule-environment-
properties> i.e.
<mule-environment-properties enableMessageEvents="true"/>
Any objects implementing CustomNotificationListener will receive this event. It's a good idea to extend
the CustomNotification and define actions for your custom event type. To use the Discovery Agent
example above -
Non-system objects in Mule can only fire Custom notifications through the
manager, attempting to fire other events such as ModelNotification will cause an
UnsupportedOperationException.
You can associate a subscription with an event listener so that only events the match the subscription will
be passed to the listener. The subscription is a wildcard String expression that will be matched against
the 'Resource ID' of the event (see the next section). So to register interest in Component events where
the component is called MyService1 you can use -
MuleManager.getInstance().registerListener(listener, "MyService1");
MuleManager.getInstance().registerListener(listener, "*Service*");
Notification payloads
All notifications extend java.util.EventObject and the payload of the object can be accessed using the
getSource() method. The following table describes the event payloads for each type of event.
Notification Actions
Action Description
ModelNotification
Action Description
Action Description
ManagementNotification
CustomNotification
Action Description
AdminNotification
Action Description
ConnectionNotification
Action Description
MessageNotification
Action Description
SecurityNotification
Action Description
SpaceNotificationNotification
Action Description
ExceptionNotification
Action Description
TransactionNotification
Action Description
Mule can be configured to use and manage any object from external containers or Naming Directories
such as Jndi, Ejb, Spring, Pico, Plexus, or HiveMind.
Supported Containers
• Jndi Container - Look up objects in one ore more Jndi contexts.
• Spring Container - Use Spring beans as Mule components and to wire bean properties.
• Pico Container Use PicoContainer objects as Mule components and to wire bean properties.
• Plexus Container - Use Plexus objects as Mule components and to wire bean properties.
• HiveMind Container - Use HiveMind objects as Mule components and to wire bean properties.
Configuring Containers
You can configure zero or more containers in a single Mule instance using the <container-context>
element.
This will configure a Jndi container. By default, when looking up an object Mule will search each of the
containers in the order they are configured.
Notice the name attribute; this is optional but allows you to reference a particular container when setting
a container property (see below). Each type of container has its own default name such as 'jndi', 'ejb',
'spring', 'pico' or 'plexus' . The only time you might want to set the name attribute yourself is if you have
2 jndi containers that contain objects of the same name and you need to distinguish between the two.
Mule services can be objects configured in an object container. To expose a container objects as a Mule
service you need to set the implmenetation attribute of the <mule-descriptor> element to the name of
the object to look up. Optionally, You can also set the container attribute to specify which container to
load the object from.
Container Properties
Any object specifed in Mule Xml that has a <properties> element can reference objects in containers as
properties. These are properties that are retrieved from a configured IoC or Naming container, such as
Spring, Jndi or EJB.
<properties>
<container-property name="testProperty" reference="testBean" required="true" container="jndi"/>
</properties>
Storing Mule objects in Jndi - How to store Mule instance configuration in a central directory.
Jndi Container - How to expose Jndi contexts to Mule for looking up objects.
The JndiContainerContext can be used to expose objects stored in Jndi as Mule components.
To configure a Jndi container you need to add a <container-context> element that uses the
org.mule.impl.container.JndiContainerContext and set the Jndi environment properties.
<container-context className="org.mule.impl.container.JndiContainerContext">
<properties>
<map name="environment">
<property name="java.naming.factory.initial" value="org.foo.jndi.InitialContextFactory"/>
</map>
</properties>
</container-context>
<container-context className="org.mule.impl.container.JndiContainerContext"/>
In this case a standard JavaSE JNDI lookup mechanism with fallback will be utilised.
Components can reference an object stored in Jndi by setting the implementation attribute of a <mule-
descriptor> to the name of the stored object.
It's also possible to reference any property from JNDI, e.g. inject a DataSource into JdbcConnector:
<container-context className="org.mule.impl.container.JndiContainerContext"/>
...
The Quartz integration has been superseeded by the Quartz Provider. This provides many
more scheduling options and is independent of Spring.
Quartz is an open source job scheduling system that can be used to create simple or complex schedules
for executing tens, hundreds, or even tens-of-thousands of jobs. Mule integrates with Quartz using Spring
to provide a simple way to declare mule jobs.
Quartz Provider
The MuleJobBean is an implementation of a Quartz Job that can be used to send or dispatch simple beans
into Mule, using Quartz scheduling features.
For an example of configuring Quartz for Mule, see the Spring configuration file.
Further information on how to configure Quartz from a Spring context, look here.
• JavaRebel Integration — Develop in regular Java, re-compile and reload on the fly.
Prerequisites
• Internet connection
• Java 5
Instructions
We'll use a Hello Example bundled with Mule to demonstrate the setup.
1. Download Mule 1.4.4-SNAPSHOT from the downloads page. Instructions apply to Mule 2.x as well.
2. Configure JAVA_HOME, MULE_HOME and run Mule for the first time to accept the license.
3. Download JavaRebel 1.0-M3 snapshot from http://www.zeroturnaround.com/download/
4. Unpack, copy javarebel.jar to $MULE_HOME/bin to keep things simple.
5. Change into $MULE_HOME/examples/hello
6. Generate project files mvn idea:idea (mvn eclipse:eclipse for, right, Eclipse)
7. Change module output path to compile into $MULE_HOME/lib/user
8. Delete mule-example-hello.jar from $MULE_HOME/lib/user. It contains the same classes we're
compiling. JavaRebel supports only exploded class reloading currently.
9. Make the project.
10. Start Mule with an extra switch to enable JavaRebel:
mule -config hello-config.xml -M-javaagent:../../bin/javarebel.jar -M-noverify
Note that we reference the config file as a resource - it's been put on the classpath in lib/user when
you built the project.
11. Type your name when prompted, watch the standard reply. Now let's have some fun.
12. Modify org.mule.samples.hello.Greeter#greet() method. Let's make it more rebellious: modify
the code to set a new greeing:
Hey, it works in debug mode as well, including remote. Just add the -debug switch to the Mule start
command and connect your debugger on port 5005 (default). Just make sure to say No when you see
debugger's prompt to reload classes - let JavaRebel rock IDEA users may need to get the JavaRebel
debugger plugin, see the troubleshooting section below.
Troubleshooting
• I get weird exception with strange class names - don't put javarebel.jar in $MULE_HOME/
lib/user. It's easier not to do it, then explain why it may fail for certain cases (complex classloader
tricks).
• It won't reload! - if nothing else works, then the worst to happen is restarting Mule.
• It won't reload Mule core classes! - these instructions apply to custom user classes only.
• Debugger never stops at breakpoint in IDEA - This is a known issue, JetBrains and
ZeroTurnaround are actively working on it. Doesn't affect Eclipse users (uses different mechanism).
Update: this has been resolved now. Download the JavaRebel Debugger plugin from IntelliJ IDEA
plugin repo (or go to http://plugins.intellij.net/plugin/?id=1699). These changes might be included
in IDEA's core in the future.
• I can't compile the code in IDEA - make sure the JDK is properly configured for the project. If
you know the name of the JDK as it is listed in IDEA, you can use it during project files generation:
mvn idea:idea -DjdkName=1.6
• I get a JVM core dump under JDK 6 Update N - it may or may not work under Java 6. There's
a regression in Java 6 Update N, which has been identified and reported. Apparently, something is
The Mule resource adapter enables a mule instance to be deployed to a J2EE application server. It can be
deployed to any JCA 1.5 compliant container, see J2EE Application Servers for more information about
specific App Server configurations.
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.ra.MuleConnectionFactory</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Unshareable</res-sharing-scope>
</resource-ref>
</session>
Inbound Configuration
the only required property for for your MDB is 'endpoint' is a valid endpoint Uri to receive Mule events.
<message-driven>
<description>An MDB listening 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.umo.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>
Managing RMI Objects - How to manage objects stored in RMI as Mule components
RMI Transport Provider - Configuring the RMI transport provider. This allows you to fire events to and
make requests from objects stored in RMI.
<container-context className="org.mule.impl.container.RmiContainerContext">
<properties>
<!-- Jndi environment properties -->
<map name="environment">
<property name="java.naming.factory.initial"
value="org.jnp.interfaces.NamingContextFactory"/>
<property name="java.naming.provider.url" value="jnp://localhost"/>
<property name="java.naming.factory.url.pkgs"
value="org.jboss.naming:org.jnp.interfaces"/>
</map>
<!-- optional properties to configure custom security policies and security manager -->
<property name="securityPolicy" value="/projects/foo/classes/wideopen.policy"/>
<property name="securityManager" value="java.rmi.RMISecurityManager"/>
</properties>
</contianer-context>
Components can reference an RMI Object by setting the implementation attribute of a <mule-descriptor>
to the name of the Object stored in Jndi.
Due to licensing issue, Mule cannot bundle JSR-223 libraries in the distribution. Until this
page is updated with detailed instructions, one can check MULE-1168 for steps involved.
Mule Components, transports and configuration can be scripted using any JSR-223 compliant scripting
language such as PHP (stateless), Groovy or Rhino (javascript).
Script Components
Scripts can be invoked as Mule managed components by using
org.mule.components.script.jsr223.ScriptComponent.
<mule-descriptor name="GroovyUMO"
inboundEndpoint="jms://groovy.queue"
implementation="org.mule.components.script.jsr223.ScriptComponent">
<properties>
<property name="scriptEngineName" value="groovy"/>
<text-property name="scriptText">
return "Received message: " + message.getPayload()
</text-property>
</properties>
</mule-descriptor>
Property Description
When a script is invoked, the JSR-223 api has a notion of a namespace, a collection of objects that are
referenceable by name from your script. Mule makes the following objects available.
Name Description
componentNamespace
The ScriptConfigurationBuilder allows developers to create a mule instance from a JSR-223 compliant
script. To load the manager from javascript -
java -Dorg.mule.script.engine=javascript
-cp ... org.mule.MuleServer
-builder org.mule.config.builders.ScriptConfigurationBuilder
-config ../conf/mule-config.js
For more information about configuring a Mule instance from code or script see Configuring Mule
Programmatically.
Script Transformers
Script transforms can be used to perform transformations on objects using scripting. The transformers
are configuring in the same way as the ScriptComponent.
To use Groovy as an example, the configuration for a transformer that converts a comma-separated
string of values to a java.util.List would look like -
The sourceType property tells the transformer only to accept source objects of type string. This property
can be set multiple times to register different source types.
The returnClass attribute on the transformer ensures that we will always get a java.util.List back from
this transformer.
• Acegi Security
• Jaas Security
• PGP Security
• Web Service Security
Acegi is a security framework for Spring. In Mule it provides a simple way of authenticating requests
via the Security Manager. There is a simple Mule security provider wrapper that delegates to Acegi,
which means you can use any of the Acegi Security Providers such as JAAS, Ldap, Cas (Yale Central
Authenication service) and Dao.
See Configuring Security for more information about configuring Acegi with Mule.
The JaasSimpleAuthenticationProvider is a security provider which provides a way to interact with the
Jaas Authentication Service.
Configuration:
The security provider for Jaas can be configured in a couple of different ways. First of all, it allows you
to configure jaas either by passing to the provider a jaas configuration file, which will be discussed
below, or by passing the required attributes directly to the JaasSimpleAuthenticationProvider. These two
configuration methods are described below.
Usually, JAAS authentication is performed in a pluggable fashion, so applications can remain independent
from underlying authentication technologies.
com.ss.jaasTest{
com.ss.jaas.loginmodule.DefaultLoginModule required
credentials="anon:anon;Marie:Marie;"
};
The above example was saved in a file called jaas.conf. This file contains just one entry called
com.ss.jaasTest, which is where the application we want to protect can be found. The entry specifies the
LoginModule that will be used to authenticate the the user. As a login module, you can either use Mule's
DefaultLoginModule, one of the LoginModules that come with Sun, or else create your own. In this case,
we have opted for Mule's DefaultLoginModule.
The "required" flag that follows the LoginModule specifies that the LoginModule must succeed in order for
the authentication to be considered successful. There are other flags apart from this. These are:
Required - The LoginModule is required to succeed. If it succeeds or fails, authentication still continues
to proceed down the LoginModule list.
Requisite - The LoginModule is required to succeed. If it succeeds, authentication continues down the
LoginModule list. If it fails, control immediately returns to the application.
Sufficient - The LoginModule is not required to succeed. If it does succeed, control immediately returns
to the application (authentication does not proceed down the LoginModule list). If it fails, authentication
continues down the LoginModule list.
Optional - The LoginModule is not required to succeed. If it succeeds or fails, authentication still
continues to proceed down the LoginModule list.
The entry also specifies the credentials, in which we put a string of authorised users together with their
passwords. The credentials are put here only when the DefaultLoginModule is going to be used as the
method in which the user names and passwords are obtained may vary from one LoginModule to another.
The Format of the credentials string must adhere to the following format if the DefaultLoginModule is
going to be used:
<username>:<password>;
<security-provider name="JaasProvider"
className="com.ss.jaas.provider.JaasSimpleAuthenticationProvider">
<properties>
<property name="loginContextName" value="com.ss.jaasTest"/>
<property name="loginConfig" value="jaas.conf"/>
</properties>
Note that in the above, the loginContextName contains the same name of the entry in the jaas
configuration file discussed above. This will be used for creating the login context as well as to find the
complete URL of the jaas.conf file.
The second option for the configuration of the JaasSimpleAuthenticationProvider is to pass the
configuration details which would otherwise be found in the jaas configuration file directly to the provider.
<security-provider name="JaasProvider"
className="com.ss.jaas.provider.JaasSimpleAuthenticationProvider">
<properties>
<property name="loginContextName" value="com.ss.jaasTest"/>
<property name="credentials" value="anon:anon;Marie.Rizzo:dragon;" />
</properties>
</security-provider>
In the above configuration, you can note that we removed the property "loginConfig" and we don't need
to pass any jaas configuration file. All we need to do is to pass the credentials to the provider (using the
same format specified above). Since no LoginModule is specified, the DefaultLoginModule will be used.
However, the JaasSimpleAuthenticationProvider also permits you to enter, using this configuration, your
own LoginModule.
<security-provider
name="JaasProvider"className="com.ss.jaas.provider.JaasSimpleAuthenticationProvider">
<properties>
<property name="loginContextName" value="com.ss.jaasTest"/>
<property name="loginModule" value="com.sun.security.auth.module.NTLoginModule"/>
</properties>
</security-provider>
In the above configuration, we have added a further property for the loginModule where you can add the
LoginModule you wish to use to authenticate the user. Since the NTLoginModule does not require you to
input a list of accepted usernames and passwords, the property for the "credentials" was removed.
PGP Security
This extension adds PGP security on endpoint communication.
With PGP you can achieve end-to-end security communication with signed and encrypted messages
between parties.
Requirements
You need to add these libraries to Mule classpath:
• Cryptix OpenPGP
• Cryptix JCE
http://java.sun.com/j2se/1.4/download.html
http://java.sun.com/j2se/1.5.0/download.jsp
The default distribution of the JCE allows as Sun calls it 'strong, but limited strength
cryptography'. This basically means that you cannot use RSA keys bigger than 2048 bits,
and no symmetric ciphers that use more than 128 bits. ElGamal is not allowed at all, thus
DH/DSS cannot be used for encryption.
securityContext.xml
<beans>
<bean id="pgpKeyManager" class="org.mule.extras.pgp.PGPKeyRingImpl"
init-method="initialise">
<property name="publicKeyRingFileName">
<value>pubring.gpg</value>
</property>
<property name="secretKeyRingFileName">
<value>secring.gpg</value>
</property>
<property name="secretAliasId">
<value>0x6168F39C</value>
</property>
<property name="secretPassphrase">
<value>TestingPassphrase</value>
<bean id="fakeCredentialAccessor"
class="org.mule.extras.pgp.FakeCredentialAccessor" />
</beans>
Our goal is to define a sample echo application that reads signed (and encrypted) files from a directory (/
temp/signedAndEncryptedFiles/in)
and write the decrypted content into /temp/decryptedFiles/out
<encryption-strategy name="KBE"
className="org.mule.extras.pgp.KeyBasedEncryptionStrategy">
<properties>
<container-property name="keyManager" reference="pgpKeyManager" />
</properties>
</encryption-strategy>
</security-manager>
<model name="echoTest">
<mule-descriptor name="echo" containerManaged="false"
implementation="org.mule.extras.pgp.EchoMsg">
<inbound-router>
<endpoint address="file:///temp/signedAndEncryptedFiles/in">
<security-filter
className="org.mule.extras.pgp.filters.PGPSecurityFilter">
<properties>
<property name="strategyName" value="KBE"/>
<property name="signRequired" value="true"/>
<container-property name="credentialsAccessor"
reference="fakeCredentialAccessor"/>
<container-property name="keyManager"
</inbound-router>
<outbound-router>
<router
className="org.mule.routing.outbound.OutboundPassThroughRouter">
</router>
</outbound-router>
</mule-descriptor>
</model>
</mule-configuration>
The property signRequired in the inbound security filter controls if we accept unsigned message or not.
the property authenticate in the outbound security filter controls if we want to encrypt messages for the
receiver
..and they said "free email account"...but I read "free persistent message queue"...
– Alessandro Riva
Properties
Ws-Security uses certificates to encrypt or sign parts, or all, of the message being sent. Hence valid
certificates are a must. Also a must is the properties files that tell the Ws-Security Filter and handlers
how to decode the message. The example properties file below demonstrates what the properties file
should include. Here we use Apache's crypto provider Merlin as our crypto provider which is available with
Apache's WSS4J. Example of a properties file used to decode incoming ws-secured messages:
org.apache.ws.security.crypto.provider=org.apache.ws.security.components.crypto.Merlin
org.apache.ws.security.crypto.merlin.keystore.type=jks
org.apache.ws.security.crypto.merlin.keystore.password=keyStorePassword
org.apache.ws.security.crypto.merlin.alias.password=mulePassword
org.apache.ws.security.crypto.merlin.keystore.alias=mulealias
org.apache.ws.security.crypto.merlin.file=privatestore.jks
<beans>
<bean id="passwords" class="org.mule.extras.wssecurity.callbackhandlers.PasswordContainer">
<constructor-arg>
<props>
<prop key="mulealias">mulePassword</prop>
<prop key="gooduser">goodUserPassword</prop>
</props>
Ws-Security on Xfire
When receiving a Ws-Secured message we need to set the WsSecurityFilter on the required endpoint. The
proper encryption and signature property files need to be added as properties of the filter to be able to
decrypt or verify the signature on the incoming message.
The WsSecurityFilter will set the appropriate handlers (the DOMInHandler and the MuleWSSInHandler) on
the service and lets WSS4J take care of the security.
By setting the WsSecurityFilter on the outbound endpoint you can secure an outgoing message.
Depending on the properties found on the message you can sign or encrypt the message. Don't forget to
include the signature/encryption property files as properties of the filter.
You can configuring the WsSecurityFilter on the outbound endpoint in exactly the same way as for the
inbound endpoint.
If you want to secure an outbound message but the WS-Security properties are not yet set on the
message, then you can set these as properties on the Security Filter and they will be set on your
outbound message for the authentication process.
If you require additional Client handlers, you can add these to the connector as shown in the following
configuration.
Ws-Security on Axis:
Although very similar to the Xfire configuration, there are some differences in how the connector is
configured.
As seen in the configuration above, Axis requires the client and server configurations on which the
security considerations will be placed, i.e. required actions, the password callback class, handlers as well
as username and password to be used.
org.apache.ws.security.saml.issuerClass=org.apache.ws.security.saml.SAMLIssuerImpl
org.apache.ws.security.saml.issuer.cryptoProp.file=out-signed-security.properties
org.apache.ws.security.saml.issuer.key.name=mulealias
org.apache.ws.security.saml.issuer.key.password=mulePassword
org.apache.ws.security.saml.issuer=mulealias
org.apache.ws.security.saml.subjectNameId.name=uid=mule,ou=people,ou=saml-demo,o=example.com
org.apache.ws.security.saml.subjectNameId.qualifier=www.example.com
org.apache.ws.security.saml.authenticationMethod=passwordorg.apache.ws.security.saml.confirmationMethod=senderV
Example of sending Saml Properties with a Mule Message using the MuleClient
The following code snippet shows how Saml properties can be sent with a message to mule. The
message, below, is sent over Xfire so Xfire's WSHandler properties were used.
The SIG_KEY_ID property has to be set to "DirectRefenence" when using Xfire for Saml as the
IssuerSerial method is not currently supported.
// Send Message
UMOMessage m = client.send("xfire:http://localhost:8282/MySecuredUMO?method=echo","Test",props);
Please note, that when the Ws-Security properties are sent to Mule in this fashion, the
DOMInHandler and the MuleWSSInHandler must be configured on the connector as
"clientOutHandlers" in order for the message to become secure.
Mule and Spring can integrate on different levels. You can can choose as much or little Mule in your
Spring application or Spring in your Mule application. The following pages describe in detail how you can
use Mule and Spring together.
Sandbox
There are currently two Spring-related additions in the MULECDEV:Sandbox. Take a
look and if you want to help get them into the main distribution, get involved!
You can configure a Spring context for Mule using Mule Xml. This means you can use Spring to wire
together a Mule instance without needing to write all the bean definitions yourself, which can be quite
time consuming and difficult to maintain. Plus you get the benefits of configuring Mule in domain-specific
Mule Xml.
To configure Mule using a Spring context with Mule xml, simply pass the Mule Xml configuration file to the
SpringConfigurationBuilder
This isn't very useful in itself, but what you can do is combine Spring beans in your Mule Xml to take
advantage of Springs advanced wiring capabilities. For example, if you wanted to set a property on a
Mule component using a factory method, you can use Spring configuration to do this.
There are element name clashes between Spring Xml and Mule Xml configuration. As such certain
configuration elements in Spring have to be prepended with spring- when being used in Mule Xml. The
following table lists the affected tags.
<map> <spring-map>
<list> <spring-list>
<entry> <spring-entry>
<!-- and you can still use normal Mule propery elements -->
<property name=jndiDestinations" value="true"/>
</properties>
</connector>
When using spring elements you can use all the configuration elements that Spring provide. The above
configures the jndiContext, connectionFactory and jndiDestinations properties on the JmsConnector.
If you want to mix beans in with your Mule Xml (like above) add the following DOCTYPE declaration to
your config file
The Spring configuration builder uses the DOCTYPE to determine how to load the configuration file.
Any Mule configuration files will be transformed into Spring bean xml before being loaded into a Spring
context.
You can mix any number of configuration files when using the SpringConfigurationBuilder just so long as
the DOCTYPE declaration uses one of the following dtds.
DTD Type
So if you had three different xml configuration files and each one used a different configuration format,
defined by the dtds, you could load all of them using the SpringConfigurationBuilder and they can be on
the classpath or the file system.
There is now no need to write Spring Bean configurations for Mule yourself as Mule can
auto-generate Spring Bean XML from Mule XML. See Configuring a Spring context using
Mule Xmlfor more information.
It is still possible to configure Mule in the ways described below and this page is left here
for reference.
Better yet, MULE-659describes how you can bootstrap Mule from Spring. The <container-
property/> elements will work without an <container-context/> element.
The MuleManager can be created directly from a Spring context. This means you can distribute your
MuleManager as a Spring applicationContext.xml file. Mule provides a Spring FactoryBean for creating the
MuleManager instance, where there are two implementations -
Many objects in Mule, such as connectors, transformers and managed components have a unique
name attribute that must be set. Most of the time the Spring bean ID will be the same as the name
for the Mule object so you can get Spring to set the bean ID's to Mule object names by declaring the
MuleObjectNameProcessor bean in the container -
Using AutowireUMOManagerFactoryBean
In order to use the AutowireUMOManagerFactoryBean you must define a muleManager bean as an
instance of org.mule.extras.spring.config.AutowireUMOManagerFactoryBean. The name of the bean is not
important to Mule. This factory bean is responsible for determining the instance type of UMOManager to
create then delegate configuration calls to that instance depending on what is available in the container.
Apart from removing the need to explicitly wire the MuleManager instance together there is another
advantage to using the AutowireUMOManagerFactoryBean. There is no need to declare a UMOModel
instance in the configuration. If the factory doesn't find a UMOModel implementation it creates a
default one of type org.mule.impl.model.MuleModel. The model is automatically initialized with a
SpringComponentResolver using the current applicationContext and defaults are used for the other model
properties. If you want to override the defaults, such as define your own exception strategy, (which
you will most likely want to do) simply declare your exception strategy bean in the container and it will
automatically be set on the model.
Mule requires a manager ID be available if JMX management is in use (since Mule 1.3.1).
You can set the managerId property on this factory bean to configure it.
Most Mule objects have explicit types and can be autowired, however some objects cannot be autowired,
such as a java.util.Mapof endpoints for example. For these objects Mule defines standard bean names
that will be looked for in the container during start up.
muleEnvironmentProperties
A map of properties to set on the MuleManager. Accessible from your code using
AutowireUMOManagerFactoryBean.MULE_ENVIRONMENT_PROPERTIES_BEAN_NAME.
muleEndpointMappings
A Map of logical endpoint mappings accessible from your code using
AutowireUMOManagerFactoryBean.MULE_ENDPOINT_MAPPINGS_BEAN_NAME.
muleInterceptorStacks
Using UMOManagerFactoryBean
Configuration with the UMOManagerFactoryBean is more involved but is sometimes useful when testing
as you explicitly control what objects are configured on the MuleManager. In order to use it you must
define a muleManager bean as an instance of org.mule.extras.spring.UMOManagerFactoryBean. Again,
the name of the bean is not important. This is a factory bean that creates a MuleManager instance (or
deriving type) and then delegates configuration calls to that instance. Each of the dependencies of the
MuleManager must be defined explicitly in the configuration.
Some of the properties of the bean have local references to java.util.List and java.util.Map beans in the
container, if you do not want these collection objects floating around in your container you can always
declare each property as a <list> or <map> and add the bean refs inline. For example, the endpoints are
declared 'inline' negating the need to declare a endpointList bean in your applicationContext.xml.
For more information about configuring the Spring Application Context you can go to the Spring web site.
1. Objects that are managed by Mule. Mule managed objects cannot be singletons because
components are pooled and each pooled instance is expected to be different.
2. Mule endpoints. Endpoints are mutable and can be global, meaning that more than one component
can reference the same instance. It is feasible that users of the same endpoint might want to
update the endpoint or properties as runtime. Initializing the endpoints as a singleton would mean
those changes would affect all other components referencing the same endpoint.
3. Mule Transformers. For the same reasons as endpoints, transformers should not be singletons.
Configuration Example
Below is a simple but complete configuration for Mule. It defines a single managed component
'orderProcessor' and an inbound and outbound JMS endpoint, a couple of JMS transformers and some
endpoint mappings. This example uses the AutowireUMOManagerFactoryBean and no model is defined so
a default one will be created. Notice that the orderProcessorDescriptor and endpoints are not singletons.
<beans>
<bean id="muleManager"
class="org.mule.extras.spring.config.AutowireUMOManagerFactoryBean"/>
<bean id="muleNameProcessor"
class="org.mule.extras.spring.config.MuleObjectNameProcessor"/>
-Dorg.mule.umo.UMOManager=com.foo.MyMuleManager
System.setProperty("org.mule.umo.UMOManager", "com.foo.MyMuleManager");
Here is a sample configuration for starting Mule from Spring posted to the users list by
Conal Markey:
<bean id="muleManager"
class="org.mule.extras.spring.config.AutowireUMOManagerFactoryBean" destroy-
method="dispose" singleton="true"/>
<!-- Used to set mule object names to their corresponding bean id -->
<bean id="muleNameProcessor"
class="org.mule.extras.spring.config.MuleObjectNameProcessor"/>
<!-- The mule client we will use to send events to the mule server -->
<bean id="muleClient" class="org.mule.extras.client.MuleClient" depends-
on="muleManager"/>
I then added this context file to the appropriate context parameter in the web.xml. (If its
not a web app you have then you should be able to just add this to the list of config files
you give the relevant application context builder).
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:com/.../.../config/muleContext.xml
The autowire manager then picks up all the other classes in my context files of mule types.
ApplicationListener.java
To publish events to listeners you call the publishEvent() method the ApplicationContext. This will publish
the same event to every listener in the context.
In Spring 1.1 it is possible to plug in custom Event Handlers into the application context, which is good
news for Mule.
Quick Start
All you need to do to start receiving Mule Events is add the MuleEventMulticaster bean to your
applicationContext and one or more endpoints on which to receive events -
Now any emails recieved for ross@muleumo.org or any JMS messages sent to my.queue will be
received by all Spring event listeners. That's it! you're now receiving events in Spring from Mule.
The inbound endpoints can be any valid Mule Endpoint so you can receive JMS messages, SOAP requests,
files, HTTP and servlet requests, TCP, multicast, etc.
If you are using JMS you will also need to add a Mule JMS connector bean to your
application context. To use ActiveMQ add the following -
For more information about using other JMS servers see Configuring Jms.
It is often more useful to have beans subscribe only to the events they are interested in. The
MuleSubscriptionEventListener adds two new methods for getting and setting an array of endpoints that
the bean will receive events on.
TestSubscriptionBean.java
The bean is configured in the spring context like any other bean.
Publishing events is just as easy are 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 the MuleApplicationEvent.
//Call publish on the application context, Mule will do the rest :-)
applicationContext.publishEvent(muleEvent);
The SpringInvokerComponent Allows Mule transports to be used to invoke Spring Remoting objects or for
Mule services to invoke spring remoting objects.
As the class names may change a bit before the Mule 1.3 final release we're holding of the documentation
investment
However, its very easy to set up and there is a test case configuration file that you can view here.
For our example we are going to use 2 beans; a RestaurantWaiter bean that receives orders, logs the
order and then passes it to the KitchenService bean which receives orders and does 'something' with
them. Our beans look something like this -
//notify kitchen
this.kitchen.submitOrder(order);
}
Setting up Spring
The first thing to do is define your Spring application context. This context will contain our
RestaurantWaiter and KitchenService beans -
<beans>
<bean id='restaurantWaiter' singleton='false' class='com.foo.RestaurantWaiter'>
<property name='kitchenService'><ref local='kitchenService'/></property>
</bean>
So we now have two beans called restaurantWaiter and kitchenService that will be created by Spring.
Notice the resturantWaiter bean is not declared as a singleton (by default, all beans in Spring are
singletons unless specified otherwise). This is important as Mule will pool your components and telling
Spring not to create a singleton ensures that each pooled instance will be a unique instance.
What is important here is the implementation attribute; this is used to identify the bean in the
container at run-time.
<mule-configuration>
....
<container-context className='org.mule.extras.spring.SpringContainerContext'>
<properties>
<property name='configFile' value='../conf/applicationContext.xml'/>
</properties>
</container-context>
....
</mule-configuration>
The configFile property specifies the location of the applicationContext.xml file. It is possible to specify a
classpath resource or a local file path.
Here the <container-property> name attribute refers to the bean mutator method on the managed
component 'restaurantWaiter', the reference denotes the bean name in the container and the required
attributed determines whether or not an exception is thrown if the reference is not found.
See Configuring Properties for more information about configuring Mule objects.
• File
• FTP / SFTP (added in 1.4.1; see MULE-1639)
• SSL
• HTTP
• HTTPS
• TCP
• SOAP (XFire)
Why Streaming
• Allows services to consume very large events in an efficient way
• Event payloads are not read into memory
• Simple routing rules based on event meta-data still possible
• Can combine Streaming and non-streaming endpoints
• Support for Streaming Transformers... on the to do list MULE-1635
All components configured in this model will have to be streaming components. If you want to mix and
match processing models just add more <model> elements to your configuration file.
Streaming works very differently to the usual SEDA event-driven processing model that most Mule users
are already familiar with. Streaming components need to implement the
org.mule.impl.model.streaming.StreamingService
interface -
Notice that the <model> type is 'streaming' and that each of the <endpoint> elements have their
'streaming' attribute set.
Finally, there is a
org.mule.components.simple.StreamingBridgeComponent
Please notice the use of the ForwardingConsumer router set on the inbound-router.
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
Concurrency
Producing Open Source Software: How to Run a Successful Free Software Project by Karl Fogel
Quality Improvement in Volunteer Free and Open Source Software Projects: Exploring the Impact of
Release Management by Martin Michlmayr
1. Components tested with a tck testcase ensures that the common behaviour of the component is
compatible with the Mule framework.
2. Using a tck testcase allows the developer to concentrate on writing tests for specific behaviour of
their component.
3. Where testing of a method in the UMO API cannot be tested by the tck testcase, the testcase
provides an abtract method for the test, ensuring the developer tests all areas of the component.
4. 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 testcases each time.
5. The TCK abstract testcases use JUnit TestCase so they are compatible with other testcases
The following describes the supplied testcases and where to use them.
• MuleProviderDescriptor
• MuleEvent
• MuleSession
• MuleDescriptor
It's a good idea to extend this testcase when testing mule components.|
AbstractEntryPointResolverTestCase
Fruit Test Model The fruit test model provides a set of simple
objects that interact in a common way to provide
an object model to test with. It can be found in
the org.mule.tck.testmodels.fruit.
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. Whatever type the
transaction is it can be handled the same way. Mule transactions are configured on inbound endpoints,
where an endpoint can be configured to start a new transaction or join an existing one. The outbound
endpoints will automatically enlist in the current transaction, provided that the managed resource is
compatible with the transaction. Transactions are configured on a endpoint using a <transaction> which
maps to org.mule.umo.transaction.UMOTransactionConfig class. This defines what action an endpoint
should take when it receives an event and the transaction factory to use to create transactions.
The configuration defines a JMS message endpoint that sends on a 'test.out' queue. The factory attribute
is a fully qualified path to a TransactionFactory which Mule will use when creating transactions for this
endpoint. The action attribute tells Mule what to do for each event, in this case a new transaction will be
created for every event received. Possible values for action on the <tx-inbound> element are -
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. So when the
inbound
endpoint will have routed the message to the outbound endpoint, the transaction will be commited or
rollbacked.
You can send multiple message using the recipient list router and all messages
will be sent in the same transaction.
XA transactions
XA transactions can be used if you want to enlist multiple managed resources within the same
transaction.
The inbound endpoints are configured in the same manner as for single resource transactions,
but the connectors need to be configured to use xa-enabled resources.
If you run mule outside an application server, you can use Jotm transaction manager to configure an
embedded transaction manager or read the next section.
XA Configuration Example
The following uses a single transaction to read from a Jms Queue and write to a database.
Because the inbound Jms Endpoint has an XATransactionFactory configured on it any outbound endpoints
for the component will also become part of the XA transaction providing that the transport type supports
XA transactions (XA enabled transports are listed above). 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 DataSource.
Depending on your server, you can run Mule either standalone or embedded in the application server. This
is not only your choice, but a requirement for some products, as one server will expose the transaction
manager in JNDI, the other will not, and yet another will grant you access only via proprietary APIs. This
is unfortunate, but still in line with Java EE 1.4 specification, which does not consider the transaction
manager a public API. Thus, you are left to the mercy of your application server vendor.
Weblogic javax.transaction.TransactionManager
org.mule.transaction.lookup.We
<transaction-manager factory="org.mule.transaction.lookup.WeblogicTransactionManagerLookupFactory"
/>
Transaction Coordination
Transaction demarcation is controlled by endpoints. The actual management of transactions is handled
by the Mule TransactionCoordinator. Its important to note that any transacted event flows will be
synchronous. The TransactionCoordinator 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.
To configure an instance of Jotm within mule, just put the following code in your mule xml config file:
Depending on your server, you can run Mule either standalone or embedded in the application server. This
is not only your choice, but a requirement for some products, as one server will expose the transaction
manager in JNDI, the other will not, and yet another will grant you access only via proprietary APIs. This
is unfortunate, but still in line with Java EE 1.4 specification, which does not consider the transaction
manager a public API. Thus, you are left to the mercy of your application server vendor.
Weblogic javax.transaction.TransactionManager
org.mule.transaction.lookup.We
<transaction-manager factory="org.mule.transaction.lookup.WeblogicTransactionManagerLookupFactory"
/>
For introduction to providers see Mule Endpoints and for more information about configuration of
transports in Mule see Configuring Endpoints.
See General Transport Configuration for information about how Transports are configured at runtime.
Rmi Provider
BPM Connector
The BPM connector allows Mule events to initiate and/or advance processes in a Business Process
Management System (BPMS) a.k.a. Process Engine. It also allows executing processes to generate Mule
events.
Overview
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 have
a requirement to integrate with a BPEL engine that only exposes SOAP endpoints (i.e., "a
black box"), you will need to use standard web services. See an example of this here.
Usage
bpm://ProcessType
bpm://ProcessType/ProcessID
bpm://MyBigProcess
bpm://MyBigProcess?processId=4561&action=advance
or just
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, let's 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.
Configuration
Connector Properties
Message Properties
Example config
<model name="bpm_example">
<!-- Messages sent to the process engine -->
<mule-descriptor name="ToBPMS" implementation="org.mule.components.simple.LogComponent">
<inbound-router>
<endpoint address="Incoming1"/>
Therefore, until such a spec. ever emerges, the Mule BPM Transport simply defines its own
// MessageService is a callback method used to generate Mule messages from your process.
public void setMessageService(MessageService msgService);
}
Any BPM engine which then implements this simple interface ( org.mule.providers.bpm.BPMS ) can "plug
in" to Mule via the BPM Transport.
So far, the only engine available with Mule out-of-the-box is JBoss jBPM, but I'm sure the Mule
For general information on jBPM and how to configure it, refer to http://docs.jboss.com/jbpm/v3/
userguide
Configuration
The recommended way to configure jBPM with Mule is using Spring and Spring's jBPM Module
If you wish to configure jBPM without using Spring, you just need to create the
org.mule.providers.bpm.jbpm.Jbpm wrapper based on your jBPM instance and set it as the "bpms"
property on the BPM connector:
MuleManager.getInstance().registerConnector(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.providers.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.
more info... org.mule.providers.bpm.jbpm.actions.SendMuleEvent
StoreIncomingData - Stores the incoming message payload into the specified variable.
more info... org.mule.providers.bpm.jbpm.actions.StoreIncomingData
The Ejb connector allows Ejb session beans to be invoked as part of an event flow. Components can be
given an ejb outbound endpoint which will invoke the remote object and optionally return a result.
The javadoc for this transport provider can be found here. And the Source Xref can be found here.
For example -
Endpoints
Rmi endpoints are described as socket-based endpoints in the form of -
For a given endpoint, the following informationwill have to be written in the uri (uri path and parameter) :
• registry host
• registry port
• romote home name
• remote method name
<endpoint address="ejb://localhost:1099/SomeService?method=remoteMethod">
If the remoteMethod can take 1 or more input arguments then they should be configured on the endpoint
as list properties. This is the syntax that is proved to work in version 1.4.3, a list of comma-separated
values into the property methodArgumentTypes.
<properties>
<list name="methodArgumentTypes">
<entry value="java.lang.String,java.lang.String,java.math.BigInteger"/>
</list>
</properties>
Transformers
There are no specific transformers required for Ejb.
The email provider can be used to connect to Pop3 and Imap mailboxes and for sending events over smtp
using the javax.mail api. For each of the protocol, SSL is supported and is enabled using pop3s, imaps
and smtps respectively.
The email connectors can be used to send and recieve event payloads over Mail protocols and support
protocol features such as attachments, replyTo, CC and BCC addresses, binary content types and custom
headers.
For information about configuring specific endpoints follow the links below -
The file connector allows files to be read and written to and from directories on the local file system. The
connector can be configured to filter the file it reads and the way files are written, such as whether binary
output is used or the file is appended to.
here
here
• ${DATE} - the
current date in the
File Endpoints
File endpoints are expressed using standard File URI syntax -
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 2 slashes for protocol, so it's a relative path, the above syntax is
preferred for readability)
or
file:////192.168.0.1/temp/
Filename Filters
Filters can be set on the endpoint to control what 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 the following can be
used.
<endpoint address="file:///inbound/myfiles">
<filter pattern="*.txt,*.xml"
className="org.mule.providers.file.filters.FilenameWildcardFilter"/>
</endpoint>
Property Overrides
You can override certain properties when defining a File receiver endpoint to control the way
that particular receiver behaves. the properties that can be set on the individual endpoint are
moveToDirectory, moveToPattern, pollingFrequency and autoDelete.
<endpoint address="file:/./temp/myfiles">
<properties>
<property name="pollingFrequency" value="30000"/>
<property name="moveToDirectory" value="./temp/myfiles/done"/>
</properties>
</endpoint>
file:/./temp/myfiles?pollingFrequency=1000&moveToDirectory=./temp/myfiles/done
Transformers
Transformers for the File provider can be found at org.mule.providers.file.transformers.
Transformer Description
The FileToByteArray is used if no other transformers are specified. It could also return the byte array as a
String if the component request it.
Comparators
Class Description
org.mule.providers.file.comparator.OlderFirstComparator
comparing files for equality based on their
modification dates
<endpoint address="file://./.mule/in">
<properties>
The FTP connector allows files to be read and written to and from remote FTP servers.
The javadoc for this transport provider can be found here. And the Source Xref can be found here.
• ${DATE} - the
current date in the
format dd-MM-
yy_HH-mm-ss.SS
• ${DATE:yy-MM-
dd} - the current
date using the
specified format
• ${SYSTIME} - The
current system
time milliseconds
• ${UUID} -
A generated
Universally unique
id
• ${ORIGINALNAME}
- The original file
name if the file
being written was
read from another
location
• ${COUNT} -
An incremental
counter
FTP Endpoints
FTP endpoints are expressed using standard FTP URI syntax -
ftp://<username>:<password>@<hostname[MULE::port]>/[MULE:address]
for example -
ftp://joe:123456@ftp.mycompany.com/~
This will connect to the FTP server at mycompany.com with a user name of joe with password 123456
and will work on Joe's home directory.
Filename Filters
Filters can be set on the endpoint to control what 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 the following can
be used.
<endpoint address="ftp://joe:123456@ftp.mycompany.com/ftp/incoming">
<filter pattern="*.txt,*.xml"
className="org.mule.providers.file.filters.FilenameWildcardFilter"/>
</endpoint>
Property Overrides
You can override certain properties when defining FTP endpoints to control the endpoint's configuration.
These properties can be set on the endpoint or the current event.
Property Description
<endpoint address="ftp://joe:123456@ftp.mycompany.com/ftp/done">
<properties>
<property name="outputPattern" value="FtpFile-${DATE}.done"/>
</properties>
</endpoint>
ftp://joe:123456@ftp.mycompany.com/ftp/done?outputPattern=FtpFile-${DATE}.done
The javadoc for this transport provider can be found here. And the Source Xref can be found here
keyManagerAlgorithm The Key Manager Depends on the JDK Yes (if keyStore is set)
algorithm to use vendor, automatically
discovered.
provider The sercurity provider Depends on the JDK Yes (if keyStore is set)
object to register vendor, automatically
with the java Security discovered.
manager
Endpoints
Http endpoints are described as socket-based endpoints in the form of -
http://localhost:1234
To use HTTPS instead you need to change the endpoint URI protocol and set the necessary certificate
information listed above -
https://localhost:1234
Unlike HTTP endpoints you can't use HTTPS endpoints without having a connector declared in your
configuration. The HTTPS connector class is org.mule.providers.http.HttpsConnector. The javadoc for this
transport provider can be found here
Endpoint Properties
Any HTTP Response Header values can be added as endpoint properties. The following is a short list of
some of the most useful properties.
The following is a short example, depicting how to set these properties on the endpoint.
In this case, the type of the payload is that of text/html & we are also instructing the client to redirect
('http.status' being set to 307 = temporary redirection) to "http://mule.codehause.org".
Security
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). If you want to configure Http
Basic you need to configure a Security Endpoint Filter on a http endpoint.
<endpoint address="http://localhost:4567">
You'll need to configure a security manager on the Mule instance for this security filter to authenticate
against. For information about security configuration options and examples see Mule Security.
Sending Credentials
If you want to make a Http request that requires authentication, you can set the credentials on the
endpoint -
http://user:password@mycompany.com/secure
To configure the Http Polling receiver you must include a HttpConnector configuration in your MuleXml.
http://anothercompany.com/services?connector=pollingHttp&pollingFrequency=30000
Transformers
The following transformers are available for use. Their javadoc can be found here
Transformer Description
This is both for sending POST request bodies as a client and when returning a response body:
This is both for receiving POST requests (as server) and when getting the response bodies as a client:
The IMAP transport provider can be used to for receiving messages from IMAP inboxes and connecting to
IMAP mailboxes using SSL (IMAPs) using the javax.mail api.
org.mule.providers.email.ImapConnector.
Server Credentials
The host, port and user credentials as set on the imap:// endpoint. If no port is specifed
the default port will be used.
When using the Imaps Connector the default port is set to 993.
Imap(s) Endpoints
Imap endpoints describe details about the connecting to a Imap mailbox. Imap URIs use the following
syntax -
Sometimes you'll have illegal (for URI) characters in your login/password. Use the standard
escape syntax your browser would use, e.g. the username user@mule would become user
%40mule.
For example,
imaps://joe:123456@imap.mycompany.com/mail?checkFrequency=30000
This will log into the imap.mycompany.com server with username joe using password 123456 (using
default IMAPs port) and open the mail folder. It will check the mailbox for new messages every 30
seconds.
To set additional properties on the endpoint, you can set them as parameters on the URI but we
recommend you set them as endpoint properties to make it easier to read and maintain the configuration.
<endpoint address="imaps://username:password@imap.mail.com/mail">
<properties>
<property name="checkFrequency" value="120000"/>
<property name="trustStore" value="./trustore"/>
<property name="trustStorePassword" value="trustNoOne"/>
Filters
Filters can be set on an endpoint to filter out any unwanted messages. The Mail transport provider has a
couple of Email filters that can either be used directly or extended to implement custom filtering rules.
Filter Description
Configuring Filters
The following demonstrates to only accept messages where the email subject starts with [MULE:mule] -
<endpoint address="imaps://username:password@imap.mail.com/lists">
<filter className="org.mule.providers.email.filters.MailSubjectRegExFilter"
pattern="\\[MULE:mule\\](.*)"/>
<properties>
<property name="checkFrequency" value="120000"/>
<property name="trustStore" value="./trustore"/>
<property name="trustStorePassword" value="trustNoOne"/>
</properties>
</endpoint>
Transformers
There are a couple of transformers provided with the Email transport that are useful for converting
javax.mail.Message to Mule event payloads. These transformers will extract the message body and
properties (including headers) and handle attachments too. If you need to customise the behaviour
of these transformers it is recommended that you extends the existing transformers rather than re-
implement them.
Transformer Description
The Jdbc provider can be used to connect to relational databases using jdbc. It supplies reads and writes
to simple tables with acknowledgement of read rows.
The javadoc for this transport provider can be found here. And the Source Xref can be found here
Configuring queries
Sql queries are used by endpoints and should be configured on the connector or the endpoint.
Queries are stored in a map and keyed by their name.
This name will be retrieved from the address of the endpoint.
The queries can be parameterized using a simple syntax. Parameters can be enclosed in a ${...}
pattern.
When the query is executed, each parameter will be looked for in the following way:
• check if the given parameter has been included as a parameter in the endpoint uri
• if there is an input (ack and write queries), evaluate the expression as a java bean property on the
input
For ack queries, the input is defined as the payload that will be sent as an UMOMessage. If you want to
access a specific column that has been read, you can thus use the expression ${myColumn} which will be
evaluated on the message.
For write queries, the input is defined as the UMOMessage itself. If you want to access to the whole
payload, you can thus use the expression ${payload} which will be evaluated on the message.
To use the jdbc connector, you must first configure the connector in the mule xml configuration file.
<bean id="myDataSource"
class="org.enhydra.jdbc.standard.StandardDataSource"
destroy-method="shutdown">
<property name="driverName"><value>org.hsqldb.jdbcDriver</value></property>
<property name="url"><value>jdbc:hsqldb:file:db/test</value></property>
</bean>
else, to retrieve the dataSource from a jndi repository, you would use
Creating queries
Sql queries used by endpoints should be configured on the connector or the endpoint.
<map name="queries">
<property name="getTest"
value="SELECT ID, TYPE, DATA, ACK, RESULT FROM TEST WHERE TYPE =
${type} AND ACK IS NULL"/>
<property name="getTest.ack"
value="UPDATE TEST SET ACK = ${NOW} WHERE ID = ${id} AND TYPE =
${type} AND DATA = ${data}" />
<property name="writeTest"
value="INSERT INTO TEST(ID, TYPE, DATA, ACK, RESULT) VALUES(NULL,
${type}, ${payload}, NULL, NULL)" />
</map>
Creating components
For a receiver,
For a dispatcher
<mule-descriptor name="..."
implementation="..."
inboundEndpoint="..."
outboundEndpoint="jdbc://writeTest?type=1" />
This is a standard Jms 1.0.2b and 1.1 connector. This connector exposes all features defined in the
1.0.2b/1.1 Specification.
The javadoc for this transport provider can be found here. And the Source Xref can be found here.
connectionFactoryProperties
Any properties to No
be passed to the
javax.jms.ConnectionFactory,
e.g. to set some
vendor-specific
properties.
connectionFactoryJndiName
The name of the JNDI Yes (if using jndi)
configured connection
factory to use.
When specifying a destination name and JndiDestinations are not being used the default destination
created is a Queue.
For example the Jms endpoint
jms://my.destination
will manifest itself as a Jms Queue called my.destination. To make this a topic you must prepend the
destination name with topic:-
jms://topic:my.destination
If you are using a Jms 1.1 compliant server you can use the same JmsConnector for 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 will need to create 2 JmsConnectors; one with a jndiConnectionfactory that references
a QueueConnectionFactory and the other that references a TopicConnectionfactory. Then each Jms
endpoint will need to reference the correct connector depending on whether the destination is a topic or a
queue. To specify the conector on a jms endpoint you need to add the connector parameter -
jms://my.destination?connector=jmsQueueConnector
or
jms://topic:my.destination?connector=jmsTopicConnector
Specifying Credentials
Client connections may need to supply a username and password when creating a connection. This
information can be specified on the URI.
jms://ross:secret@my.destination?createConnector=ALWAYS
or
jms://ross:secret@topic:my.destination?createConnector=ALWAYS
Note that the 'createConnector' param is set to 'ALWAYS'. This ensures that a new connection is
made with the user credentials. When creating JmsConnectors more information is is needed such as
ConnectionFactory Jndi details. This can be set as parameters on the URI, but this can get difficult to
manage not to mention messy. It is possible to set default properties for connectors when they are
created. For more information see this Jms cookBook entry.
See Mule Endpoint URIs for more general information about configuring endpoint URIs.
Jms Selectors
You can set a Jms selector as a filter on an endpoint. The JmsSelectorFilter simply sets the filter
expression on the consumer.
<endpoint address="jms://important.queue">
<filter expression="JMSPriority=9"
className="org.mule.providers.jms.filters.JmsSelectorFilter"/>
</endpoint>
<endpoint address="jms://important.queue">
<properties>
<property name="selector" value="JMSPriority=9"/>
</properties>
</endpoint>
jms://important.queue?selector=JMSPriority=9
Durable Subscribers
Durable subscribers can be used by setting the durable property on the JmsConnector, this tells it to
make all topic subscribers durable. Only Topic subscriptions can be durable. When a durable subcriptions
a durableName is needed by the Jms server to identfy this subscriber. By default, Mule generates a
durableName in the following form -
However, if you want to set the durableName yourself, you can do so on the endpoint by setting the
durableName property.
<endpoint address="jms://topic:durable.topic">
<properties>
<property name="durableName" value="myDurableSubscription"/>
</properties>
</endpoint>
or the equivilent -
jms://topic:durable.topic?durableName=myDurableSubscription
You can also specify certain endpoints to be durable while others are not by setting the durable property
on the JmsConnector to false and then setting the durable property on the individual endpoints.
<endpoint address="jms://topic:durable.topic">
<properties>
<property name="durable" value="true"/>
</properties>
</endpoint>
or the equivilent -
jms://topic:durable.topic?durable=true
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 customise the way Jms resources are initialised.
Configuring this customisation requires that you tell the JmsConnector to use a custom JmsSupport class.
Transformer Description
When the message is received and transformed all the message properties are still available via the
UMOMessage object. To access sandard Jms properties such as JMSCorrelationID and JMSRedelivered
simply use the property name i.e.
any custom header properties on the message can be accessed the same way.
The multicast connector can be used to send and receive mule events via multicast groups.
The javadoc for this provider can be found here.
Transformers
The following transformers are used by default for this connector unless a transformer is explicitly set on
the provider.
Transformer Description
The Pop3 transport provider can be used to for receiving messages from POP3 inboxes and connecting to
POP3 mailboxes using SSL (POP3s) using the javax.mail api.
org.mule.providers.email.Pop3Connector.
The host, port and user credentials as set on the pop3:// endpoint. If no port is specifed
the default port will be used.
When using the Pop3s Connector the default port is set to 995.
Pop3(s) Endpoints
Pop3 endpoints describe details about the connecting to a Pop3 mailbox. Pop3 URIs use the following
syntax -
pop3://<user:password>@<pop3 server>[MULE::port][MULE:?params]
pop3s://<user:password>@<pop3 server>[MULE::port][MULE:?params]
Sometimes you'll have illegal (for URI) characters in your login/password. Use the standard
escape syntax your browser would use, e.g. the username user@mule would become user
%40mule.
For example to connect to a Google gmail box you need to use POP3s,
pop3s://muletestbox:123456@pop.gmail.com?checkFrequency=30000
This will log into the muletestbox mailbox on pop.gmail.com using password 123456 (using default POP3s
port) and will check the mailbox for new messages every 30 seconds.
To set additional properties on the endpoint, you can set them as parameters on the URI but we
recommend you set them as endpoint properties to make it easier to read and maintain the configuration.
<endpoint address="pop3s://username:password@pop.mail.com">
<properties>
<property name="checkFrequency" value="120000"/>
<property name="trustStore" value="./trustore"/>
<property name="trustStorePassword" value="trustNoOne"/>
</properties>
</endpoint>
Filter Description
Configuring Filters
The following demonstrates to only accept messages where the email subject starts with [MULE:mule] -
<endpoint address="pop3s://username:password@pop.mail.com">
<filter className="org.mule.providers.email.filters.MailSubjectRegExFilter"
pattern="\[MULE:mule\](.*)"/>
<properties>
<property name="checkFrequency" value="120000"/>
<property name="trustStore" value="./trustore"/>
<property name="trustStorePassword" value="trustNoOne"/>
</properties>
</endpoint>
Transformers
There are a couple of transformers provided with the Email transport that are useful for converting
javax.mail.Message to Mule event payloads. These transformers will extract the message body and
properties (including headers) and handle attachments too. If you need to customise the behaviour
of these transformers it is recommended that you extends the existing transformers rather than re-
implement them.
Transformer Description
Quartz provider supplies scheduling features to Mule. This provider is based on the great scheduler
Quartz from OpenSymphony.
The javadoc for this transport provider can be found here. And the Source Xref can be found here
jobGroupName mule No
Additionally, other properties need to be set depending on the type of Job being used. The following
describes the standard Mule Jobs and how to configure them.
Jobs
Mule provides a number of default Job implementations that help orchestrate scheduled events -
• Mule Receiver Job - An inbound endpoint job that schedules events to a Mule component
• Delegating Job - And outbound endpoint job that will schedule a job that is attached to the Mule
Event.
• Mule Client Dispatch Job - An outbound endpoint job that will dispatch the event on a given endpoint
URI.
• Mule Client Receiver Job - An outbound endpoint job that will perform a receive on an endpoint and
then will dispatch the result over a different endpoint.
This is the Job used when an inbound quartz endpoint is configured on a component. It triggers an event
to be received by the component based on the endpoint configuration.
<endpoint address="quartz:/myService">
<properties>
<property name="repeatInterval" value="1000" />
<property name="payloadClassName" value="com.foo.bar.Payload" />
</properties>
</endpoint>
<endpoint address="quartz:/myService?repeatInterval=1000&payloadClassName=com.foo.bar.Payload"
/>
The payload can be set on the endpoint using the following mutually exclusive properties -
Property Description
Extracts the Job object to invoke Mule Event that was dispatched to the quartz endpoint. The job can
either be set as a property on
the event (this property can be a container reference or the actual job object) or the payload
The following properties can be set on the MuleEvent before the event is dispatched to quartz -
Property Description
If the Job is set as the payload of the event, these properties will be ignored and the DelegatingJob will
be used automatically.
To explicitly configure the Delegating Job, you need to configure an outbound endpoint -
Can be used to schedule a one-off or repeated message dispatch to a Mule endpoint. To Configure this
Job you add an outbound endpoint with the following configuration -
Property Description
The event payload dispatched with be the same event that triggered the sheduling of the job. The
payload will also be the same for each execution of the job. Usually, this Job will be used for one-off
execution, to delay event delivery to a later date/time.
Is similar to the MuleClientDispatchJob but will first perform a receive on an endpoint before doing a
dispatch. The dispatch will not happen if the receive yielded null.
The configuration is the same as for MuleClientDispatchJob except there a couple of new parameters -
Property Description
Cron Expressions
A cron endpoint can be configured this way -
<endpoint address="quartz:/myService">
<properties>
<property name="cronExpression" value="0 0 2 * * ?" />
....
</properties>
</endpoint>
<model name="sample">
<mule-descriptor name="scriptRunner"
implementation="org.mule.components.script.jsr223.ScriptComponent">
</mule-configuration>
The rmi connector can be used to send and receive mule events over jrmp.
Endpoints
Rmi endpoints are described as socket-based endpoints in the form of -
rmi://localhost:1099
For a dispatcher:
For a given endpoint (outbound), several info will have to be written in the uri (uri path and parameter) :
• registry host
• registry port
• service name (jndi object name)
• remote method name
<endpoint address="rmi://localhost:1099/SomeService?method=remoteMethod">
If remoteMethod can take 1 or more input arguments then they should be configured on the endpoint as
list properties.
<properties>
<list name="methodArgumentTypes">
<entry value="java.lang.String"/>
<entry value="java.lang.String"/>
</list>
</properties>
Transformers
There are no specific transformers for Rmi at the moment.
SalesForce Connector
Now available on MuleForge.
The servlet connector is really just facade to a Sevlet implementation. The implementing servlet does the
work of receiving a request, the connector can then hand-off the request to any receivers registed with
it. There is no notion of a dispatcher for this connector, it is triggered by a request and may or may not
return a response.
Mule provides a REST style service implementation that uses the servlet connector. For more information
see MULE:Mule REST.
The javadoc for this transport provider can be found here . And the Source Xref can be found here .
The connector class name is org.mule.providers.http.servlet.ServletConnector .
For more information about using Mule with Servlet containers, see MULEINTRO:Embedding Mule in a
Webapp.
SFTP Connector
Now available on MuleForge.
Background
This example demonstrates sending and receiving a file message from an SFTP service, using the Mule
SFTP Connector.
This is a simple example that accepts text input from the console, then dispatches that text input as a file
to an SFTP service. Then, the same file is received from the SFTP service and printed to the console.
The starting directory for this sample is the "examples" directory, found in either your SFTP Connector zip
directory if you installed from binary, or your Subversion workspace if you built from source.
1. Open conf/mule-sftp-examples-config.xml in a text editor. Change the sftp endpoint URIs to match
your sftp service (there are 2 of them, so make sure to change them both). For this example, use the
same directory for both the inbound and outbound sftp endpoints.
For most Unix/Linux sftp services, ~/path/to/dir above would translate to the absolute path
of /path/to/dir. Using FreeSSHd on Windows, you set the base path for all users, so /path/
to/dir would be relative to that base. |
Make sure the user has permissions to access the directory specified.
3.Start your Mule 1.3.3 server with the configuration we edited in Step 1:
4. After startup, you should see something like this in the console:
**********************************************************************
* Mule ESB and Integration Platform version Not Set *
* Not Set *
* For more information go to http://mule.mulesource.org *
* *
* Server started: Monday, March 19, 2007 1:17:21 AM PDT *
* Server ID: SFTP_TEST *
* JDK: 1.5.0_11 (mixed mode) *
* OS: Windows XP - Service Pack 2 (5.1, x86) *
* Host: QMULE (192.168.1.101) *
* *
* Agents Running: *
* Mule Admin: accepting connections on tcp://localhost:60504 *
**********************************************************************
INFO 2007-03-19 01:17:22,734 [MULE:WrapperSimpleAppMain] org.mule.MuleServer: Mule S
erver initialized.
5. By entering text to the console at the prompt above, Mule will dispatch a file message to the SFTP
service specifed in Step 1. You will then see the following (linebreaks added for readability):
The INFO logging tells you that Mule was able to connect and write to the resource sftp://
mule:test123@localhost/files/sftp-target.
6. The SFTP Connector uses a PollingMessageReceiver to retrieve files from an SFTP. Since we
configured the polling frequency to be 10 seconds, you should see the following in the console in 10 s
(linebreaks added for readability):
Prerequisites
Winzip/Gzip any
$M2_REPO/com/jcraft/jsch/0.1.29/jsch-0.1.29.jar
Note: The $M2_REPO location on Linux/Unix the location is ~/.m2 by default. On Windows it's usually c:/
Documents and Settings/<user>/.m2.
The 1.3.3 version of the SFTP connector is based on the JSCH 0.1.29 library.
Installation Instructions and Examples are also available. More examples can be found in the
MULE:#Unit Tests section below.
• ${DATE}- the
current date in the
format dd-MM-
yy_HH-mm-ss.SS
• ${DATE:yy-MM-
dd}- the current
date using the
specified format
• ${SYSTIME}- The
current system
time milliseconds
• ${UUID}- A
generated
Universally unique
id
• ${ORIGINALNAME}-
The original file
name if the file
being written was
SFTP Endpoints
SFTP endpoints are expressed using the standard URI of:
sftp://<username>:<password>@<host>/path/to/dir
This endpoint would connect over SFTP to myhost.com as mule/test123, then read or write to ~/tmp/
mule-vfs.
Transformers
Transformer Description
org.mule.providers.sftp.transformers.InputStreamByteArray
Materializes an InputStream into a byte array
This transformer makes it possible to use the SFTP Message Receiver with non-streaming Service
Components or Message Dispatchers. Typical usage is to add this transformer to an SFTP receiving
endpoint, so that downstream Service Components or Message Dispatchers can deal with a byte[] instead
of InputStream. Note however that materializing an InputStream for a large file will cause OOM errors,
so this transformer should not be used if large files are expected.
Unit Tests
org.mule.providers.sftp.LargeFileSendFunctionalTestCase
Tests ability of the SftpMessageDispatcher to
send a large file. The file is streamed from /tmp/
big.zip on the local machine.
org.mule.providers.sftp.SendReceiveFunctionalTestCase
Tests a round trip send/receive of multiple files.
here
org.mule.providers.email.SmtpConnector org.mule.providers.email.SmtpsConnector
Server Credentials
The host, port, and user credentials are set on the smtp:// endpoint and the additional
properties on the connector act as defaults if the same properties are not set on the
endpoint.
When using the Smtps Connector the default port is set to 465.
Smtp(s) Endpoints
Smtp endpoints describe details about the Smtp server and the recipients of messages sent from the
Smtp endpoint. Smtp URIs use the following syntax -
For example,
smtp://muletestbox:123456@smtp.mail.yahoo.co.uk?address=dave@mycomany.com
Will send mail using smtp.mail.yahoo.co.uk (using default smtp port) to the address
dave@mycomany.com. The Smtp request is authenticated using username muletestbox and password
123456.
You will probably want to set other information such as subject and fromAddress. These can be set as
parameters on the URI but we recommend you set them as endpoint properties to make it easier to read
and maintain the configuration.
<endpoint address="smtp://muletestbox:123456@smtp.mail.yahoo.co.uk?
address=dave@mycomany.com">
<properties>
<property name="fromAddress" value="steve@mycompany.com"/>
<property name="ccAddresses" value="john@mycompany.com,rex@foo.com"/>
<property name="subject" value="Please verify your ebay account details"/>
</properties>
</endpoint>
So far, all configurations has been static in that you define all the information in the configuration of the
endpoint. However, you can set the following properties on the MuleMessage to control the settings of the
outgoing Smtp Message. These properties will override the endpoint properties -
MailProperties.TO_ADDRESSES_PROPERTY
toAddresses comma-separate list of
addresses
MailProperties.CC_ADDRESSES_PROPERTY
ccAddresses comma-separate list of
addresses
MailProperties.BCC_ADDRESSES_PROPERTY
bccAddresses comma-separate list of
addresses
MailProperties.REPLY_TO_ADDRESSES_PROPERTY
replyToAddresses comma-separate list of
addresses
MailProperties.FROM_ADDRESS_PROPERTY
fromAddress single email address
MailProperties.CUSTOM_HEADERS_MAP_PROPERTY
customHeaders A Map of string header
properties
MailProperties.CONTENT_TYPE_PROPERTY
contentType The Mime content type of the
message
If you always want to set the email address dynamically, you can leave out the address parameter on the
Smtp endpoint.
Transformers
There are a couple of transformers provided with the Email transport that are useful for converting Object
payloads to javax.mail.Message types. These transformers adhere to the rules listed above and handle
attachments too. If you need to customise the behaviour of these transformers it is recommended that
you extends the existing transformers rather than re-implement them.
The soap provider can be used to publish and invoke services using either Apache Axis, XFire or
WebMethods Glue.
The SOAP transport in Mule allows soap endpoints to be defined as -
soap:http://localhost:1234/MyService
and the actual SOAP stack used to execute this service will be discovered based on the first SOAP stack
available on the class path.
For more information about using Web services and Mule see -
• Axis
• XFire
• Glue
The Ssl connector can be used for secure socket communication using ssl or tls.
The javadoc for this transport provider can be found here. And the Source Xref can be found here
keyManagerAlgorithm The Key Manager Depends on the JDK Yes (if keyStore is set)
algorithm to use vendor, automatically
discovered.
provider The sercurity provider Depends on the JDK Yes (if keyStore is set)
object to register vendor, automatically
with the java Security discovered.
manager
clientKeyStorePassword
Endpoints
SSL endpoints are described as socket-based endpoints in the form of -
ssl://localhost:1234
To use TLS instead of SSL you just need to change the endpoint URI protocol -
tls://localhost:1234
Transformers
The following transformers are used by default for this connector unless a transformer is explicitly set on
the provider.
Transformer Description
The Stream Provider allows the reading and writing of streaming data. Typically, this is used as the
interface to Java's System.out and System.in objects for debugging via the System Stream Provider.
A typically use of the System Stream Provider for getting data via System.in is like this:
Note that no <connector> definition is required per se: use of the stream endpoint tells Mule to use the
SystemStreamConnector. However, if you need to define it explicitly, you can do so like this:
<connector name="SystemStreamConnector"
className="org.mule.providers.stream.SystemStreamConnector">
<properties>
<property name="promptMessage" value="Enter something: "/>
<property name="messageDelayTime" value="1000"/>
</properties>
</connector>
A typically use of the System Stream Provider for sending data to the console via System.out is like this:
<outbound-router>
<router className="org.mule.routing.outbound.OutboundPassThroughRouter">
<endpoint address="stream://System.out" transformers="JMSMessageToObject"/>
</router>
</outbound-router>
In this example, the output is a JMS message which is sent to System.out. The transformer converts the
JMS message to something readable.
Stream Endpoints
stream://[MULE:stream name]
Property Overrides
You can override certain properties when defining a System Stream endpoint to control the way that
particular receiver or dispatcher behaves. The properties that can be set on the individual endpoint are
promptMessage and outputMessage.
Transformers
Internationalising Messages
If you are internationalising your application as described here, you can also internationalise the
promptMessages and outputMessages for the SystemStreamConnector. (This assumes that you have
already created a resource bundle that contains your messages as described on that page.)
To internationalise, 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 below, the "hello-example" resource bundle means that the
prompt message "3" will be expected in the bundle META-INF/services/org/mule/i18n/hello-example-
messages<langCode>.properties:
<connector name="SystemStreamConnector"
className="org.mule.providers.stream.SystemStreamConnector">
<properties>
<property name="promptMessageCode" value="3"/>
<property name="resourceBundle" value="hello-example"/>
The tcp connector can be used to send and receive mule events over tcp.
The javadoc for this transport provider can be found here. And the Source Xref can be found here
tcpProtocol An implementation of No
TcpProtocol interface
maxRetryCount Removed: A - -
Connection Strategy
should be used to
manage connection
Endpoints
Tcp endpoints are described as socket-based endpoints in the form of -
tcp://localhost:1234
Transformers
The following transformers are used by default for this connector unless a transformer is explicitly set on
the provider.
Transformer Description
Protocols
When transfering data with other applications, it may be necessary to use custom application level
protocols. This is also useful when transfering large amount of data (or when using slow connections) so
that the data are not split.
This protocol is handled with the TcpProtocol interface.
If your protocol implementation does not need configuration, you can use
Protocol Description
org.mule.providers.tcp.protocols.MuleMessageProtocol
writes/reads the complete Mule Message object
(not just the payload), preserving metadata
3
information like correlation IDs (unsafe )
org.mule.providers.tcp.protocols.MuleMessageEOFProtocol
combines MuleMessageProtocol with EOFProtocol
1,2
org.mule.providers.tcp.protocols.MuleMessageLengthProtocol
combines MuleMessageProtocol with
2 LengthProtocol
org.mule.providers.tcp.protocols.XmlMessageEOFProtocol
separates messages by the <?xml prefix on XML
1,2 documents or when the stream closes (so can be
used for multiple messages, unlike EOFProtocol)
1
Cannot be used in Remote Request-Response pattern, because this requires the socket to be open until
response is received
2
Version 2.0 onwards (some may be available in later 1.4 versions too)
3
TCP does not guarantee grouping of data and/or signal the "gap" between "writes", so it is possible that
data within a single message will be received in more than one "chunk". Unsafe protocols cannot handle
such fragmented messages.
AS400 Messaging
DQ
Ejb Remoting
Email Record
File Record
Ftp Record
Http Socket
Imap Messaging
Jdbc Record
Jdbc,
Xa
Jms Messaging
Jms,
Ack, Xa
Multicast Socket
Pop3 Messaging
Quartz Repository
Rmi Remoting
Servlet Socket
Smtp Messaging
Soap: Messaging
Axis
Soap: Messaging
XFire
Soap: Messaging
Glue
WSDL Messaging
Ssl Socket
Tcp Socket
Udp Socket
Vm Messaging
Vm,
Xa
Xmpp Messaging
Heading Descriptions
Transport - The name/protocol of the transport
Type - Whether the transport is a lower level socket-based or higher-level messaging or remoting or if
the interacts with a record store such as a file system or database.
Receive - Whether the transport can receive events and can be used for an inbound endpoint
Send (sync) - Whether events can be send synchronously (in the same thread as the request) using the
transport
Dispatch(async) - Whether events can be send aynchronously
Request/Response - Whether this endpoint can be queried directly with a request and return a
response (Imlementation of the receive() method in UMOMessageDispatcher)
Remote Sync - Whether this transport support remoteSynchronous. This where Mule uses as back
channel automatically to receive a response from a remote host. Transports such as Http support this
implicitly others such as Jms will set up a Temporary ReplyTo Queue to receive a response. This allows
you to chain request/response calls over two or more remote hosts.
Transactions - Whether transactions are supported by the transports. Transports that support (/)A
transactions can be configured in a distributed 2 Phase Commit (Distributed) transaction.
Streaming - Able to work with the Streaming Model and stream data between endpoints. This allows for
very efficient processing of large data.
The udp connector can be used to send and receive mule events as datagram packets.
Transformers
The following transformers are used by default for this connector unless a transformer is explicitly set on
the provider.
Transformer Description
Enables access to and from various protocols such as WebDav, Samba, File System, Jar/Zip and more.
This transport is currently available on MuleForge
Comments
The VM connector is used for intra-VM communication between components managed by Mule. The
connector provides options for configuring VM transient or persistent queues.
VM Connector Properties
Using VM Queues
When using a synchronous VM endpoint events are delivered in memory from one component to another
(asynchronous endpoints introduce an event queue that threads can consume from). However, when the
'queueEvents' property is set, events can be stored in arbitrary memory queues and consumed later by
clients or components. Furthermore these queues can be persistent and XA transactional (see below).
To use VM Queues the 'queueEvents' property must be set on the connector and all VM endpoints
that should queue events must use a VM connector that has queueEvents enabled. You cannot set the
'queueEvents' property on the endpoint, it can only be set at the connector level. i.e.
<model name="TestModel">
<mule-descriptor name="TestComponent"
implementation="org.mule.components.simple.PassThroughComponent">
<inbound-router>
<endpoint address="vm://test.queue" connector="vmQueue"/>
</inbound-router>
</mule-descriptor>
</model>
Notice that the endpoint explicitly tells Mule to use the vmQueue connector. Otherwise Mule will look for
the first connector that matches the protocol for the endpoint.
VM queue can be made persistent so that its state can be maintained between server shutdowns. To
make VM queues persistent you must set a persistence strategy in the Mule Xml configuration. This
strategy is shared for all VM queues in Mule instance.
<mule-environment-properties>
<queue-profile persistent="true" maxOutstandingMessages="1000"/>
<persistence-strategy className="org.mule.util.queue.FilePersistenceStrategy"/>
</mule-environment-properties>
Note you must add a <queue-profile> element for the VM queue configuration and you must also add a
<persistence-strategy> that tells mule how to persist the events. If a <persistence-strategy> is not set,
Mule will use the default in-memory persistence strategy.
Users can write their own persistence strategies to write to a database or some other store if required.
Persistence strategies must implement QueuePersistenceStrategy.
Using Transactions
VM Queues support Transactions and can take part in distributed XA transactions. To make a VM queue
endpoint transactional use the following configuration -
You will also need to add a transaction manager to your configuration. For more information see
Transaction Management.
Endpoints
VM endpoints are 'resource' endpoints in that they just name a resource, there is not host or other
configuration required. For example -
vm://myComponent
Points to an address called 'myComponent', anything listening on vm://myComponent will receive events
dispatched on vm://myComponent.
Transformers
There are no specific transformers for the VM transport.
WSDL Endpoints
The WSDL endpoint works in much the same way as the other SOAP endpoints such as Axis, Glue or
XFire. You must provide the full URL to the WSDL of the service to invoke and you must also supply a
'method' parameter which tells Mule which operation to invoke on the service -
wsdl:http://www.webservicex.net/stockquote.asmx?WSDL&method=GetQuote
The WSDL URL is pre-pended with wsdl:. Behand the scenes Mule will check you class path to see if there
is a WSDL provider that it can use to create a client proxy from the WSDL. Mule supports the Axis and
XFire methods. If you want to use a specific one you can specify which on the URL i.e.
wsdl-xfire:http://www.webservicex.net/stockquote.asmx?WSDL&method=GetQuote
or
wsdl-axis:http://www.webservicex.net/stockquote.asmx?WSDL&method=GetQuote
The javadoc for the Xfire WSDL dispatcher can be found here.
Sometimes the Axis WSDL generation will not work (Incorrect namespaces are used) So
you might want to experiment with each one. We have had no problems with the XFire
WSDL generation so far
Transformers
There are no specific transformers to set on WSDL endpoints.
In these cases, you can specify the "wsdlUrl" property of the XFire endpoint like this:
<endpoint
address="wsdl-xfire:http://localhost:8080/book/services/BookService?method=getBooks"
connector="xfiretest">
<properties>
<property name="wsdlUrl" value="file:///c:/BookService.xml"/>
</properties>
</endpoint>
In this case, the wsdl-xfire endpoint works as it normally does, except that it reads the WSDL from the
local drive.
<!-- This tests a simple XFire service using the XFire book example -->
<mule-configuration id="Sample" version="1.0">
<mule-environment-properties synchronous="true"/>
<!-- Need this to add the proper SOAP headers to the outgoing message -->
<connector name="xfiretest" className="org.mule.providers.soap.xfire.wsdl.XFireWsdlConnector">
<properties>
<property name="clientTransport" value="org.codehaus.xfire.transport.http.SoapHttpTransport"/>
<list name="clientOutHandlers">
<entry value="org.codehaus.xfire.demo.handlers.OutHeaderHandler"/>
</list>
</properties>
</connector>
<transformers>
<transformer name="DomDocumentToXml" className="org.mule.transformers.xml.DomDocumentToXml"/>
</transformers>
<model name="sample">
<mule-descriptor name="inputService"
implementation="org.mule.components.simple.PassThroughComponent">
<inbound-router>
<endpoint address="stream://System.in?promptMessage=Enter something to invoke the service:"/>
</inbound-router>
<outbound-router>
<router className="org.mule.routing.outbound.ChainingRouter">
<endpoint address="wsdl-xfire:http://127.0.0.1:8080/xfiretest/services/BookService?method=getBooks"
connector="xfiretest"/>
<endpoint address="vm://process"/>
</router>
</outbound-router>
</mule-descriptor>
<mule-descriptor name="outputService"
implementation="org.mule.components.simple.PassThroughComponent">
<inbound-router>
<endpoint address="vm://process"/>
</inbound-router>
<outbound-router>
<router className="org.mule.routing.outbound.OutboundPassThroughRouter">
<endpoint address="stream://System.out?transformers=DomDocumentToXml"/>
</router>
</mule-descriptor>
</model>
</mule-configuration>
When the XFire 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.
There are several ways to do this, but the easiest is a new transformer - StringToObjectArrayTransformer
- that translates a delimited String into an Object array. In the example below, all you have to do is type
in a String in the format of <fromCurrency>,<toCurrency>.
<mule-environment-properties synchronous="true"/>
<transformers>
<transformer name="StringToObjectArray"
className="org.mule.transformers.simple.StringToObjectArray">
<properties>
<property name="delimiter" value=","/>
</properties>
</transformer>
</transformers>
<model name="sample">
<mule-descriptor name="inputService"
implementation="org.mule.components.simple.PassThroughComponent">
<inbound-router>
<endpoint address="stream://System.in?promptMessage=Enter from and to currency symbols, separated
by a comma:"
transformers="StringToObjectArray"/>
</inbound-router>
<outbound-router>
<router className="org.mule.routing.outbound.ChainingRouter">
<endpoint address="wsdl-xfire:http://www.webservicex.net/CurrencyConvertor.asmx?
WSDL&method=ConversionRate"/>
<endpoint address="stream://System.out"/>
</router>
</outbound-router>
</mule-descriptor>
</model>
</mule-configuration>
The Xmpp provider enables the Xmpp (jabber) instant messaging protocol using the Smack API.
The javadoc for this transport provider can be found here and the Source Xref can be found here.
Endpoints
An Xmpp endpoint specifies user credentials and a host to connect to.
xmpp://username:password@jabber.org:5222/
It is important to ensure that there is a "/" at the end. To send and receive instant messages with a
specific user, just put their username and hostname after the "/". For example:
xmpp://muletest:test@jabber.org:5222/muletest2@jabber.org
For sending messages, the recipient can also be specified at message level using the following notation:
xmpp://muletest:test@jabber.org:5222/?to=muletest2@jabber.org
Note
Filters
TODO
Transformers
There are two transformers provided with the Xmpp transport...
Transformer Description
org.mule.providers.xmpp.transformers.XmppPacketToString
Converts an Xmpp Packet to a String, returning a
java.lang.String object.
org.mule.providers.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.
• Getting started - Introduction to exposing Mule services over Axis and invoking Soap services.
• Axis Transport - Basic configuration of the Axis Connector.
• Configuring Axis - Controlling WSDL generation, named parameters, Advanced Service
configuration, etc.
• 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.
XFire Web Services - Configuring Mule and XFire STaX-based Web services framework.
Mule Client - The Universal Mule Client can be used as a soap client.
Examples
MULEINTRO:Echo Example - A simple example of exposing a Mule service as a web service using Axis.
Spring Events - An example of how to Have you Spring Beans use Mule transports without configuring the
Mule Server. The example demonstates using JMS, Axis web services and Email.
• Getting started - Introduction to exposing Mule services over Axis and invoking Soap services.
• Axis Transport - Basic configuration of the Axis Connector.
• Configuring Axis - Controlling WSDL generation, named parameters, Advanced Service
configuration, etc.
• 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.
For each example we provide a client call and a server example. The Client example shows 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. The Server example demonstrates how to
expose a service in Mule with any additional steps that may be necessary.
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 obviously 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.
Sometimes you might not want to have Namespaces and parameter names hard-coded, but would
prefer having this information in your Mule config file. Create an endpoint configuration in the MuleXml
configuration and reference it from your Mule Client. the Config file will look like -
This endpoint configuration can be used by the MuleClient or on a component outbound router.
Document Literal
Mule hosted Web services using Axis cannot be invoked using Doc/Lit, Doc/Lit/Wrapped
should be used 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 MuleClient. However, this will not work without 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 sometimes may 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 (see Axis Operations) is the same as the operation/
method name you want to invoke.
RPC Encoded
Client Example
Because Axis uses RPC/Encoded by default there is no need to pass any additional config information.
Client Example
Quick Links
• Soap over Jms
• Soap over Vm
• Binding to a Servlet container
• Using other Mule transports
Mule transports are used to deliver soap requests between Axis clients and Axis services hosted by Mule.
This means you can easily use jms, vm, smtp even xmpp (jabber) to send soap requests. The following
describes how to configure each one.
We will create a descriptor that listens to a queue called echoComponent. This will be the queue on which
the soap request will be sent and the method is the operation to invoke.
To expose a Mule service as a soap service over jms you add an inbound endpoint to the component -
<mule-descriptor name="echoComponent"
implementation="org.mule.components.simple.EchoComponent">
<inbound-router>
<endpoint address="axis:jms://echoComponent"/>
</inbound-router>
</mule-descriptor>
Now all you need to do is configure the service endpoint. Here is an example of a client request endpoint
over jms -
axis:jms://echoComponent?method=echo¶m=hello
When you need to dispatch on a queue having a different name than that of the serviceComponent then
the service endpoint will have to be configured in a slightly different way in order to enable us to specify a
SoapAction property for Axis to use since Axis will look for a service having the same name as that of our
descriptor. For example, if we have the following descriptor configured:
<mule-descriptor name="echoComponent"
implementation="org.mule.components.simple.EchoComponent">
<inbound-router>
<endpoint address="axis:jms://soap.echo.queue"/>
</inbound-router>
</mule-descriptor>
Note that the queue name and the descriptor name are no longer the same. However, Axis will still
register the service with the name echoComponent so using the following service endpoint will not work:
axis:jms://soap.echo.queue?method=echo¶m=hello
The above can also be achieved through configuration by setting the SOAPAction as a property on the
dispatching endpoint.
You can configure the Jms soap endping the same way you configure a normal Jms endpoint so that all
QoS and transaction options are supported. See the Jms Provider documentation for a full description.
Soap over VM
Soap over Mule's Vm transport is also supported. This can be usful for testing or prototyping. The
endpoints are configured in the exact same way as Jms soap endpoints. For a client to invoke a service
using VM -
axis:vm://echoComponent?method=echo¶m=hello
<mule-descriptor name="echoComponent"
implementation="org.mule.components.simple.EchoComponent">
<inbound-router>
<endpoint address="axis:vm://echoComponent"/>
</inbound-router>
</mule-descriptor>
<servlet>
<servlet-name>muleServlet</servlet-name>
<servlet-class>org.mule.providers.http.servlet.MuleReceiverServlet</servlet-class>
<load-on-startup/>
</servlet>
<servlet-mapping>
<servlet-name>muleServlet</servlet-name>
<url-pattern>/mule/services/*</url-pattern>
</servlet-mapping>
<mule-descriptor name="TestService"
implementation="org.mule.providers.soap.TestServiceComponent">
<inbound-router>
<endpoint address="axis:servlet://TestService"/>
</inbound-router>
</mule-descriptor>
Note that there is not host or port information on the endpoint, Just the component name. The host, port
and path is dictated by the servlet container and the url-pattern of the MuleReceiverServlet. If The servlet
container was listening on port 8080 the URL to invoke the service would be -
http://localhost:8080/mule/services/TestService
//Client
axis:xmpp://mule1:mule@jabber.org.au/axis?method=echo¶m=hello
//Server
axis:xmpp://mule1:mule@jabber.org.au/axis
Axis Connector
Allows Mule managed components to be published as Axis services and allows components to invoke web
services using Axis client calls.
AxisConnector Properties
MuleDescriptor Properties
There are a number of properties that can be set on a Mule compoent configuration that can be used to
configure it as an Axis service.
Programmatic Configuration
If you want to programmatically configure your Axis service you can implement the
org.mule.providers.soap.axis.AxisInitialisable interface. This will pass the SOAPService object to your
component where it can be manipulated.
Axis integrates with Mule meaning you can expose Mule components as Axis services and invoke
Axis Services from mule. To expose a Mule component as an Axis service all you have to do is set the
components receive endpoint to An Axis URL. Please note that web services expect methods to be
exposed through interfaces implemented by their respective components. Otherwise, you will receive
configuration errors during Mule start-up.
<mule-descriptor name="echoService"
inboundEndpoint="axis:http://localhost:81/services"
implementation="org.mule.components.simple.EchoComponent">
</mule-descriptor>
When Mule starts, the service will be available on http://localhost:81/services/echoService. The Echo
component class implements the EchoService interface that has a single method called echo that accepts
a single parameter string.
To invoke Echo Service using the Mule Client, use the following -
TestEchoService.java
To invoke the Echo Service from a component you need to add an outbound endpoint to your component
descriptor. The example shown below is a component that receives an event on vm://test.component,
does some work on the event and then invokes or echo service.
org.foo.TestComponent
//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, just return an array of parameters in
your component.
When an event is published vm://test.component the onCall method will be called with the current event.
After the onCall method executes, Mule will invoke the outbound endpoint for TestComponent with what
is returned from the onCall method call.
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 Test Component) 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 -
When testing it can be cumbersome to start a separate Mule server to test a service, so
you can use the QuickConfigurationBuilder to start a server and register your service in
your test code i.e.
You will need to have the Axis jar and associated jars on your classpath, these ship with the Mule
distribution.
Exposing Services
All service operations are exposed through interfaces implemented by your component.
This means your component must implement at least one service interface. This is
generally good practice anyway.
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 remember to add the following handlers in the global
configuration -
<requestFlow>
<handler
type="java:org.mule.providers.soap.axis.extensions.MuleSoapHeadersHandler"/>
</requestFlow>
<responseFlow>
<handler
type="java:org.mule.providers.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 customising Axis behaviour, Naming parameters, Message style options and
more see Configuring Axis.
Quick Links
• Controlling Exposed Methods
• Document Styles
• Map as Parameters
• Service Properties
• Customising the Soap Action
• Named Parameters
• WSDL Generation
• Object Type Mappings
• Customising the Mule Axis Service
• Service Initialisation Callbacks
Often a service will not want to expose all it's methods to the outside world. One way to restrict the
exposure is to set the serviceInterfaces property. This is a list of interface names that the service
implements and that should be exposed.
<mule-descriptor name="testService"
implementation="org.mule.providers.soap.TestServiceComponent"
inboundEndpoint="axis:http://localhost:38009/mule/services">
<properties>
<list name="serviceInterfaces">
<entry value="org.mule.providers.soap.EchoService"/>
<entry value="org.mule.providers.soap.DateService"/>
</list>
</properties>
</mule-descriptor>
You can also specify one or more methods to expose in a comma separated list, using the axisOptions
property (discussed in more detail later).
<mule-descriptor name="testService"
implementation="org.mule.providers.soap.TestServiceComponent"
inboundEndpoint="axis:http://localhost:38009/mule/services">
<properties>
<map name="axisOptions">
<property name="allowedMethods" value="echo,getDate"/>
</map>
</properties>
</mule-descriptor>
Map as parameter
The AxisConnector treats a Map as container for named parameters, which eventually will be unpacked...
This will result into a problem if your exposed service needs to take a Map as a parameter, because the
actual Map will never reach the service intact.
There is one way though to configure the connector not to unpack Maps, so that these can be passed as
parameters. The configuration of the connector looks as follows:
The style and Uses properties can be set for a service by setting the properties on the mule-descriptor.
For example to make your service Document/Literal/Wrapped -
<mule-descriptor name="testService"
implementation="org.mule.providers.soap.TestServiceComponent"
inboundEndpoint="axis:http://localhost:38009/mule/services">
<properties>
<property name="style" value="Wrapped"/>
<property name="use" value="Literal"/>
</properties>
</mule-descriptor>
The style property can be on of: 'RPC' (default), 'Document', 'Message', or 'Wrapped'. And the use
property can either be 'Encoded' (default) or 'Literal'.
For more information about service styles and Mule see Axis SOAP Styles, also take a look at the Axis
website.
Service properties are attributes that are set on the Axis service object itself. The two useful properties to
set here are scope and allowedMethods, through there may be others depending on your Axis server
configuration.
<mule-descriptor name="testService"
implementation="org.mule.providers.soap.TestServiceComponent"
inboundEndpoint="axis:http://localhost:38009/mule/services">
<properties>
<map name="axisOptions">
<property name="allowedMethods" value="*"/>
<property name="scope" value="Application"/>
</map>
</properties>
</mule-descriptor>
If these properties are not set the default Axis values are used.
By default Mule uses the axis endpoint as the soapAction when make WS calls. This is fine for Axis
clients but may not work with .Net clients. In fact the soapAction can be different across different soap
implementations so developers need a way to customise how the soap Action is formatted.
Mule users can set the soapAction on the outbound endpoint making the soap request i.e.
If using the Mule Client you can set the soapAction 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.
Some WebService clients require that all method parameters of a call should be named. You can do this in
Mule in two ways.
1. In the Mule Xml the soap method parameters for a servie can be set on the endpoint using the
soapMethods property map.
Within the map element you can define 1 or more property elements where the name attribute is the
method name and the value is a string representation of the named parameters of the method and the
return type. The parameter string is in the format of -
[paramName1];[type];[mode],[paramName2];[type]; ...,[return;type]
The parameterName is the name of the parameter. The type is an XSD string such as int, long, map, etc.
and the parameter mode can be in, out or inout. The return type is also an XSD type string. You can also
set the returnClass instead of return and provider a fuly qualified classname instead of an XSD type.
If you have a lot of named parameters you can pass in a list of parameters i.e.
<endpoint address="axis:http://localhost:38011/mule/concatService?method=concat"
synchronous="true">
Controlling Namespaces
Namespaces for elements can be controled at the method and parameter level or declare a namespace on
the method with a prefix of 'foo' with a uri of 'http://mycompany.com/foo' use the following -
qname{[prefix]:[localname]:[namespace]}
You can supply either just a localname, localname and namespace or a prefix, localname and
namesspace.
The namespace for the method will be applied to the parameters also, but you can set the namespace for
each parameter explicitly also using an identical syntax i.e. -
To set method parameter name using the MuleClient you need to 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
MuleClient.
Most commonly, you will want to set the namespace for your service. this can be done by setting the
'serviceNamespace' property on your service i.e.
<mule-descriptor name="testService"
implementation="org.mule.providers.soap.TestServiceComponent">
<inbound-router>
<endpoint address="axis:[http://localhost:38009/mule/services]"/>
</inbound-router>
<properties>
<property name="serviceNamespace" value="http://foo.namespace"/>
</properties>
</mule-descriptor>
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 autogenerated WSDL document.
You can control the values used in Axis wsdl generation by setting wsdl specific Axis options. Not you do
not need to changes these values, but if you want to you can. 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 -
<mule-descriptor name="testService"
implementation="org.mule.providers.soap.TestServiceComponent">
<inbound-router>
<endpoint address="axis:http://localhost:38009/mule/services"/>
</inbound-router>
<properties>
<map name="axisOptions">
<property name="wsdlServiceElement" value="MyService"/>
</map>
</properties>
</mule-descriptor>
Note that as of Axis 1.2-RC3 it is no longer necessary to configure Type Mappings as bean serialisation is
handled automatically by Axis. If you are using an older version of Axis Type Mappings may need to be
configured.
Mule enables default type mappings for object serialisation between soap calls. This means, for the most
part serialisation/deserialisation of call parameters and return objects is 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 of these types. However, it does not work where you have
a bean that has as 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 in order
to manage your service. For example, say you have a PersonService service that will get a Person object
when passed the persons name. The Person object contains an Address object. The configuration will look
like -
<mule-descriptor name="personService"
implementation="org.foo.PersonServiceComponent"
inboundEndpoint="axis:http://localhost:38009/mule/services">
<properties>
<list name="beanTypes">
<entry value="org.foo.Address"/>
</list>
</properties>
</mule-descriptor>
It is important to note that only custom types should be listed. If any standard types are
present, like java.util.ArrayList, Axis may produce serialization errors.
For convenience, the BeanTypes property can be set on an Axis connector configuration so that all
services that use the connector will have the types registered in the TypeRegistry for the service.
<connector name="axisConnector"
className="org.mule.providers.soap.axis.AxisConnector">
<properties>
<list name="beanTypes">
<entry value="org.foo.Address"/>
</list>
</properties>
</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.
The Axis Service component is a Mule managed component that handles axis service requests. This
component is equivilent to the Axis Servlet used when running Axis in a servlet container. Being a Mule
managed component you can configure how threading, pooling and queuing behaves for the component.
By default, when the Axis Service component is created it will be assigned the default threading, pooling
and queuing as defined in the MuleConfiguration object. If your Mule instance is receiving a high number
of requests you may want to increase the compoent pool size. To customise the Axis Service component
you need to configure a mule-descriptor with a name of _axisServiceComponent and set the relevant
properties on it. For example -
<mule-descriptor
name="_axisServiceComponent"
implementation="org.mule.providers.soap.axis.AxisServiceComponent">
<threading-profile maxBufferSize="100" threadTTL="600000"
maxThreadsActive="30" maxThreadsIdle="20" />
<pooling-profile exhaustedAction="GROW" maxActive="20"
If you need further control over the Axis service created by Mule it is possible for your component to
implement AxisInitialisable.
AxisInitialisable.java
This gets called when the service is initialised and allows you to customise the service configuration form
your Mule component.
WebMethods Glue integrates with Mule meaning you can expose Mule components as Glue Web Services
and invoke Glue Web Services from Mule. This document provides a beginner overview of how to
configureGlue endpoints in Mule. Also take a look at how to configure the Glue connector.
To expose a Mule component as an Glue service all you have to do is set the components receive
endpoint to An Glue URL, i.e.
<mule-descriptor name="echoService"
inboundEndpoint="glue:http://localhost:81/services"
implementation="org.mule.components.simple.EchoComponent">
</mule-descriptor>
When Mule starts, the service will be available on http://localhost:81/services/echoService. The Echo
component class has a single method called echo that accepts a single parameter string that it will echo
back to the client.
To invoke the service you can use the Mule Client i.e.
TestEchoService.java
When the TestEchoService is run you will see the following output -
http://localhost:81/services/echoService.wsdl
Downloading Glue
Unfortunately due to Webmethods license restrictions, Mule cannot ship with Glue.
Webmethods have either made it extremely difficult to locate Glue on their website or they
have removed it. If you're using this connector it's assumed that you have the glue jar
kicking around somewhere. You only need to include the glue.jar on the Mule classpath.
Mule works with Glue Standard Edition and above.
If you need control over the Glue service created by Mule it is possible for your component to implement
org.mule.providers.soap.glue.GlueInitialisable.
GlueInitialisable.java
Unlike the Axis Support the Glue provider uses Glue's internal Http server rather that the Mule Http
Transport.
Glue Connector
Allows Mule managed components to be published as Glue services and allows components to invoke web
services using Glue client calls.
GlueConnector Properties
There are no specific properties that can be set on the Glue connector
MuleDescriptor Properties
There are a couple of properties that can be set on a Mule component configuration that can be used to
configure it as an Glue service.
Programmatic Configuration
If you want to programmatically configure your Glueservice you can implement the
org.mule.providers.soap.glue.GlueInitialisable interface. This will pass the IService object and
ServiceContext objects to your component where they can be manipulated.
REST Service Wrapper - Proxy REST service calls to invoke them as local components.
MULEINTRO:Stock Quote Example - An Example of invoking a ASPX webservice using the REST service
Wrapper.
XFireConnector Properties
clientInHandlers A List of No
org.codehaus.xfire.handler.Handler
objects for processing
of incoming messages
clientOutHandlers A List of No
org.codehaus.xfire.handler.Handler
objects for processing
of outgoing messages
To expose a Mule component as an XFire service all you have to do is to set the component's receive
endpoint to a XFire URL, i.e.
When Mule starts, the service will be available on http://localhost:81/services/echoService. The Echo
component class has a single method called echo that accepts a single parameter string that it will echo
back to the client.
To invoke the service you can use the Mule Client i.e.
TestEchoService.java
When the TestEchoService is run you will see the following output -
http://localhost:81/services/echoService?wsdl
Although the property serviceInterfaces is a list, which of course might contain more than one element,
only the first interface will be considered.
If you would like to expose methods from two or more interfaces, the work around is very simple.
You need to create an abstract class which implements the interfaces you want to expose. In the
serviceInterfaces list, then you just need to add this new abstract class.
Messaging Styles
The following describes how to configure diffent messaging styles for XFire services in Mule. To configure
the style of service to use you set the style and use properties on the service object i.e.
Doc Lit
TODO
RPC Wrapped
TODO
Message
TODO
RPC Encoded
RPC encoded is not supported by XFire. For this request style you need to use either the Mule Axis or
Glue transport.
SOAP over VM
Exposing your XFire service over the VM Transport is not very useful in production but is useful for
development and testing. To expose the service using VM you specify the xfire and vm protocol and the
component name, as shown below -
TODO
TODO
TODO
TODO
<outbound-router>
<router className="org.mule.routing.outbound.OutboundPassThroughRouter">
<endpoint address="xfire:http://localhost:9999/services/PeopleServiceWS?
method=addPersonWithConfirmation">
<properties>
<map name="complexTypes">
<property name="org.mule.tck.testmodels.services.Person"
value="Person:http://services.testmodels.tck.mule.org"/>
</map>
</properties>
</endpoint>
</router>
</outbound-router>
The map "complexTypes" is a map that can contain one or more complex types. The actual complex types
are defined as properties of the complexTypes map. The above example shows how we can send the
org.mule.tck.testmodels.services.Person bean over xfire. The class name is specified as the property's
name, while the value should contain the complex type name as defined in the wsdl (in this case Person)
and the namespace (which is also specified in the wsdl), separated by a ':'. The format should be as
follows:
Transport providers are used to provide connectivity to an underlying data source or message source in a
consistent way.
Mule transport providers can be one of three types -
1. inbound-only: Components can only subscribe to events, they cannot dispatch events.
2. outbound-only: Components can only dispatch events, but cannot subscribe to events.
3. inbound-outbound: Components can subscribe and dispatch events
In a Nutshell
A transport provider consists of a set of interface implementations that expose the features for the
underlying transport. Cannot resolve external resource into attachment.
|| Interface || Role ||
The connector is used by Mule to register listeners and create message dispatchers for the transport.
Configuration parameters that should be shared by all Message Receivers and Dispatchers are stored
on the connector. Usually, only one connector instance is needed for multiple inbound and outbound
endpoints as multiple Message Receivers and Dispatchers can be associated with a connector. However,
where the underlying transport API has the notion of a Connection such as the JMS or JDBC API there
should be a one to one mapping between Mule Connector and the underlying connection.
org.mule.umo.provider.UMOMessageReceiver
The Message Receiver is used to receive incoming data from the underlying transport and package it up
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 a Http server
implementation that accepts http requests. An implementation of this class is needed if the transport
supports inbound communication.
org.mule.umo.provider.UMOMessageDispatcher
The Message Dispatcher is used to send events, which is akin to making client calls with the underlying
technology. For example the Axis Message Dispatcher will make a web service call. An implementation of
this class is needed if the transport supports outbound communication.
org.mule.umo.provider.UMOMessageDispatcherFactory
This is a factory class used to create UMOMessageDispatcher instances. An implementation of this class is
needed if the transport supports outbound communication.
org.mule.umo.provider.UMOMessageAdapter
The message adapter is used to provide a consistent way of reading messages in Mule. The massage
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
Where do I start?
With the maven Transport Archetype of course!
Connectors
The org.mule.providers.AbstractConnector implements all the default functionality required for Mule
connectors, such as threading configuration, and receiver/dispatcher management. Details about the
standard connector properties can be found here.
Further properties can be set on the connector depending on the implementation. Often a connector will
have a set of properties that can be overridden on a per endpoint basis, meaning the properties set on
the connector serve as defaults when an endpoint configuration doesn't provide overrides.
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 2 types of Message Receiver: Polling and Listener-based.
1. A Polling Receiver polls a resource such as the file system, database and streams.
2. The Listener-based type is a receiver that register itself as a listener to a transport. Examples would
be JMS (javax.message.MessageListener); Pop3 (javax.mail.MessageCountListener). These base
types may be transacted.
The AbstractMessageReceiver provides methods for routing events. Developers extending this class
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
PollingMessageReceiver
Its quite common for some transport providers to poll a resource periodically waiting for new data to
arrive. The PollingMessageRecievers implements the code necessary to setup and destroy a listening
thread and provides single method poll() that is invoked repeatedly at a given frequency.
Methods to Implement
TransactedMessageReceiver
Connection Strategy
Connection Strategy classes can be used to customise the way a connection is made to the transport
when the connection fails or the Mule connector is started. Connection strategies are responsible for
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 it is recommended that Developers call scheduleWork(...)
on the WorkManager rather than startWork(...).
Message Dispatchers
Messages Receivers are equivalent to a server for the transport in that it will serve up client requests.
Whereas, Message Dispatchers are the client implementation of the transport. They are responsible for
making client requests over the transport, such as writing to a socket or invoking a web service. The
AbstractMessageDispatcher provides a good base implementation leaving 3 methods for the custom
MessageDispatcher to implement.
Methods to Implement
Custom transports do not need to worry about dispatcher threading. Unless threading is turned off,
the Dispatcher methods listed above will be executed in their own thread. This is managed by the
AbstractMessageDispatcher.
When a request is made for a dispatcher, it is looked up from a dispatcher cache on the
AbstractConnector. The cache is keyed by the endpoint being dispatched to. If a Dispatcher is not found
one is created using the MessageDispatcherFactory and then stored in the cache for later. If developers
want a new Dispatcher to be created for each request they can set the disposeDispatcherOnCompletion
property on the AbstractConnector to true. This will essentially turn off dispatcher caching.
Message Adapters
MessageAdapters are usually simple objects that provide a uniform way of accessing an event payload
and associated metadata from a format used by the underlying transport. Almost all messaging protocols
have the notion of message payload and header properties, which means that a MessageAdapter just
needs to allow access to the header properties using standard Map notation i.e.
//Jms message id
String id = (String)message.getProperty("JMSMssageID");
or
//Http content length
int contentLength = message.getIntProperty("Content-Length");
Methods to Implement
Service Descriptors
A service descriptor is a file that contains a number of properties that describes how the internals of a
transport provider is configured i.e. which Dispatcher factory to use or which endpoint builder to use.
The service descriptor must be a file with the same name as the protocol of the transport stored in the
META-INF directory, where protocol might be Jms, Http or File.
META-INF/services/org/mule/providers/<protocol>.properties
The following describes each of the properties that can be set in a Transport service descriptor.
Coding Standards
Package Structure
All mule providers have a similar package structure. They follow the convention of -
org.mule.providers.<protocol>
Internationalisation
Any exceptions messages used in your transport provider implementation should be stored in a resource
bundle so that they can be internationalised . The message bundle is a standard java properties file and
must be located at -
META-INF/services/org/mule/i18n/<protocol>-messages.properties
A service descriptor is a file that contains a number of properties that describes how the internals of a
transport provider is configured i.e. which Dispatcher factory to use or which endpoint builder to use.
The service descriptor must be a file with the same name as the protocol of the transport stored in the
META-INF directory, where protocol might be Jms, Http or File.
META-INF/services/org/mule/providers/<protocol>.properties
The following describes each of the properties that can be set in a Transport service descriptor.
XSLT Transformer
The XSLT Transformer gives users the ability to perform XSLT transformations on XML messages in Mule.
This works in a very similar way to the XQuery Transformer on MuleForge.
Configuration
To use the XSLT transformer you need to add it to your Mule XML configuration
<transformers>
<transformer name="xslt" className="org.mule.transformers.xml.XsltTransformer"
returnClass="java.lang.String">
<properties>
<map name="transformParameters">
<property name="title" value="#getProperty(message,'ListTitle')"/>
<property name="rating" value="#getProperty(message,'ListRating')"/>
</map>
<text-property name="xslt">
<![CDATA[
<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>
]]>
</text-property>
</properties>
</transformer>
</transformers>
<map name="transformParameters">
<property name="title" value="#getProperty(message,'ListTitle')"/>
<property name="rating" value="#getProperty(message,'ListRating')"/>
</map>
Configuration options
uriResolver The URI resolver to use when LocalUriResolver (reads from the
validating the XSL output (since classpath or file)
1.4.4-SNAPSHOT)
Example
Now your configured XSLT transformer can be referenced by an endpoint. In the following example, you
can drop and XML file into a directory on the local machine (see the inbound file endpoint) and the result
will be written to System.out.
<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> -->
<transformers>
<transformer name="xslt" className="org.mule.transformers.xml.XsltTransformer"
returnClass="java.lang.String">
<properties>
<map name="transformParameters">
<property name="title" value="#getProperty(message,'ListTitle')"/>
<property name="rating" value="#getProperty(message,'ListRating')"/>
</map>
<text-property name="xslt">
<![CDATA[
<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>
]]>
</text-property>
</properties>
</transformer>
</transformers>
<model name="main">
<mule-descriptor name="Echo" implementation="org.mule.components.simple.EchoComponent">
<inbound-router>
<!--<endpoint address="file:///var/data/in" transformers="xquery"/>-->
<!-- this endpoint is used by the functional test -->
<endpoint address="vm://test.in" transformers="xslt" synchronous="true"/>
</inbound-router>
<outbound-router>
<router className="org.mule.routing.outbound.OutboundPassThroughRouter">
<endpoint address="stream://System.out"/>
</router>
</outbound-router>
</mule-descriptor>
</model>
</mule-configuration>
Testing it
//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));
Embedded Mule
Nothing special about it, the configuration is completely delegated to the owning container. Launch
YourKit Profiler, Tools -> Integrate with J2EE server... and follow simple instructions. Typically, a
server's launch script is modified accordingly to support profiling and one has to use this modified start
script instead of the original
set PATH=c:\java\yourkit-6_0_15\bin\win32;%PATH%
Next, follow the steps applicable to your Java runtime version below.
wrapper.java.additional.4=-Xrunyjpagent:sessionname=Mule
wrapper.java.additional.4=-agentlib:yjpagent=sessionname=Mule
This glossary tries to give a brief explanation of terms used within Mule. In addition to Mule specific terms
the glossary also includes various descriptions revolving around integration and messaging concepts, e.g.
SEDA or EIP. Please note that this glossary is constant work in progress and definitions may evolve over
time. Whenever you feel there's a need for clarification of any Mule related term, feel free to add it to this
list.
ABCDEFGHIJKLMNOPQRSTUVWYXZ
Catch-All-Strategy
Chaining Router
Channel
...
Communication Channel
...
Configuration Builder
Class that knows how to parse a given configuration file - the default is the
org.mule.config.MuleXmlConfigurationBuilder class that knows how to parse Mule's XML
configuration.
More information on the different types of configuration builders is available on the Configuration
Overview page
Connector
Connector Dispatcher
...
...
Endpoints are used to connect to components in the server and external systems or to each
other locally or over the network. An Endpoint is a specific channel through which two parties
can communicate. A provider can be used to send or receive events from disparate systems,
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 response sent back over Http.
EIP
Common name referring to Enterprise Integration Patterns: Designing, Building, and Deploying
Messaging Solutions, Gregor Hohpe & Bobby Woolf; Addison-Wesley 2003
...
Filter
...
Global Endpoint
Inbound Router
...
Interceptor
Interceptors are used to intercept message flow into a service component. Mule interceptors
are useful for attaching common behavior to multiple UMOs. Typical interceptors are loggers,
profilers, or permissions checkers.
Local Endpoint
These are endpoints that are configured or set on the objects that have Endpoints, but are not
registered with the MuleManager.
Message Context
...
Message Filter
...
Message Payload
Message Router
See Router
Mule is an ESB (Enterprise Service Bus) and integration platform. It can be thought of as a
lightweight messaging framework and highly distributable object broker that can seamlessly
handle interactions with other applications using disparate technologies such as JMS, Http,
Email, and Xml-RPC.
The Mule framework provides a highly scalable environment in which you can deploy your
business components. Mule manages all the interactions between components transparently
whether they exist in the same VM or over the Internet, and regardless of the underlying
transport used.
Mule was designed around the ESB (Enterprise Service Bus) enterprise integration pattern,
which stipulates that different components or applications communicate through a common
messaging bus, usually implemented using JMS or some other messaging server.
Mule Configuration
...
Mule Event
An event message can be any kind of message in the messaging system. Event notification is used to
coordinate actions among applications. A Mule Event actually references a Mule Message. The difference
between a Mule Event and Mule Message (the payload really) is a matter of timing and content. An
event's timing is very important whereas e.g. guaranteed delivery is important to content.
...
MuleForge
...
MuleHQ
...
Mule Instance
...
...
Mule Message
A message carrying a Message Payload and a set of properties that are associated with the
processing of the message. The UMOMessage object represents a message in Mule. See also
Mule Event.
MuleSource
...
...
Placeholder
...
Property
...
Protocol
...
Provider
Response Router
...
Router
Routers are used to control how messages are sent and received by components in the system.
Mule supports 3 classes of routers:
Routers can be nested and configured to filter messages. For details also see routers.
SEDA
For more information see the SEDA homepage. Also, this article makes a good introduction.
Service Component
A Service Component is a POJO running under Mule, which exposes the POJO to external
entities as a service. It is also known as a Universal Message Object (UMO) within Mule.
Service Container
Service Manager
...
Transformers are used to transform message payloads to and from different types. Mule
supports chaining of transformers. This allows to have reusable and fine-grained transformers
that may be linked together to provide required functionality.
Transport
...
Transport Element
Transport Provider
UMO
Wire Tap
A router which forwards copies of messages to another endpoint. It can either forward a copy
of all messages that it receives or it can be configured to use a filter and send a sub-set of
these messages only. This router will not prevent messages from being delivered to service
components. See also Interceptor.
These are the various tools that help develop, document or test Mule applications.
• Mule IDE - A set of Eclipse plugins for configuing and testing Mule applications
• MULEUSER:Benchmark - A simple command-line benchmarking tool for Mule
• Config Visualizer - A great little tool for generating a visual diagram of your Mule configuration
• Transport Archetype - A Maven archetype that creates a set of commented template classes for a
new transport
• Transport Archetype for Mule 2.0 - A more advanced Archetype for creating a template project for a
Mule 2.0 transport.
• Project Archetype - A Maven archetype for creating a Mule project. A project can be stand alone,
and example project or module.
Note: the visualizer is bundled in Mule 1.4.2+, instructions below apply if building from the source.
The Mule Configuration Visualizer is a great tool for generating Configuration graphs from Mule Xml. Take
a look at some samples -
Loan Loan
Voip
Broker Broker
Service
ESB Sync
Config
Config Config
Error
Hello Http Echo Mule
Handler
Config Config
Config
Prerequisites
You need Java 1.4 and Maven 2.0.6 to build the code and subversion (svn) to check out the source.
Install Graphiz, a graph visualization software from http://www.graphviz.org. A binary is included for
Windows. On Unix machines install Graphviz separately and add it to the standard PATH. It should then
be used automatically. Alternatively, see "exec" option.
Building
cd trunk/mule/tools/visualizer
mvn compile
Running
The visualizer can be run as a command line application. Command line provide a few options that you
can specify:
Take note that, if you run the Mule visualizer command at any directory (instead of running it in
$MULE_HOME/bin ) you need to specify the -exec option, e.g.
set MULE_GRAPHVIZ=$MULE_HOME/lib/native/visualizer/dot.exe
visualizer -files updater-config.xml -exec $MULE_GRAPHVIZ
Otherwise, please provide the full/relative path to the $MULE_HOME directory when you specify the
configuration file location:
urls ? ? No
config ? ? No
templateprops ? ? No
showmodels ? false No
showconfig ? false No
showagents ? false No
showtransformers ? false No
Combining Files
Combining files can be really useful for getting the 'big picture' of your Mule Application as you can
combine Mule node configurations from many different machines.
Mappings are defined as key/value pairs in a .properties file where the key 'maps' to the value in the
diagram. These values use the object names as represented on the output graph so you can define
relationships between component, endpoints, routers or any other object.
An example mapping might be where a replyTo endpoint is set on a message and Mule handles the
routing from the replyTo to the next component. Using the Loan Broker as an example, the replyTo
endpoints for the Banks would be mapped as -
Bank1=LoanBrokerQuotes
Bank2=LoanBrokerQuotes
Bank3=LoanBrokerQuotes
Bank4=LoanBrokerQuotes
Bank5=LoanBrokerQuotes
When using dynamic routers such as the receipient List you may want to define the possible routes from
the router to the endpoints i.e.
LenderService.org.mule.routing.outbound.StaticRecipientList=Bank1,Bank2,Bank3,Bank4,Bank5
This says, from the StaticRecipientList router on the LenderService, map to each of the Bank endpoints.
Sometimes and inbound endpoint is not expressed in the same way as an outbound endpoint. This is the
case for Soap endpoints where the outbound endpoint has a method param, but inbound endpoint Soap
endpoint doesn't. You can logically map these two endpoints so that they appear as one on the graph, i.e.
CreditAgencyReceiver.equals=CreditAgency
Note the 'equals' extension tells the Config Graph that the two objects are equivilent.
Once you map the two endpoints you'll probably want to hide one of them...
Hiding Nodes
To hide a node you add the following entry to the mapping file
CreditAgencyReceiver.hide=true
Tips
It's a good practice to use Endpoint Identifiers in your Mule Xml to map physical endpoints to logical
names. This helps when configuring mappings for the Config Grapher and these logical names can be
used in the mappings instead of the physical names.
The Mule project wizards are based on Maven Archetypes that are code templates that can get you up
and running with a mule project complete with a set of implementation notes and 'todo' pointers.
The Mule Project archetype enables users to generate a tailored boilerplate project in seconds.
• Mule Project Archetype 2.x - Generate a Module, example or stand alone project for Mule.
Following the instructions below will create template files, including all the necessary Java boilerplate and
detailed implementation instructions in comments, for a new Mule project.
The Mule project archetype is publicly available from the central maven repo.
Configuring Maven
Edit the file settings.xml (usually in $HOME/.m2) so that Maven will allow you to execute Mule plugins.
<settings>
...
<pluginGroups>
<pluginGroup>org.mule.tools</pluginGroup>
</pluginGroups>
...
</settings>
<settings>
...
<profiles>
<profile>
<id>codehaus</id>
<repositories>
<repository>
<id>codehaus.org</id>
<name>CodeHaus Snapshots</name>
<url>http://snapshots.repository.codehaus.org</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>codehaus.org</id>
<name>CodeHaus Plugin Snapshots</name>
<url>http://snapshots.repository.codehaus.org</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
...
</settings>
> cd yourDir
Next you will execute archetype and generate the code. This will ask various questions and then generate
the files.
You need to pass in two system parameters -
Note that this plug-in can be used without user prompts. For a full list of arguments that
can be passed in. See MULE:Command Line Options.
Note you also need to use the codehaus profile. The command looks like the following (all on one line) -
Next you'll be asked a number of questions about the Mule project you are creating. These may vary
according to the options you select. An example of the output is shown below.
You should provide an accurate description of the transport with any high level details of what you can or
cannot do with it. This text will be used where a description of the project is required.
The version of Mule you want to use for your transport. By default this will default to the Archetype
version passed in on the command line.
If the transport is going to be hosted on MuleForge, then additional information will be added to your
project for linking to its issue tracker, web site, build server and deployment information.
Will This transport have a custom schema for configuring the transport in Xml?
It's recommended that all new transports targeted for Mule 2.0 should define an Xml schema that defines
how the transport is configured. If you do not use this option, users will have to use generic configuration
to use your transport.
This should be a java package path for you project i.e. org/mule/modules/foo. Note that you must use
slashes not dots.
Specifies the type of project that will be created. Typically, the project structure will remain the same for
each project type, but the POM configuration may change to inherit from a different parent POM.
Will This project need to make objects available in the Registry as soon as it's loaded?
The registry bootstrap is a properties file that specifies class names of simple objects that can be made
available in the Mule Registry as soon as the module is loaded. This is useful for registering custom
transformers or property extractors.
The custom option allows you to deviate from the existing endpoint styles and parse your own.
[default:]
********************************************************************************
[INFO] muleVersion:
********************************************************************************
[default: 2.0.0-RC1-SNAPSHOT]
********************************************************************************
[INFO] packagePath:
********************************************************************************
What is the base Java package path for this module? (i.e. org/mule/modules
or org/mule/examples):
[default: org/mule/applications]
********************************************************************************
[INFO] forgeProject:
********************************************************************************
[default: y]
********************************************************************************
[INFO] projectType:
********************************************************************************
[INFO] hasCustomSchema:
********************************************************************************
Will This project have a custom schema for configuring the module in Xml?
[default: n]
********************************************************************************
[INFO] hasBootstrap:
********************************************************************************
Will This project need to make objects available in the Registry as soon as
it's loaded?
[default: n]
********************************************************************************
-Dinteractive=false
groupId - org.mule.application.<artifactId>
DgroupId=org.mule.applicationxxx
The Mule code wizards are based on Maven Archetypes that are code templates that can get you up and
running with a mule project complete with a set of implementation notes and todo pointers.
The Mule transport archetype enables users to generate a tailored boilerplate transport project in
seconds.
Following the instructions below will create template files, including all the necessary Java boilerplate and
detailed implementation instructions in comments, for a new transport.
The transport archetype is publicly available from the central maven repo.
<settings>
...
<pluginGroups>
<pluginGroup>org.mule.tools</pluginGroup>
</pluginGroups>
...
</settings>
> cd yourDir
Create the archetype. This will ask various questions and then generate the files (the "\" in the command
below indicate that it is all on one line)
The protocol name to use for the transport (lower case) i.e. jms or http
[default: myTransport]
********************************************************************************
foo
[INFO] TransportDescription:
********************************************************************************
Does the Message Receiver need to poll the underlying resource? [y] or [n]
[default: n]
********************************************************************************
y
[INFO] Streaming:
********************************************************************************
If this transport will have a default inbound transformer, enter the name of the
transformer? (i.e. JmsMessageToObject)
[default: n]
********************************************************************************
FooMessageToObject
[INFO] Dispatcher:
********************************************************************************
If this transport will have a default outbound transformer, enter the name of the
transformer? (i.e. ObjectToJmsMessage)
[default: n]
********************************************************************************
ObjectToFooMessage
[INFO] Transactions:
********************************************************************************
User Guide
1. Using Mule
• Mule Distributions
• MULEINTRO:Embedding Mule in a Java Application
• MULEINTRO:Embedding Mule in a Webapp
3. Mule Security
4. Mule Client
5. Mule Agent
6. Administration Tools
• Mule IDE
• Benchmark
• Config Visualizer
8. MULECB:Home
Configuring Maven
Edit the file settings.xml (usually in $HOME/.m2) so that Maven will allow you to execute Mule plugins.
<settings>
...
<pluginGroups>
<pluginGroup>org.mule.tools</pluginGroup>
</pluginGroups>
...
</settings>
<settings>
...
<profiles>
<profile>
<id>codehaus</id>
<repositories>
<repository>
<id>codehaus.org</id>
<name>CodeHaus Snapshots</name>
<url>http://snapshots.repository.codehaus.org</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>codehaus.org</id>
<name>CodeHaus Plugin Snapshots</name>
<url>http://snapshots.repository.codehaus.org</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
...
</settings>
Introduction
The aim of this guide is to provide a practical approach for developing with Mule. It will describe the steps
involved in setting up Mule application and best practices.
Prerequisites
This guide assumes you have an understanding of the core concepts of Mule, ESBs, and J2EE.
If you are not yet familiar with Mule see the Getting Started Guide.
MuleMessage Construction
The MuleMessage is constructed by taking the body of the received data as the
payload and any message headers and meta information (such as Filename in the
File Transport). For example the Content-Type of a Http request can be read using –
MuleMessage.getStringProperty("Content-Type", null) or a JMS header such as JMSPriority
can be read using - MuleMessage.getIntProperty("JMSPriority")
If the underlying transport supports attachments (such as SOAP and Mail) these will be
added to the MuleMessage attachments.
Endpoint
The Endpoint is used to receive messages from a transport. An endpoint is a configuration object
that defines how data will be received and transformed by Mule. On the Endpoint you can configure
the endpoint address, transport-specific configuration information, transactions and filters. For more
information see Mule Endpoints.
Inbound Router
Inbound Routers control the inbound flow of events to a component and can re-sequence, aggregate or
filter incoming messages. For example the IdempotentReceiver will reject any inbound messages that
Inbound Router Mule provides a number of Only the routers such as the
standard Inbound Routers CorrelationAggregator need
that can be used without any customisation in order to plug in
customisation. The only reason logic to aggregate many events
customisation is necessary is into one event.
when custom logic is required to
do things like aggregate a set of
events.
Interceptor (pre)
Interceptors are used to intercept message flow into your service component. They can be used trigger
monitor/events or interrupt the flow of the message i.e. an authorisation interceptor could ensure that
the current request has the correct credentials to invoke the service.
Inbound Transformer
Inbound transformers are used to transform the inbound message from the underlying transport format
to something that the Service Component needs. Transformers can be chained together and should be
used for data-level transforms i.e. from one data-type/format to another.
Complex Transformations
Service Invocation
The service is the business logic. It can be a POJO, EJB, Remote Object or any other type of object. The
Service component can be instantiated by the mule Model or it can be created by or stored in another
container such as Spring, Hivemind, JNDI, Pico or Plexus.
Todo
Interceptor (post)
Service Invocation This is where the service object This object has to be written
actually gets invoked. It can by the developer and can be as
be a POJO, EJB, Remote object simple or complex as the service
or objects instantiated by a requires. The service object
container such as Spring or itself need not have any reliance
Hivemind. or knowledge about mule.
Service Components should be
stateless or manage any state in
a shared data repository, unless
the component is not running
[concurrently].
The Outbound Router is responsible for controlling how and where the message goes next. Mule defines
a number of standard Outbound Routers including all those listed in the excellent Enterprise Integration
Pattern Book plus some other routing patterns that we have seen. Outbound Routers allow for Content-
based, Itinerary (routing slip), Dynamic and Header-based routing or a combination of these. Mule has
standard routers for MessageSplitting, Multicasting and content-based routers.
Outbound Transformer
TODO
Endpoint (outbound)
Note that there can be zero or more endpoints that the event gets dispatched on depending on the
Outbound Router logic.
TODO
Outbound Router
Outbound Transformer
Endpoint (Outbound)
The UMOEventContext
TODO
* Note: this is the start of a discussion between support and our customers around the area of Best
Practices - work in progress. If you feel differently about this, please contribute your ideas and
suggestions.
Inevitably, Mule users and customers ask us - "How should I handle a given transformation?" or "Where
should I do this transformation in my ESB event flow?". With Mule's flexibility, you may be wondering
what the "recommended" way to handle a given problem.
Mule has a rather efficient transformation mechanism. Transformers are applied on to inbound or
outbound endpoints and the data is transformed before it gets to the component (or before it gets sent).
Transformers can be easily concatenated so it is simple to perform multiple transformations on in-flight
data. More information is available here: Transformers
If you research ESB concepts on the web, there is no general consensus as to how/where transformations
should occur in an ESB. Some maintain that since transformations are not business decisions (that
is to say, since a transformation should always be applied on inbound/outbound data), then the
transformation should be available as part of the ESB [MULE:1]. This matches the concepts of Aspect
Oriented Programming (AOP). Others conclude that it is far more efficient to encode the transformation
logic into the business
components themselves. [MULE:2] 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 goes against the
philosophy of an ESB.
While there is no industry best practise, we recommend that developers examine their transformation
logic to see if it will always be used (AOP) or if it is specific to a business process. If the former, then this
is a transformation. If the latter, then this should be part of the service component.
References:
[MULE:1] - http://msdn2.microsoft.com/en-us/library/aa480061.aspx
[MULE:2] - http://blogs.ittoolbox.com/eai/applications/archives/transformation-in-a-soa-12186
Many of Mule's features are documented here using the same terms as the popular Enterprise Integration
Patterns book. The book describes the problems Mule aims to solve and documents many of the patterns
used in the Mule framework. EIP documentation in this guide and other Mule guides will be in the form of
-
EIP - (pattern name) (book pattern no.) (the pattern url on the EIP site)
Introduction
This document aims to give an insight to the architecture of Mule. Mule's ultimate goal is to provide
a unified method of interacting with data from disparate sources without encumbering the developer
with the details about how the data is sent or received or the protocols involved. The result is an ESB
(Enterprise Service Bus) server that is highly-scalable, light-weight, fast and simple to pick up and
start using. Mule was architected with the ESB model in mind and its primary focus is to simply and
speed up the process of developing distributed service networks. However, as the name suggests, the
ESB model is usually associated with large integration projects where there are an array of disparate
enterprise applications. Mule makes Enterprise level service architectures possible for smaller projects
where resources, development cost and TTM need to be kept to a minimum.
Architecture Overview
The primary goal is to enable integration between applications using standards, open protocols and well-
defined patterns. To achieve this goal, Mule defines a set of components that can be used to perform
most of the hard work necessary to get disparate applications and services talking together.
Cannot resolve external resource into attachment.
This diagram shows a simple end-to-end topology of how Mule components fit together.
Application
The Application can be of any type, such as a web application, back office system, application server or
another Mule instance.
Channel
Can be any method of communicating data between two points. Channels are used in Mule to wire UMO
components together as well as to wire different Mule nodes together across a local network or the
internet.
Cannot resolve external resource into attachment. Mule doesn't implement or mandate any particular
channels though Mule does provide many channel options known as Transport providers.
"When an application has information to communicate, it doesn't just fling the information into the
messaging system, it adds the information to a particular Message Channel. An application receiving
information doesn't just pick it up at random from the messaging system; it retrieves the information
from a particular Message Channel."
A Message Receiver is used to read or receive data from the Application. In Mule a Receiver is just one
element of a Transport provider and Mule provides many transports such as JMS, SOAP, HTTP, TCP, XMPP,
SMTP, file, etc.
Much of the 'magic' in Mule is it's ability to communicate to disparate systems without your business
logic (UMO components) ever needing to know about system location, format of the data, the delivery
mechanism or protocols involved. Likewise when the UMO component has done its work, it need not
worry about where the data is going next or in what format the data is expected.
Cannot resolve external resource into attachment. Mule manages all delivery of data to and from
endpoints transparently.
"Message Endpoint code is custom to both the application and the messaging system's client API. The
rest of the application knows little about message formats, messaging channels, or any of the other
details of communicating with other applications via messaging. It just knows that it has a request or
piece of data to send to another application, or is expecting those from another application. It is the
messaging endpoint code that takes that command or data, makes it into a message, and sends it on
a particular messaging channel. It is the endpoint that receives a message, extracts the contents, and
gives them to the application in a meaningful way."
Inbound Router
Inbound routers are used to control how and which events are received by a component subscribing on
a channel. Inbound routers can be used to filter, split aggregate and re-sequence events before they are
received by the UMO component.
Connector
The connector understands how to send and receive data over a particular channel. A Message receiver is
coupled with a connector to register interest in data coming from a source understood by the connector.
There is more information on connectors further on in this guide.
Transformers
Transformers are used to transform message or event payloads to and from different types. Mule does
not define a standard message format (though Mule may support standard business process definition
message types in future) Transformation provided out of the box is Type transformation, such as JMS
Message to Object and standard XML transformers. Data transformation is very subjective to the
application and Mule provides a simple yet powerful transformation framework.
There is more information on transformers further on in this guide.
Endpoint
An endpoint is really a configuration wrapper that binds a connector, endpoint URI, transformers, filters
and transactional information to provide a Channel Adapter. The provider also stores transactional
information for the provider instance. See the Mule Endpointschapter that goes into more detail about
endpoints.
Cannot resolve external resource into attachment. A provider is equivalent to a Channel Adapter.
Outbound Router
Outbound routers are used to publish messages/events to different providers depending on different
aspects of events or other rules defined in configuration.
Mule Manager
Core to Mule is the MuleManager. It manages the configuration of all core services for the Model and the
components it manages. Below is an overview of the core components that comprise a Mule manager.
Cannot resolve external resource into attachment.
The following sections go in to more detail for each of these elements in Mule.
The Model
The model encapsulates and manages the runtime behavior of a Mule Server instance. It is responsible
for maintaining the UMO's instances and their configuration. The Model has 3 control mechanisms to
determine how Mule interacts with it's UMO components -
1. Checks to see if the component implements the Callable life cycle interface, in which case, the
onCall(UMOEventContext) method will be used to receive the event.
2. If the component has a transformer configured for it, the return type for the transformer will
be matched against methods on the component to see if there is a method that accepts the
transformer return type. If so this event will be used. Note if there is more than one match, an
exception will be thrown.
3. If there is a method on the component that accepts an org.mule.umo.UMOEventContext . If so this
event will be used. Note if there is more than one match, an exception will be thrown.
4. The last check determines if there are any methods on the component that accept a java.util.Event .
If so this event will be used. Note if there is more than one match, an exception will be thrown.
5. If none of the above find a match an exception will be thrown and the component registration will
fail.
Of course there are many scenarios where the DynamicEntryPointResolver is suitable. For
example, if you are migrating from another framework you may want to restrict (such
as org.mule.model.CallableEntryPointResolver that only accepts components that extend
org.mule.umo.lifecycle.Callable ) or change the way the entry point is resolved. To implement a custom
Entry Point Resolver the org.mule.model.EntryPointResolver must be implemented.
Lifecycle Adapter
Defined by the org.mule.umo.lifecycle.UMOLifecycleAdapter interface, the lifecycle adapter is responsible
for mapping the mule component lifecycle to the underlying component. The DefaultLifecycleAdapter
simply delegates life cycle events to the component where the component implements zero or more UMO
lifecycle interfaces.
Transport Providers
A transport provider is a Mule plug-in that enables Mule components to send and receive information over
a particular protocol, repository messaging or other technology. The following describes the architecture
of a transport provider. Cannot resolve external resource into attachment.
Connectors
The connector provides the implementation for connecting to the external system. The connector is
responsible for sending data to the external receiver and managing the listener on the connector to
receive data from the external system. For example, the Http connector creates a Http Connection and
sends the payload over the connection and will return a UMOEvent with the return status (if running
synchronously). Receivers for the Http connector are simply objects that get notified when something is
received on the Http server port.
Connectors are responsible for managing sessions for the underlying technology, i.e. the JmsConnector
provides a JMS Session for the Connectors' Message Receiver and one also for the Message Dispatcher to
publish or send events over Jms.
Endpoints Address
An endpoint address defines any form of destination or source of data and is always expressed as URI.
Examples of endpoints could be -
Endpoint addresses are always expressed as valid URIs with the protocol of the connector then resource
specific information.
Mule Transport providers have pluggable endpoint builders that allow developers to customize the way an
endpoint is read by Mule.
Endpoint Resolution
This section describes the process Mule uses to resolve an endpointUri. For this example we will use the
following URI 'jms://topic:myTopic?durable=true'. This a JMS URI to a durable topic.
Message Receivers
Message receivers or message listeners are responsible for receiving data from the external system.
It is the responsibility of the connector to manage the registering and unregistering of receivers. The
complexity of the message receiver will vary depending on the external system being used. For example,
the message receiver for the JMS provider simply implements the javax.jms.MessageListener and the JMS
connector registers the listener with its JMS connection. However, the Http message receiver implements
an Http server that listens on a specified port for incoming requests.
Message Adapters
Message adapters are required to read disparate data objects in the format they are received from
the external application in a common way. The UMOMessageAdapter interface specifies a small set of
methods needed to read the payload and properties of any Java object. Message Adapters are specific to
a connector; when a connector is written a Message Adapter is also needed to read or translate data from
a particular data type used by the connector into either a byte array or string.
In order for Mule to treat all transactions the same way there is a small API that transacted enabled
providers must define -
Container Contexts
The component resolver is the gateway to using an external container framework to manage the
instantiation and configuration of UMO components or their dependent objects. Mule doesn't provide
it's own component container as there is a wealth of very good IoC containers that are tried and tested.
Instead Mule provides some default Component Resolvers for popular containers -
• Spring Component Resolver - see the Spring Framework. For more information about Mule / Spring
integration see the Spring chapter of the user guide.
• Pico Component Resolver - see the PicoContainer.
To use a component from an external container as your UMO component simply configure the desired
ComponentResolver on the model and when defining the mule-descriptor in the configuration file , set the
implementation attribute to the component key (or class in the case of picocontainer) in the container.
If the configuration does not specify a Component Resolver the MuleComponentResolver is used.
This implementation expects a class name to instantiate instead of a component key to resolve the
component with. It behaves in the same way as real implementations except it does not support looking
up components from a container.
UMO Components
Central to the architecture of Mule are single autonomous components that can interact without being
bounded by the source, transport or delivery of data. These components are called UMO Components
and can be arranged to work with one another in various ways. These components can be configured
to accept data a number of different sources and can send data back to these sources. Cannot resolve
external resource into attachment.
The 'UMO Impl' specified above actually refers to an Object. This object can be anything, a JavaBean
or component from another framework. This is your client code that actually does something with the
events received. Mule does not place any restrictions on your object except that if configured by the Mule
directly, it must have a default constructor (if configured via Spring or Pico, Mule imposes no conventions
on the objects it manages).
Obviously, with this sort of flexibility, Mule needs to know a bit more about your object. It is the job of the
outer two layers shown to control how events are utilized by your Object.
Mule defines a default lifecycle for the components it manages. The components can participate in none,
any or all of these lifecycle events by implementing the required lifecycle interfaces. The lifecycle is as
follows - Cannot resolve external resource into attachment.
Components managed by Mule do not need to follow the Mule defined lifecycle. Using the
DefaultLifecycleAdapter a component can implement any of the lifecycle interfaces -
These lifecycle interfaces also apply to Connectors, Agenets and Interceptors. For example the
LifecycleInterceptor implements the Startable, Stoppable and Disposable interfaces to manage it's
lifecycle.
Transformers
Transformers are used to convert source data to an object type required by the UMO Component.
Transformers can be configured on Endpoints that receive data to ensure that the expected object
type is always received by an UMO Component. Transformers configured on an Outbound endpoint
ensure that the endpoint receives the the correct object type before dispatching the event. Multiple
transformers can be chained together to allow for finer grained transformer implementations that
are easier to reuse. To configure an Endpoint to use more than one transformer, just specify a space
separated list of transformers in the config file or programmatically chain the transformers together using
the setTransformer() method on the transformer.
For example an inbound transformer may look like -
Entrypoint Resolvers
Also (not shown on this digram) is the EntryPointResolver. This is used by the Model when the
UMOComponent is registered to find the method to call on your object when an event is received for it.
If a method is not found an exception will be thrown. The details of the EntryPoint resolver can be seen
here.
Events
Mule is an event-based architecture, that is, actions within a Mule network are triggered by either events
occurring in Mule or in external systems. Events always contain some sort of data, the payload, which
will be used and/or manipulated by one or more components and a set of properties that are associated
to the processing of the event. These properties are arbitrary and can be set at any time from when the
Event Processing
Mule can send and receive events using 3 processing models -
1. Asynchronously - Many events can be processed by the same component at a time in different
threads. When the Mule server is running asynchronously instances of a component run in different
threads all accepting incoming events, though the event will only be processed by one instance of
the component.
2. Synchronously - When a UMO Component receives an event in this mode the the whole request is
executed in a single thread
3. Request-Response - This allows for a UMO Component to make a specific request for an event and
wait for a specified time to get a response back.
You can control the synchronicity of event processing by setting the synchronous property on the
endpoint (or programmatically on the event). Synchronicity of the call can be propagated across the
network where the transports being used support a reply channel. For example, a synchronous JMS
request will establish a temporary reply queue when a request is made and will wait for a response on
that queue. The same applies to socket based transports.
The actual event flow is governed by the synchronous property, whether the endpoint is inbound or
outbound and if there is a transaction in progress. The following rules apply.
Asynchronous event processing occurs when the inbound endpoint synchronous flag is set to false.
In this scenario the message is dispatched to a queue and is consumed by a worker thread in a pool that
actually does the execution work of your UMOComponent. The outbound endpoint is also asynchronous
the resulting message will be dispatched by a dispatcher thread.
In this scenario the message is dispatched to a queue and is consumed by a worker thread in a pool
that actually does the execution work of you UMOComponent. The outbound endpoint is synchronous
so the dispatch happens in the same thread as component execution. This scenario is used by outbound
transactions so that all dispatches from the component occur in the same thread. This behavior is
handled automatically by Mule.
Synchronous Processing
An event is received and processed by your UMOComponent in the same thread and any result is
returned from your UMO component will be passed back to the receiver where if there is a response
channel, i.e Socket outputstream a result will be sent.
Transactions can only (currently) be managed over synchronous endpoints. Thus if an endpoint has been
configured for transactions it will automatically be synchronous. When dispatching and a transaction is in
progress the dispatch will also happen in the current thread.
Message Routers
Message routers are used to control how events are sent and received by components in the system.
Mule defines Inbound routers that apply to events as they are received and outbound routers that are
invoked when an event is being dispatched.
Cannot resolve external resource into attachment. Mule provides extensible routers to control how
messages are dispatched.
"a Message Router ... consumes a Message from one Message Channel and republishes it to a different
Message Channel channel depending on a set of conditions."
Inbound Routers
Inbound routers can be used to control and manipulate events received by a component. Typically, an
inbound router can be used to filter incoming event, aggregate a set of incoming events or re-sequence
events when they are received. You can chain inbound routers together, in this scenario each router is
matched before the event is dispatched to a Mule component. Inbound routers are different to outbound
routers in that the provider is already known so the purpose of the router is to control how messages are
sent via the provider. You can specify a catch-all strategy which will be invoked if any of the routers do
not accept the current event. An Inbound Router can be configured on a mule-descriptor element in the
mule-config.xml -
<inbound-router>
<catch-all-strategy
className="org.mule.tck.testmodels.mule.TestCatchAllStrategy"/>
<router className="org.mule.routing.inbound.SelectiveConsumer">
<filter expectedType="java.lang.String"
className="org.mule.routing.filters.PayloadTypeFilter"/>
</router>
<router className="org.mule.routing.inbound.Aggregator">
</router>
</inbound-router>
If there are no special processing requirements for messages received by a component there is no need
to configure an inbound router.
Outbound Routers
Outbound routers are used to control which providers are used to send events once an UMO component
has finished processing. Message Routers are configured on UMOCompnent and allow the developer to
define multiple routing constraints for any given Event. You can specify a catch-all strategy which will be
<outbound-router>
<catch-all-strategy className="org.mulerouting.ForwardingCatchAllStrategy"
provider="catchAll"/>
<router providers="TestApple-Out"
className="org.mule.routing.outbound.FilteringOutboundRouter">
<filter expectedType="java.lang.String"
className="org.mule.routing.filters.PayloadTypeFilter"/>
</router>
<router providers="waterMelonProvider"
className="org.mule.routing.outbound.FilteringOutboundRouter">
<filter className="org.mule.routing.filters.logic.AndFilter">
<left-filter pattern="the quick brown (.*)"
className="org.mule.routing.filters.RegExFilter"/>
<right-filter pattern="(.*) brown (.*)"
className="org.mule.routing.filters.RegExFilter"/>
</filter>
</router>
</outbound-router>
The catch all strategy receives the event if none of the router accept the event. Custom strategies must
implement org.mule.umo.routing.UMORoutingCatchAllStrategy which defines a method -
Note that this a void method, so that no return event can be passed back to the calling code. This is
important when running synchronously as the synchronous chain of events is broken. It is considered an
error condition when a catch-all strategy is invoked.
Routers
In the example, there are 2 routers defined, with the outbound-router element as the parent. This means
that each router will be checked in order to see if the current event can be routed.
It is not recommended to use transacted providers in router configurations. As routing of the event is
determined at run-time, there are situations where an event within a transaction is routed to a non-
transacted provider, thus orphaning the current transaction causing 'surprise' transaction timeouts. For
transacted providers it is recommended that you configure one inbound and one outbound transacted
provider for the event path.
In situations where only one outbound provider is configured for an UMO component it is not necessary to
define a Message router.
For more information about using the routers that ship with Mule, see the Message Routers chapter of the
Home.
Interceptors
Mule interceptors are useful for attaching common behavior to multiple UMOs. The Interceptor or
Command pattern is often referred to as practical AOP (Aspect Oriented Programming) as it allows
the developer to intercept processing on an object and potentially alter the processing and outcome.
Interceptors a very useful for attaching profiling, permission and security checks, etc, to a component in
Mule.
1. org.mule.interceptors.EnvelopeInterceptor - Envelope filter that will execute before and after the
event is processed. Good for Logging and profiling.
The following shows a typical interceptor stack and the event flow. Cannot resolve external resource into
attachment.
Exception Management
Exception strategies can be defined on UMOComponents, but sometimes it's sufficient to have all
components managed by the the model tp use the same exception strategy. By defining the exception
strategy on the model, it is not necessary to define individual exception strategies (by default if no
exception strategy is defined on a UMO Component the org.mule.impl.DefaultExceptionStrategy will be
used).
MULE_SERVICE_METHOD
Mule's entry point resolver class (based upon org.mule.umo.model.UMOEntryPointResolver) works
its way through its priority scheme to be able to figure out what entry point to use. This allows Mule
to dynamically use a different entry point depending on the payload of the inbound message. Other
entry point resolver classes can also be used if the DynamicEntryPointResolver is not sufficient for
your needs. The only drawback to the default mechanism is the fact that if two methods have the
same type of parameters, Mule obviously cannot decide which of the methods to use and raises a
TooManySatisfiableMethods exception. In such cases, you can easily implement the Callable interface in
your component and direct the message to the correct method.
However, this is not always a feasible solution; perhaps you do not have access to the source code of
your service component or perhaps you do not want to make your component "Mule-aware". The work
around to this would be to have a wrapper component that can direct the message for you but this just
adds another level of abstraction that you may not want either. Besides, this is all routing logic so why
should we put this into a service component?
Let us illustrate this with a simple example - If we have two components called "A" and "B" that
communicate synchronously using the VM channel called "vm://Communication". Let us assume that "A"
is the producer of string messages and "B" consumes these messages. However, "B" has more than one
method that accepts strings.
What we need is a routing mechanism that allows us to select which method to use. We need to be able
to specify a number of methods within our configuration that can be used directly and therefore bypass
the entry point resolver logic. What we really need is the ability to specify a different endpoint for each
of the methods; i.e, to be able to route along a particular channel but control which part of the consumer
will actually be invoked. Mule has such a property for the endpoints - the MULE_SERVICE_METHOD
property that needs to be configured on both the inbound and outbound endpoints. Component "A" would
have the following outbound router configured:
<outbound-router>
<router className="org.mule.routing.outbound.OutboundPassThroughRouter">
<endpoint address="vm://Communication?method=Method1"/>
</router>
</outbound-router>
Here, the endpoint is defined as it usually is but has a "method" property which we have set to
"Method1". We therefore want the result of this service component to be sent along the VM channel
called "Communication" and passed along to the method called "Method1" Component "B" would have the
following inbound router configured:
Note that the configuration of the inbound router and the inbound endpoint is the same as it usually
is. The difference is the addition of the properties on the Mule descriptor. We can therefore route a
message along a channel for a specific method as long as the methods are defined as properties on the
mule-descriptor. This allows us to bypass the entry point resolver logic and control which method to
invoke in case of multiple methods having the same parameters.
Pitfalls
Here, the Mule configuration is tightly coupled with the implementation of your component. If
the component changes and the methods are renamed, you will need to adjust your configuration
accordingly.
Restrictions
This will only work on synchronous paradigms. This will currently not work if your processing is
asynchronous due to an issue with threading.
Filtering
Of course, we still need to figure out what criteria to look out for before routing using this mechanism. If
"B" has any number of methods, we still need to figure out which method is the correct one for each
message. If we take a simple content based example, the criteria would be contained within the payload
itself. In such a situation, the Mule configuration would look like this:
This cookbook contains various examples on how to invoke Oracle SOA BPEL engine from Mule and how
to invoke services hosted on Mule from BPEL engine.
Although these examples are based on the Oracle BPEL Engine, they demonstrate how Mule can be
integrated with any BPEL engine via standard SOAP endpoints (web services) and JMS.
• How to invoke Oracle SOA BPEL engine from Mule using Web Services — A Mule configuration that
demonstrates how to invoke Oracle SOA BPEL engine using Web Services
• How to invoke Oracle SOA BPEL from Mule Using JMS connector — A Mule configuration file that
demonstrates how to invoke an Oracle BPEL process using Jms connector
• How to invoke services hosted on Mule from SOA BPEL process — Demonstrates how to invoke
services hosted on Mule from SOA BPEL engine
A Mule configuration that demonstrates how to invoke Oracle SOA BPEL engine using Web Services
Following example is tested against Oracle SOA Suite 10g Release 3 (10.1.3.1.0). Oracle SOA comes with
several sample processes. CreditRatingService a bpel process that receives a social security number and
returns credit rating. Following is the picture of the process.
Following is a Mule configuration file to invoke this process using xfire endpoint. Notice that the input,
social security number, is given from commandline. The result of process invocation, credit score, is
converted to xml string and displayed on the console.
A Mule configuration file that demonstrates how to invoke an Oracle BPEL process using Jms connector
Following example is tested usingOracle SOA Suite 10g Release 3 (10.1.3.1.0). Oracle SOA comes with
several sample processes. Queue2Topic a bpel process that receives an xml instance of expense record
on a queue and publishes it to a topic. Following is the snapshot of the process:
Following is a Mule configuration file to invoke this process using Jms connnector. Notice thatjms/
demoQueue is Jndi name of the receiving queue. jms/QueueConnectionFactory is the jndi name of
theQueueConnectionFactory. The input, expense record, is given from commandline as xml string.
sample input:
Expense Record:
<ExpenseRecord xmlns="http://xmlns.oracle.com/pcbpel/samples/expense">
<EmpId>111</EmpId>
<Item>PC</Item>
<Count>1</Count>
<Cost>1149.99</Cost>
</ExpenseRecord>
Demonstrates how to invoke services hosted on Mule from SOA BPEL engine
Following example is tested against Oracle SOA Suite 10g Release 3 (10.1.3.1.0). In order to invoke a
web service on Mule, the WSDL file for the service needs to copied to a local directory. For example, the
configuration file for a HelloWorld service deployed on mule is given below.
"http://mule.mulesource.org/dtds/mule-configuration.dtd">
The Java code that that implements the logic of this web service is given below:
package org.mule.samples.hello;
In order to get WSDL file for this service, open a browser and enter url "http://<host>:81/
services/helloWorld?WSDL". Save this file to a local directory where Oracle SOA is installed.
Following is a simple Oracle process that receives a string as input. Using the input string, it invokes the
Mule service using web service call.
In order to invoke the process, go to BPEL console using a browser and invoke the process.
The JavaSpaces module for Mule is now hosted at MuleForge. You can go directly to the project here.