Top Banner
Document generated by Confluence on Mar 25, 2009 00:56 Page 1 Space Details Key: MULE2USER Name: Mule 2.x User Guide Description: Mule Users Guide for the 2.x release line Creator (Creation Date): ross (Jan 30, 2008) Last Modifier (Mod. Date): tcarlson (Apr 15, 2008) Available Pages Home Storing Objects in the Registry About Transports Available Transports BPM Transport CXF Transport Building a CXF Web Service CXF Transport Configuration Reference Enabling WS-Addressing Enabling WS-Security Supported Web Service Standards Using a Web Service Client as an Outbound Endpoint Using a Web Service Client Directly Using HTTP GET Requests Using MTOM EJB Transport Email Transport File Transport FTP Transport HTTPS Transport HTTP Transport IMAPS Transport IMAP Transport JDBC Transport JDBC Transport Examples JDBC Transport Performance Benchmark Results Jetty Transport Jetty SSL transport JMS Transport Mule WMQ Transport Multicast Transport POP3S Transport POP3 Transport Quartz Transport
733
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 1

Space DetailsKey: MULE2USER

Name: Mule 2.x User Guide

Description: Mule Users Guide for the 2.x release line

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

Last Modifier (Mod. Date): tcarlson (Apr 15, 2008)

Available Pages• Home

• Storing Objects in the Registry

• About Transports

• Available Transports• BPM Transport

• CXF Transport• Building a CXF Web Service

• CXF Transport Configuration Reference

• Enabling WS-Addressing

• Enabling WS-Security

• Supported Web Service Standards

• Using a Web Service Client as an Outbound Endpoint

• Using a Web Service Client Directly

• Using HTTP GET Requests

• Using MTOM

• EJB Transport

• Email Transport

• File Transport

• FTP Transport

• HTTPS Transport

• HTTP Transport

• IMAPS Transport

• IMAP Transport

• JDBC Transport• JDBC Transport Examples

• JDBC Transport Performance Benchmark Results

• Jetty Transport• Jetty SSL transport

• JMS Transport

• Mule WMQ Transport

• Multicast Transport

• POP3S Transport

• POP3 Transport

• Quartz Transport

Page 2: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 2

• RMI Transport

• Servlet Transport

• SMTPS Transport

• SMTP Transport

• SOAP Transport

• SSL Transport

• STDIO Transport

• TCP Transport

• UDP Transport

• VM Transport

• WSDL Transport

• XMPP Transport

• Bootstrapping the Registry

• Choosing the Right Topology

• Configuration Overview

• Configuration Reference• Asynchronous Reply Router Configuration Reference

• Catch All Strategy Configuration Reference

• Component Configuration Reference

• Endpoint Configuration Reference

• Exception Strategy Configuration Reference

• Filters Configuration Reference

• Global Settings Configuration Reference

• Inbound Router Configuration Reference

• Model Configuration Reference

• Notifications Configuration Reference

• Outbound Router Configuration Reference

• Properties Configuration Reference

• Service Configuration Reference

• Transactions Configuration Reference

• Configuring a Mule Instance• Configuring Endpoints

• Mule Endpoint URIs

• Using Filters

• Configuring a Transport• Configuring Retry Policies

• Configuring Logging

• Configuring Queues

• Configuring Security• Component Authorization Using Acegi

• Component Authorization Using Spring Security

• Configuring the Acegi Security Manager

Page 3: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 3

• Configuring the Spring Security Manager

• Encryption Strategies

• Setting up LDAP Provider for Acegi

• Setting up LDAP Provider for Spring Security

• Upgrading from Acegi to Spring Security

• Controlling the Infrastructure with Mule Galaxy

• Creating a Custom XML Namespace

• Creating Custom Routers

• Creating Transports• Transport Archetype

• Transport Service Descriptors

• Deployment Scenarios• Deploying Mule to WebLogic

• Embedding Mule in a Java Application or Webapp

• JBoss Integration• Mule as MBean

• Developing Service Components• Entry Point Resolver Configuration Reference

• Error Handling

• Functional Testing

• Open MQ Integration

• Internationalizing Strings

• Introduction to Extending Mule

• Introduction to Testing Mule

• Models

• Mule Agents• Jmx Management

• Mule Server Notifications

• Profiling Mule

• Resource Adapter

• Suggested Reading

• Third-party Software in Mule

• Transaction Management

• Tuning Performance

• Unit Testing

• Using IDEs

• Using Mule HQ• Installing Mule HQ with an External Database

• Mule HQ Agent Settings

• Using Mule Modules• Acegi Module

• JAAS Module

• JBoss Transaction Manager

Page 4: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 4

• Scripting Module

• Spring Extras Module

• SXC Module

• XML Module• DomToXml Transformer

• JXPath Extractor Transformer

• XmlObject Transformers

• XmlToXMLStreamReader Transformer

• XPath Extractor Transformer

• XSLT Transformer

• Using Mule with Spring• Sending and Receiving Mule Events in Spring

• Spring Application Contexts

• Using Spring Beans as Service Components

• Using the Mule Client

• Using the Mule RESTpack• Architecting RESTful HTTP applications

• Making Sense of REST

• Using Transformers• Creating Custom Transformers

• Transformers Configuration Reference

• XmlPrettyPrinter Transformer

• Using Web Services• Axis

• Axis SOAP Styles

• Axis SOAP Transports

• Axis Transport

• Axis Web Services and Mule

• Configuring Axis

• Proxying Web Services

• Using .NET Web Services with Mule

• Web Service Wrapper

• Working with Services• Configuring Components

• Configuring Java Components

• Using Interceptors

• Configuring the Service

• MEPs

• Mule Messaging Styles

• Using Message Routers• Component Bindings

• Using the WireTap Inbound Router

• XML Configuration

Page 5: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 5

• ActiveMQ Integration

• Example Archetype

• Fiorano Integration

• Integrating SwiftMQ with Mule

• Jaas Security

• JBoss Jms Integration

• Module Archetype

• OpenJms Integration

• PGP Security

• Project Archetype

• SeeBeyond JMS Server Integration

• SonicMQ Integration

• Sun JMS Grid Integration

• Tibco EMS Integration

• Using Expressions• Creating Expression Evaluators

• Expressions Configuration Reference

• WebLogic JMS Integration

Page 6: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 6

Home

This page last changed on Mar 23, 2009 by jwheeler.

Some of the documentation on this site is under construction for the current release. If you have anyfeedback on the content, or would like to sign up to become a site contributor or editor, please contactus.

Getting Started

(Click the arrow to expand the topics from theGetting Started guide, including an introductionto Mule, steps to get started, and migrationinformation.)

Click here to expand...

• Introduction° What is Mule?° Understanding the Messaging

Framework° Understanding the Mule Architecture° Understanding the Logical Data Flow° Integrating Mule into Your Environment° Summary

• Getting Started° Quick Start° Download Page° Installing Mule° Running Mule° Setting Up Eclipse° Examples° Basic Usage° What's New in This Release° Migrating Mule

Using Mule

• Configuring Mule° Configuration Overview° XML Configuration° Configuring a Mule Instance° Configuring Endpoints° Using Transformers° About Models

• Working with Services° Configuring the Service° Configuring Components° Using Message Routers° Using Filters° Mule Messaging Styles° Using Web Services° Using Spring Beans as Service

Components• Customizing Behavior

° Developing Service Components° Creating Custom Transformers° Creating Custom Routers° Creating Custom Filters

Using Transports

• About Transports• Available Transports• Configuring a Transport

Mule DeploymentArchitecture

• Deployment Scenarios• Choosing the Right Topology

Mule Administration

• Managing and Monitoring Deployments°

Using Mule HQ ° Jmx Management

• Controlling the Infrastructure with MuleGalaxy

Extending Mule

• Introduction to Extending Mule• Creating Transports• Creating a Custom XML Namespace• Creating Expression Evaluators• Bootstrapping the Registry• Internationalizing Strings• Using MuleForge

Testing Mule

• Introduction to Testing Mule• Functional Testing• Unit Testing• Running Benchmark Tests• Profiling Mule

Development Tools

• Developer's Guide• Using IDEs• Mule IDE User Guide• Using Maven

Page 7: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 7

° Using Interceptors° Configuring Retry Policies

• Beyond the Basics° Using Expressions° Using Mule with Spring° Using the Mule RESTpack° Using Mule Modules° Error Handling° Storing Objects in the Registry° Configuring Security° Using the Mule Client° Tuning Performance° Configuring Queues° Managing Transactions° Using Agents° Mule Server Notifications° Configuring Logging

Reference

• Glossary• Configuration Reference• API Reference• Test API Reference• Third-party Software in Mule• Suggested Reading• Distribution Contents• PDF versions of the User's Guide for offline

reading

Documentation for PreviousReleases

Click a link below to view the documentation forthat release.

• Mule 1.x Getting Started• Mule 1.x User Guide

Page 8: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 8

Storing Objects in the Registry

This page last changed on Feb 14, 2009 by tcarlson.

Storing Objects in the Registry

If you need to store runtime data that is available across the application, you can store the data asobjects in the Registry . You can get a handle to the Registry from anywhere that you have access to theMuleContext , as in most Mule entities. For example, you could store the object as follows:

muleContext.getRegistry().registerObject("foo", new MyFoo());

You could then update the object from somewhere else:

Foo foo = (Foo) muleContext.getRegistry().lookupObject("foo");foo.setBarVal(25);// Replace the previous objectmuleContext.getRegistry().registerObject("foo", foo);

This approach is useful for storing an object that is needed by multiple components across yourapplication.

Page 9: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 9

About Transports

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

About Transports

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

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

Related TopicsAvailable TransportsConfiguring a TransportCreating Transports

Page 10: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 10

Available Transports

This page last changed on Jan 19, 2009 by jackie.wheeler.

Available Transports

[ Mule Transports ] [ Transports Feature Matrix ]

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

• About Transports• Configuring a Transport• Creating Transports

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

The following list includes some prominent transports from MuleForge (denoted by ). Transports that

are available only in Mule Enterprise Edition are denoted by .

Mule Transports

Transport Description

AS400 DQ TransportConnectivity to IBM AS400 Data Queue messagingserver. This transport is available on MuleForge.

Axis Transport Allows Mule managed components to be publishedas Axis services and allows components to invokeweb services using Axis client calls.

BPM Transport Allows Mule events to initiate and/or advanceprocesses in a Business Process ManagementSystem (BPMS) a.k.a. Process Engine.

CXF Transport Provides support for web service integration viaApache CXF.

EJB Transport Allows EJB invocations to be made using outboundendpoints.

Email Transport This transport supplies various email connectivityoptions.

File Transport This transport allows files to be read and writtento directories on the local file system. Theconnector can be configured to filter the fileit reads and the way files are written, suchas whether binary output is used or the file isappended to.

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

Page 11: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 11

HTTP Transport This transport supplies HTTP transport of Mulemessages between applications and other Muleservers.

HTTPS Transport A secure version of the HTTP transport.

IMAP Transport Connectivity to IMAP mail folders.

IMAPS Transport A secure version of the IMAP transport.

JCR TransportA transport that reads from, writes to, andobserves JCR 1.0 containers. This transport isavailable on MuleForge.

JDBC TransportA transport for JDBC connectivity. Some of itsfeatures are available only in Mule EnterpriseEdition.

Jetty Transport Provides support for exposing services over HTTPby embedding a light-weight Jetty server. Forinbound endpoints only.

Jetty SSL transport A secure version of the Jetty transport.

JMS Transport A Mule transport for JMS connectivity. Mule itselfis not a JMS server but can use the services ofany JMS 1.1 or 1.02b compliant server suchas ActiveMq, OpenJms, Joram, JBossMQ, andcommercial vendors such as WeblogicMQ,WebsphereMQ, SonicMQ, SeeBeyond, etc.

Multicast Transport Allows your components to receive and sendevents via IP multicast groups.

POP3 Transport Connectivity to POP3 inboxes.

POP3S Transport A secure version of the POP3 transport.

Quartz Transport Provides scheduling facilities with cron /interval definitions and allows Mule events to bescheduled/rescheduled.

RMI Transport Enables events to be sent and received over RMIvia JRMP.

Servlet Transport Provides facilities for Mule components to listenfor events received via a servlet request. Thereis also a servlet implementation that uses theServlet transport to enable REST style servicesaccess. This transport is now bundled with theHTTP transport.

SMTP Transport Connectivity to SMTP servers.

SMTPS Transport A secure version of the SMTP transport.

SOAP Transport Enables your components to be exposed as webservices and to act as SOAP clients. The SOAPtransport supports CXF and Apache Axis.

SSL Transport Provides secure socket-based communicationusing SSL or TLS.

Page 12: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 12

STDIO Transport This transport provides connectivity to streamssuch as System.in and System.out and is usefulfor testing.

TCP Transport Enables events to be sent and received over TCPsockets.

UDP Transport Enables events to be sent and received asdatagram packets.

VM Transport Enables event sending and receiving over VM,embedded memory, or persistent queues.

WebSphere MQ TransportA Mule transport for WebSphere MQ. Thistransport is available with Mule Enterprise version1.6 and later.

WSDL Transport Invokes remote web services by obtaining theservice WSDL. Mule will create a dynamic proxyfor the service and then invoke it.

XMPP Transport Provides connectivity over the XMPP (Jabber)instant messaging protocol.

Transports Feature Matrix

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

Transport ReceiveEvents

DispatchEvents

RequestEvents

Request/ResponseEvents

TransactionsStreamingInboundMEPs

OutboundMEPs

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

Out-OnlyOut-In Out-Optional-In

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

Out-Only

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

Out-OnlyOut-In Out-Optional-In

EJB In-Only Out-OnlyOut-In Out-Optional-In

Email In-Only Out-Only

Page 13: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 13

File In-Only Out-Only

FTP In-Only Out-Only

HTTP In-Out In-Optional-Out

Out-In Out-Optional-In

HTTPS In-Out In-Optional-Out

Out-In Out-Optional-In

IMAP In-Only

IMAPS In-Only

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

Out-OnlyOut-In Out-Optional-In

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

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

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

Out-OnlyOut-In Out-Optional-In

Multicast In-Out In-Optional-Out

Out-In Out-Optional-In

POP3 In-Only

POP3S In-Only

Quartz In-Only Out-Only

RMI In-Only Out-OnlyOut-In

Servlet In-Only In-Out In-

Page 14: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 14

Optional-Out

SMTP Out-Only

SMTPS Out-Only

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

Out-OnlyOut-In Out-Optional-In

STDIO In-Only Out-Only

TCP In-Out In-Optional-Out

Out-In Out-Optional-In

UDP In-Out In-Optional-Out

Out-In Out-Optional-In

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

Out-OnlyOut-In Out-Optional-In

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

Out-OnlyOut-In Out-Optional-In

Heading Descriptions

Transport - The name/protocol of the transportReceive Events - Whether the transport can receive events and can be used for an inbound endpointDispatch - Whether events can be sent asynchronouslyRequest - Whether this endpoint can be queried directly with a requestRequest/Response - Whether this endpoint can be queried directly with a request and return aresponse (implementation of the request() method in MessageRequester)Transactions - Whether transactions are supported by the transport. Transports that supporttransactions can be configured in a distributed two-phase commit (distributed) transaction.Streaming - Whether this transport can stream data between endpoints. This allows for very efficientprocessing of large data.Inbound and Outbound MEPs - The messaging exchange patterns (MEPs) supported by the inboundand outbound endpoints of the transport. See Mule Messaging Styles for more information on themessaging styles Mule supports and how they map to MEPs.

Page 15: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 15

BPM Transport

This page last changed on Mar 17, 2009 by jackie.wheeler.

BPM Transport

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

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

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

Javadocs for the BPM transport are available here .

Features

• Incoming Mule events can launch new processes, advance or terminate running processes.• A running process can generate synchronous or asynchronous Mule events.• Endpoints of type "bpm://MyProcess" are used to intelligently route process-generated events within

Mule.• Synchronous responses from Mule are automatically fed back into the running process.• Mule can interact with different running processes in parallel.

BPELThe connector can only integrate with BPM engines that provide a Java API. If you need tointegrate with a BPEL engine that only exposes SOAP endpoints (i.e., "a black box"), youwill need to use standard web services.

Usage

Sending events to the BPMS

The basic URI for a new process is:

bpm://ProcessType

For a running process, use:

bpm://ProcessType/ProcessID

Initiate a new process of type "MyBigProcess"

bpm://MyBigProcess

Advance an already running process with ID = 4561

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

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

bpm://MyBigProcess/4561

Update process variables (without advancing the process)

bpm://MyBigProcess/4561?action=update

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

Page 16: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 16

bpm://MyBigProcess/4561?action=abort

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

Incoming Messages to the BPMS

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

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

named "incomingSource"

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

Generating Events from the BPMS

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

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

bpm://MyBigProcess/4561

and if not, then by this endpoint:

bpm://MyBigProcess

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

bpm://*

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

Integration with BPM Engines

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

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

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

// Advance an already-running process. public Object advanceProcess(Object processId, Object transition, Map processVariables);

// Update the variables/parameters for an already-running process. public Object updateProcess(Object processId, Map processVariables);

// Abort a running process (end abnormally). public void abortProcess(Object processId); // MessageService is a callback method used to generate Mule messages from your process. public void setMessageService(MessageService msgService);

Page 17: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 17

}

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

Integration with JBoss jBPM

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

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

Configuration

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

<?xml version="1.0" encoding="UTF-8"?><mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:bpm="http://www.mulesource.org/schema/mule/bpm/2.2" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/bpm/2.2 http://www.mulesource.org/schema/mule/bpm/2.2/mule-bpm.xsd">

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

<!-- BPMS object for Mule's BPM Connector --> <spring:bean id="jbpm" class="org.mule.transport.bpm.jbpm.Jbpm" destroy-method="destroy"> <spring:property name="jbpmConfiguration"> <spring:ref local="jbpmConfig" /> </spring:property> </spring:bean>

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

Page 18: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 18

<spring:property name="createSchema"> <spring:value>false</spring:value> </spring:property> </spring:bean>

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

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

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

</mule>

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

ProcessConnector connector = new ProcessConnector();

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

MuleManager.getInstance().registerConnector(connector);

Page 19: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 19

Generating a Mule Message from jBPM

Use the org.mule.transport.bpm.jbpm.actions.SendMuleEvent ActionHandler to generate a Mule messagefrom your jBPM process:

<process-definition name="sendMessageProcess">

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

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

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

<end-state name="end" />

</process-definition>

jBPM Action Handlers for Mule

The primary way of adding custom functionality to jBPM is via ActionHandlers. The BPM transportprovides 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, theresponse from Mule will be automatically stored in the "incoming" process variable.

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

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

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

Configuration

Following is a simple configuration example:

<?xml version="1.0" encoding="UTF-8"?><mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:bpm="http://www.mulesource.org/schema/mule/bpm/2.2" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd

Page 20: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 20

http://www.mulesource.org/schema/mule/bpm/2.2 http://www.mulesource.org/schema/mule/bpm/2.2/mule-bpm.xsd">

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

<model name="bpm_example"> <!-- Messages sent to the process engine --> <service name="ToBPMS"> <inbound> <inbound-endpoint address="Incoming1"/> <inbound-endpoint address="Incoming2"/> </inbound> <log-component/> <outbound> <filtering-router> <outbound-endpoint address="bpm://MyProcess" synchronous="false" /> </filtering-router> </outbound> </service>

<!-- Messages generated from the process engine --> <service name="FromBPMS"> <inbound> <inbound-endpoint address="bpm://MyProcess" /> </inbound> <log-component/> <outbound> <bpm:outbound-router> <outbound-endpoint address="Outgoing1"/> <outbound-endpoint address="Outgoing2"/> <outbound-endpoint address="Outgoing3"/> </bpm:outbound-router> </outbound> </service> </model></mule>

Message Properties

Property Description Default Required

processType The name of theprocess

yes

processId The unique ID of therunning process

yes, unless action ="start"

action Action to perform onthe BPMS: "start" /"advance" / "update" /"abort"

"advance" if processIdexists, otherwise "start"

no

transition Transition to take ifmore than one exitpath is available for thecurrent process state

no

Page 21: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 21

Connector

Attributes of <connector...>

Name Type Required Default Description

bpms-ref name (no spaces) no A reference tothe underlyingBPMS, which mustimplement theorg.mule.transport.bpm.BPMSinterface toexchangemessages throughMule using theBPM transport.

allowGlobalReceiver boolean no false The globalreceiver allowsan endpoint oftype "bpm://*"to receive anyincoming messageto the BPMS,regardless of theprocess. If this isfalse, the processname must bespecified for eachendpoint. Forexample, "bpm://MyProcess" willonly receivemessages forthe process"MyProcess".

allowGlobalDispatcherboolean no false If false, anymessagegenerated bythe process isrouted fromthe componenton which it isreceived. If true, aprocess can sendmessages to anyendpoint on anycomponent.

processIdField string no This field will beused to correlatemessages withprocesses.

Page 22: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 22

CXF Transport

This page last changed on Feb 09, 2009 by jackie.wheeler.

CXF Transport

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

Introduction

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

Note: The CXF transport requires Java 5.0.

Features

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

• Integrated Installer: CXF and XFire have some conflicting libraries and therefore cannot both bedeployed in the same instance of Mule. The Mule Enterprise installer allows you to install CXF whenyou're installing Mule and handles all library changes for you. This is an enhancement over thesnapshot version of the CXF transport on MuleForge.

• Bookstore Example: A complete example of using the CXF transport to send complex objects.• MTOM Support: The CXF transport supports SOAP Message Transmission Optimization Mechanism

(MTOM), which specifies an optimized method for sending binary data as part of a SOAP message.• Complete Functional Tests: The functional tests have been converted from XFire to CXF.

Using the CXF Transport

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

Building a CXF Web ServiceUsing Web Services over JettyUsing a Web Service Client as an Outbound EndpointUsing a Web Service Client DirectlyUsing HTTP GET RequestsUsing MTOMProxying Web ServicesSupported Web Service StandardsEnabling WS-AddressingEnabling WS-SecurityBookstore ExampleConfiguration Reference

Troubleshooting

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

I've received a "java.lang.IllegalArgumentException: wrong number of arguments" whenusing the CXF outbound endpoint

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

Page 23: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 23

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

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

Your message payload must be like this:

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

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

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

Your WebService annotation should look like this:

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

Suggested Reading

XFire->CXF Migration GuideXFire and Celtix Merge FAQ

Page 24: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 24

Building a CXF Web Service

This page last changed on Mar 25, 2009 by jwheeler.

Building a CXF Web Service

[ Creating a JAX-WS Service ] [ Configuring Mule to Use the Web Service ] [ Using WSDL-firstMethodologies ] [ Changing the Data Binding ] [ Setting the Binding URI ] [ Changing the DefaultMessage Style ]

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

Creating a JAX-WS Service

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

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

package org.example;

import javax.jws.WebService;

@WebServicepublic interface HelloWorld { String sayHi(String text);}

Your implementation would then look like this:

package demo.hw.server;

import javax.jws.WebService;

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

public String sayHi(String text) { return "Hello " + text; }}

Configuring Mule to Use the Web Service

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

<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:spring="http://www.springframework.org/schema/beans" xmlns:cxf="http://www.mulesource.org/schema/mule/cxf/2.2" xsi:schemaLocation="http://www.springframework.org/schema/beans

Page 25: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 25

http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/cxf/2.2http://www.mulesource.org/schema/mule/cxf/2.2/mule-cxf.xsd"><model name="CxfExample"> <service name="helloService"> <inbound> <inbound-endpoint address="cxf:http://localhost:63081/hello" /> </inbound> <component> <singleton-object class="org.example.HelloServiceImpl" /> </component></service>...

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

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

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

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

Using WSDL-first Methodologies

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

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

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

Supplying the Original WSDL to CXF

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

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

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

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

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

Page 26: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 26

Changing the Data Binding

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

1. AegisDatabinding2. JAXBDatabinding (Default)3. StaxDatabinding

You specify the databinding class to use as follows:

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

Setting the Binding URI

The bindingUri attribute specifies how your service operations are mapped to resources. You configurethis attribute as follows:

<inbound-endpoint address="cxf:http://localhost:18080/mule/CxfService" bindingUri="http://www.w3.org/2003/05/soap/bindings/HTTP/" />

Changing the Default Message Style

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

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

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

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

Page 27: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 27

CXF Transport Configuration Reference

This page last changed on Feb 20, 2009 by jackie.wheeler.

CXF Transport Configuration Reference

[ Connector ] [ Inbound Endpoint ] [ Outbound Endpoint ] [ Endpoint ] [ Common CXF Endpoint Elements] [ Wrapper Component ] [ Stax ]

This page provides reference information about the elements and attributes you can configure for the CXFTransport.

Connector

Attributes of <connector...>

Name Type Required Default Description

defaultFrontend string no jaxws The CXF frontendthat is usedto build aninternal servicerepresentationfrom your Javaclasses. Thedefault is "jaxws".The "simple"frontend is alsosupported.

configurationLocationstring no The location of aCXF configurationfile, if any needsto be supplied.

initializeStaticBusInstanceboolean no true Initialize the staticCXF Bus with aBus configured touse Mule for alltransports. Thiswill affect anyCXF generatedclients that yourun standalone.Defaults to true.

Inbound Endpoint

Attributes of <inbound-endpoint...>

Name Type Required Default Description

frontend jaxws/simple no The CXF frontendthat is usedto build aninternal service

Page 28: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 28

representationfrom your Javaclasses. Thedefault is "jaxws".The "simple"frontend is alsosupported.

bindingUri string no The binding thatshould be usedfor this service.It defaults to theSOAP binding bydefault.

endpointName string no The WSDLendpoint name ofyour service.

namespace string no The servicenamespace. (As of2.2.1)

serviceClass string no The class CXFshould use toconstruct itsservice model.This is optional,and by defaultit will use theimplementationclass of yourcomponent.

serviceName string no The WSDL servicename of yourservice.

applyFiltersToProtocolboolean no true Whether to applythe filters to theprotocol endpoint.Defaults to truefor Mule 2.2+ andfalse for 2.1 andprevious versions.

applySecurityToProtocolboolean no true Whether to applythe security filterto the protocolendpoint. Defaultsto true for Mule2.2+ and false for2.1 and previousversions.

proxy boolean no Whether or notthis outboundendpoint is actingas a web serviceproxy. If so, itwill expect rawxml as the inputparameter andreturn an XML

Page 29: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 29

stream as theoutput.

mtomEnabled boolean no Whether ornot MTOM(attachmentsupport) isenabled for thisendpoint.

wsdlLocation string no The location ofthe WSDL for yourservice. If thisis a server sideendpoint it willserved to yourusers.

protocolConnector string no The name of theconnector thatyou wish to useto send/receivemessages on withCXF. (As of 2.1)

applyTransformersToProtocolboolean no true Whether to applythe transformersto the protocolendpoint. Defaultsto true for Mule2.2+ and false for2.1 and previousversions.

enableMuleSoapHeadersboolean no true Whether or notthis endpointshould write MuleSOAP headerswhich pass alongthe correlationand ReplyToinformation. Thisis true by default,but the MuleSOAP headersare only triggeredin situationswhere thereis an existingcorrelation IDand the ReplyToheader is set. (Asof 2.2.1)

The <inbound-endpoint> element also supports the common CXF endpoint elements.

Outbound Endpoint

Attributes of <outbound-endpoint...>

Name Type Required Default Description

Page 30: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 30

wsdlPort string no The WSDL portyou want to use tocommunicate withthe service.

clientClass string no The name of theclient class thatCXF generatedusing CXF'swsdl2java tool.You must usewsdl2java if youdo not have boththe client andthe server inthe same JVM.Otherwise, thiscan be optionalif the endpointaddress is thesame in bothcases.

operation string no The operation youwant to invokeon the outboundendpoint.

proxy boolean no Whether or notthis outboundendpoint is actingas a web serviceproxy. If so, itwill expect rawxml as the inputparameter andreturn an XMLstream as theoutput.

mtomEnabled boolean no Whether ornot MTOM(attachmentsupport) isenabled for thisendpoint.

wsdlLocation string no The location ofthe WSDL for yourservice. If thisis a server sideendpoint it willserved to yourusers.

protocolConnector string no The name of theconnector thatyou wish to useto send/receivemessages on withCXF. (As of 2.1)

Page 31: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 31

applyTransformersToProtocolboolean no true Whether to applythe transformersto the protocolendpoint. Defaultsto true for Mule2.2+ and false for2.1 and previousversions.

enableMuleSoapHeadersboolean no true Whether or notthis endpointshould write MuleSOAP headerswhich pass alongthe correlationand ReplyToinformation. Thisis true by default,but the MuleSOAP headersare only triggeredin situationswhere thereis an existingcorrelation IDand the ReplyToheader is set. (Asof 2.2.1)

The <outbound-endpoint> element also supports the common CXF endpoint elements.

Endpoint

Attributes of <endpoint...>

Name Type Required Default Description

frontend jaxws/simple no The CXF frontendthat is usedto build aninternal servicerepresentationfrom your Javaclasses. Thedefault is "jaxws".The "simple"frontend is alsosupported.

bindingUri string no The binding thatshould be usedfor this service.It defaults to theSOAP binding bydefault.

endpointName string no The WSDLendpoint name ofyour service.

Page 32: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 32

namespace string no The servicenamespace. (As of2.2.1)

serviceClass string no The class CXFshould use toconstruct itsservice model.This is optional,and by defaultit will use theimplementationclass of yourcomponent.

serviceName string no The WSDL servicename of yourservice.

applyFiltersToProtocolboolean no true Whether to applythe filters to theprotocol endpoint.Defaults to truefor Mule 2.2+ andfalse for 2.1 andprevious versions.

applySecurityToProtocolboolean no true Whether to applythe security filterto the protocolendpoint. Defaultsto true for Mule2.2+ and false for2.1 and previousversions.

wsdlPort string no The WSDL portyou want to use tocommunicate withthe service.

clientClass string no The name of theclient class thatCXF generatedusing CXF'swsdl2java tool.You must usewsdl2java if youdo not have boththe client andthe server inthe same JVM.Otherwise, thiscan be optionalif the endpointaddress is thesame in bothcases.

operation string no The operation youwant to invokeon the outboundendpoint.

Page 33: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 33

proxy boolean no Whether or notthis outboundendpoint is actingas a web serviceproxy. If so, itwill expect rawxml as the inputparameter andreturn an XMLstream as theoutput.

mtomEnabled boolean no Whether ornot MTOM(attachmentsupport) isenabled for thisendpoint.

wsdlLocation string no The location ofthe WSDL for yourservice. If thisis a server sideendpoint it willserved to yourusers.

protocolConnector string no The name of theconnector thatyou wish to useto send/receivemessages on withCXF. (As of 2.1)

applyTransformersToProtocolboolean no true Whether to applythe transformersto the protocolendpoint. Defaultsto true for Mule2.2+ and false for2.1 and previousversions.

enableMuleSoapHeadersboolean no true Whether or notthis endpointshould write MuleSOAP headerswhich pass alongthe correlationand ReplyToinformation. Thisis true by default,but the MuleSOAP headersare only triggeredin situationswhere thereis an existingcorrelation IDand the ReplyToheader is set. (Asof 2.2.1)

Page 34: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 34

The <endpoint> element also supports the common CXF endpoint elements.

Common CXF Endpoint Elements

Following are the sub-elements you can set on CXF endpoints. For further information on CXFinterceptors, see the CXF documentation.

Name Description

databinding The databinding implementation that should beused. By default, this is JAXB for the JAX-WSfrontend and Aegis for the simple frontend. Thisshould be specified in the form of a Spring bean.

features Any CXF features you want to apply to the client/server. See the CXF documentation for moreinformation on features.

inInterceptors Additional incoming interceptors for this service.

inFaultInterceptors Additional incoming fault interceptors.

outInterceptors Additional outgoing interceptors.

outFaultInterceptors Additional outgoing fault interceptors.

Wrapper Component

The WebServiceWrapperComponent class allows you to send the result of a web service call to anotherendpoint.

Attributes of <wrapper-component...>

Name Type Required Default Description

address string no The URL of theweb service.

addressFromMessageboolean no Specifies that theURL of the webservice will beobtained from themessage itself.

wsdlPort string no The WSDL portyou want to use tocommunicate tothe service.

operation string no The operation youwant to invokeon the outboundendpoint.

Page 35: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 35

Stax

Attributes of <stax...>

Name Type Required Default Description

xmlInputFactory string no

xmlOutputFactory string no

Page 36: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 36

Enabling WS-Addressing

This page last changed on Nov 04, 2008 by [email protected].

Enabling WS-Addressing

To enable your services to use WS-Addressing, you must configure the CXF endpoint to use the WS-Adressing feature:

<cxf:inbound-endpoint address="http://localhost:63081/services/employee"> <cxf:features> <wsa:addressing /> </cxf:features></cxf:inbound-endpoint>

This works with outbound endpoints as well:

<cxf:outbound-endpoint address="http://localhost:63081/services/employee" ..... > <cxf:features> <wsa:addressing /> </cxf:features></cxf:outbound-endpoint>

Note that currently "decoupled" reply to endpoints are not supported with Mule.

Manipulating WS-Addressing Headers

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

Page 37: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 37

Enabling WS-Security

This page last changed on Feb 09, 2009 by jackie.wheeler.

Enabling WS-Security

[ UsernameToken Scenario ] [ Server Configuration ] [ Client Configuration ] [ Configure the CXFClient to Use WS-Security ] [ Client Password Callback ] [ UsernameToken verification with the MuleSecurityManager ]

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

UsernameToken Scenario

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

Server Configuration

On the server side, you do the following:

• Create a Mule service for your component implementation• Configure the WSS4JInInterceptor and the SAAJInInterceptor. The former is responsible for checking

the security of your message.• Write a server PasswordCallback that verifies the password.

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

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

The <cxf:inInterceptors> element configures the incoming interceptors on the service. TheWSS4JInInterceptor performs the security operations on the incoming SOAP message. The"action" parameter controls which actions it performs on the incoming message - in this case the"UsernameToken" action specifies that it will verify the username token via a specified password callback.The password callback is specified by the "passwordCallbackRef" property, which is detailed in the next

Page 38: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 38

section. The SAAJInInterceptor is also installed here. It enables the use of SAAJ, an in-memory DOMdocument format, which is required by WSS4J.

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

import java.io.IOException;

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

import org.apache.ws.security.WSPasswordCallback;

public class ServerPasswordCallback implements CallbackHandler{

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

WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];

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

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

Client Configuration

On the client side, you do the following:

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

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

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

Page 39: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 39

</cxf:outInterceptors></cxf:outbound-endpoint>

Configure the CXF Client to Use WS-Security

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

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

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

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

The above configuration specifies the following:

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

Client Password Callback

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

import java.io.IOException;

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

import org.apache.ws.security.WSPasswordCallback;

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

// set the password for our message. pc.setPassword("yourpassword"); }

Page 40: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 40

}

UsernameToken verification with the Mule SecurityManager

If you're using the Mule security manager, you can set up WSS4J to verify passwords with it. This allowsyou to easily integrate your own authentication mechanisms or use Mule's support for Spring Security.

First, you'll want to set up your security manager:

<mule-ss:security-manager> <mule-ss:delegate-security-provider name="memory-dao" delegate-ref="authenticationManager"/> </mule-ss:security-manager>

<spring:beans> <ss:authentication-manager alias="authenticationManager"/>

<ss:authentication-provider> <ss:user-service id="userService"> <ss:user name="joe" password="password" authorities="ROLE_ADMIN" /> <ss:user name="anon" password="anon" authorities="ROLE_ANON" /> </ss:user-service> </ss:authentication-provider> </spring:beans>

Next, you'll want to create a <cxf:security-manager-callback> element. This callback is responsiblefor bridging together the Mule security manager and WSS4J.

<spring:beans> ... <cxf:security-manager-callback id="serverCallback"/> </spring:beans>

Finally, you'll want to set up your server side WSS4J handlers to use this callback:

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

In this example, the CXF inbound-endpoint creates a WSS4JInInterceptor which performsUsernameToken verification of the message. Once it reads in the username/password, it will perform acallback to the Mule security manager using the <cxf:security-manager-callback>.

Page 41: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 41

On the client side, you'll want to use plaintext passwords for this to work. To do this, setthe "passwordType" property on the WSS4JOutInterceptor to "PasswordText".

Page 42: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 42

Supported Web Service Standards

This page last changed on Dec 16, 2008 by jackie.wheeler.

Web Service Standards

The CXF transport supports a variety of web service standards.

• SOAP 1.1 and 1.2• WSDL 1.1• WS Addressing• WS Security 1.1• WS Policy• WS-I BasicProfile 1.1• WS-I SecurityProfile• SAML 1.0 (with WS-Security)• MTOM• SOAP with attachments

Future versions of Mule may support WS-ReliableMessaging. Although CXF currently supports it, it is noteasy to support "decoupled" WS-RM over non-native CXF transports, so it does not work well with Muletransports. One-way channels might work but are currently untested.

Future Releases

In version 2.2, the CXF transport is slated to support the following additional standards:

• WS-Trust• WS-SecureConversation• WS-SecurityPolicy• WS-Security

Page 43: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 43

Using a Web Service Client as an Outbound Endpoint

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

Using a Web Service Client as an OutboundEndpoint

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

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

• clientClass: The client class generated by CXF, which extends javax.xml.ws.Service.• port: The WSDL port to use for communicating with the service• wsdlLocation: The location of the WSDL for the service. CXF uses this to configure the client.• operation: The operation name to invoke on the web service. The objects that you pass to the

outbound router must match the signature of the method for this operation. If your method takesmultiple parameters, they must be put in an Object[] array.

Following is a simple example:

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

Page 44: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 44

Using a Web Service Client Directly

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

Using a Web Service Client Directly

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

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

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

HelloWorldService service = new HelloWorldService();HelloWorld hello = service.getSoapPort();

// Possibly set an alternate request URL:// ((BindingProvider) greeter).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:63081/greeter");String sayHi = hello.sayHi();

Building a Client Proxy

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

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

Service service = Service.create(SERVICE_NAME);

// Endpoint AddressString endpointAddress = http://localhost:63081/hello";

// Add a port to the Serviceservice.addPort(PORT_NAME, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress); HelloWorld hw = service.getPort(HelloWorld.class);

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

Additional Resources

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

Page 45: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 45

Using HTTP GET Requests

This page last changed on Feb 09, 2009 by [email protected].

Using HTTP GET Requests

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

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

For example:

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

The above Echo service is hosted in Mule on the endpoint cxf:http://localhost:65081/services/EchoUMO,so you can access the service from a simple web browser by typing the following:

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

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

Due to a bug in CXF, this is only supported with the JAX-WS frontend.

Page 46: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 46

Using MTOM

This page last changed on Nov 25, 2008 by jackie.wheeler.

Using MTOM

[ Writing an MTOM-enabled WSDL ] [ Generating Server Stubs and/or a Client ] [ Configuring the CXFInbound Endpoint ] [ Configuring the CXF Outbound Endpoint ]

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

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

1. Write your WSDL2. Generate your server stubs3. Configure the CXF endpoint in Mule

Writing an MTOM-enabled WSDL

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

Normally, when creating XML schema types for binary data, you would write a schema type like this:

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

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

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

<element name="yourData" type="xsd:base64Binary" xmime:expectedContentTypes="application/octet-stream"/>...</schema>

Generating Server Stubs and/or a Client

After writing your WSDL, you run wsdl2java on it to generate server stubs and a client (if you arecreating outbound endpoints). To do this, download the CXF distribution, extract it, and then enter thefollowing command:

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

Configuring the CXF Inbound Endpoint

The above command generates a server stub interface. This is the interface that your service mustimplement. Each method will correspond to an operation in your WSDL. If the base64Binary type is anargument to one of your operations, CXF will generate a method like this:

Page 47: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 47

public void yourOperation(DataHandler handler) {...}

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

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

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

Configuring the CXF Outbound Endpoint

The configuration of an MTOM client endpoint is exactly like the configuration of a normal CXF outboundendpoint, except that you must specify the mtomEnabled attribute. For example:

<cxf:outbound-endpoint name="outboundEmployeeDirectoryEndpoint" address="http://localhost:63081/services/employeeDirectory" clientClass="org.mule.example.employee.EmployeeDirectory_Service" operation="addEmployee" wsdlPort="EmployeeDirectoryPort" wsdlLocation="classpath:employeeDirectory.wsdl" mtomEnabled="true"/>

See the Using a Web Service Client as an Outbound Endpoint page for more information.

Page 48: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 48

EJB Transport

This page last changed on Feb 20, 2009 by jackie.wheeler.

EJB Transport

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

The Javadoc for this transport can be found here .

Connector

The Mule EJB Connector provides connectivity for EJB beans.

Attributes of <connector...>

Name Type Required Default Description

pollingFrequency long no Period (ms)between pollingconnections.

securityManager-ref

name (no spaces) no Bean referenceto the securitymanager thatshould be used.

securityPolicy string no The securitypolicy (file name)used to enableconnections.

serverClassName name (no spaces) no The target classname.

serverCodebase string no The targetmethod.

For example:

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

Using the EJB Connector

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

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

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

Page 49: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 49

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

Alternatively, you could use URI-based configuration:

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

If the method can take one or more input arguments, you configure their types as a comma-separatedlist using the methodArgumentTypes attribute. Multiple arguments are passed in as an array of objects asthe payload of the Mule message.

Transformers

There are no specific transformers required for EJB.

Page 50: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 50

Email Transport

This page last changed on Feb 20, 2009 by jackie.wheeler.

Email Transport

The Email transport provides a standard email connector that is extended by each of the email protocols.

Protocols

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

The email transports support protocol features such as attachments, replyTo, CC and BCC addresses,binary content types, and custom headers. Each email transport supports the following attributes forconnecting to the mail server:

Attribute Description

user The user name for connecting to the mail server

password The password for connecting to the mail server

host The host of the mail server

port The port of the mail server

The Javadoc for the email transports can be found here .

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

• SMTP and SMTPS Transport• POP3 and POP3S Transport• IMAP and IMAPS Transport

Filters

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

Filter Description

org.mule.transport.email.filters.AbstractMailFilter A base filter implementation that must beextended by any other mail filter.

org.mule.transport.email.filters.MailSubjectRegExFilterApplies a regular expression to a Mail Messagesubject.

For more information on filters, see Using Filters.

Transformers

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

Page 51: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 51

transformers.

Name Description

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

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

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

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

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

Page 52: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 52

File Transport

This page last changed on Mar 04, 2009 by jackie.wheeler.

File Transport

[ Connector ] [ Endpoint ] [ Inbound Endpoint ] [ Outbound Endpoint ] [ File To Byte Array Transformer] [ File To String Transformer ] [ Legacy Filename Parser ] [ Expression Filename Parser ] [ CustomFilename Parser ] [ Abstract Filenameparser ] [ Expressing File Endpoints ]

The File transport allows files to be read and written to and from directories on the local file system. Theconnector can be configured to filter the file it reads and the way files are written, such as whether theoutput will be placed in a new file or if it should be appended.

Connector

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

Attributes of <connector...>

Name Type Required Default Description

writeToDirectory string no The directory pathwhere the fileshould be writtenon dispatch. Thispath is usually setas the endpointof the dispatchevent, howeverthis allows you toexplicitly force asingle directory forthe connector.

readFromDirectory string no The directorypath where thefile should beread from. Thispath is usually setas the inboundendpoint, howeverthis allows you toexplicitly force asingle directory forthe connector.

autoDelete boolean no true If set to true (thedefault), it willcause the fileto be deletedonce it is read.If streaming isturned on, thisoccurs when theInputStream forthe file is closed.Otherwise the

Page 53: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 53

file will be readinto memoryand deletedimmediately.To access thejava.io.Fileobject set thisproperty to falseand specify aNoActionTransformertransformer forthe connector.Mule will notdelete the file,so it is up to thecomponent todelete it whenit is done. If themoveToDirectoryis set, the file isfirst moved, thenthe File object ofthe moved fileis passed to thecomponent. It isrecommendedthat amoveToDirectoryis specified whenturning autoDeleteoff.

outputAppend boolean no false Whether theoutput shouldbe appended tothe existing file.Default is false.

serialiseObjects boolean no Determineswhether objectsshould beserialized to thefile. If false (thedefault), the rawbytes or text iswritten.

streaming boolean no true Whether aFileInputStreamshould be sentas the messagepayload (if true)or a file (if false).The default istrue.

pollingFrequency long no The frequency inmilliseconds thatthe read directoryshould be checked(default is 0).Note that theread directoryis specified by

Page 54: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 54

the endpointof the listeningcomponent.

fileAge long no Miniumum age(ms) for a file tobe processed.This can be usefulwhen consuminglarge files. It tellsMule to wait fora period of timebefore consumingthe file, allowingthe file to becompletely writtenbefore the file isprocessed.

moveToPattern string no The pattern touse when movinga read file toa new locationdetermined by themoveToDirectoryproperty. This canuse the patternssupported by thefilename parserconfigured for thisconnector.

moveToDirectory string no The directory pathwhere the fileshould be writtenafter it has beenread. If this isnot set, the fileis deleted after ithas been read.

comparator class name no Sorts incomingfiles usingthe specifiedcomparator,such ascomparator="org.mule.transport.file.comparator.OlderFirstComparator".The class mustimplement thejava.util.Comparatorinterface.

reverseOrder boolean no Whether thecomparatororder should bereversed. Defaultis false.

outputPattern string no The pattern to usewhen writing a fileto disk. This canuse the patternssupported by thefilename parser

Page 55: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 55

configured for thisconnector.

Child Elements of <connector...>

Name Cardinality Description

abstract-filenameParser 0..1 The abstract-filenameParserelement is a placeholder forfilename parser elements. Thefilename parser is set on theconnector used when writingfiles to a directory. The parserwill convert the outputPatternattribute to a string using theparser and the current message.The default implmentation usedis legacy-filename-parser, butyou can specify expression-filename-parser or custom-filename-parser.

Endpoint

Attributes of <endpoint...>

Name Type Required Default Description

path string no A file directorylocation.

pollingFrequency long no The frequency inmilliseconds thatthe read directoryshould be checked(default is 0).Note that theread directoryis specified bythe endpointof the listeningcomponent.

fileAge long no Miniumum age(ms) for a file tobe processed.This can be usefulwhen consuminglarge files. It tellsMule to wait fora period of timebefore consumingthe file, allowingthe file to becompletely writtenbefore the file isprocessed.

Page 56: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 56

moveToPattern string no The pattern touse when movinga read file toa new locationdetermined by themoveToDirectoryproperty. This canuse the patternssupported by thefilename parserconfigured for thisconnector.

moveToDirectory string no The directory pathwhere the fileshould be writtenafter it has beenread. If this isnot set, the fileis deleted after ithas been read.

comparator class name no Sorts incomingfiles usingthe specifiedcomparator,such ascomparator="org.mule.transport.file.comparator.OlderFirstComparator".The class mustimplement thejava.util.Comparatorinterface.

reverseOrder boolean no Whether thecomparatororder should bereversed. Defaultis false.

outputPattern string no The pattern to usewhen writing a fileto disk. This canuse the patternssupported by thefilename parserconfigured for thisconnector.

Inbound Endpoint

Attributes of <inbound-endpoint...>

Name Type Required Default Description

path string no A file directorylocation.

pollingFrequency long no The frequency inmilliseconds thatthe read directory

Page 57: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 57

should be checked(default is 0).Note that theread directoryis specified bythe endpointof the listeningcomponent.

fileAge long no Miniumum age(ms) for a file tobe processed.This can be usefulwhen consuminglarge files. It tellsMule to wait fora period of timebefore consumingthe file, allowingthe file to becompletely writtenbefore the file isprocessed.

moveToPattern string no The pattern touse when movinga read file toa new locationdetermined by themoveToDirectoryproperty. This canuse the patternssupported by thefilename parserconfigured for thisconnector.

moveToDirectory string no The directory pathwhere the fileshould be writtenafter it has beenread. If this isnot set, the fileis deleted after ithas been read.

comparator class name no Sorts incomingfiles usingthe specifiedcomparator,such ascomparator="org.mule.transport.file.comparator.OlderFirstComparator".The class mustimplement thejava.util.Comparatorinterface.

reverseOrder boolean no Whether thecomparatororder should bereversed. Defaultis false.

Page 58: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 58

Outbound Endpoint

Attributes of <outbound-endpoint...>

Name Type Required Default Description

path string no A file directorylocation.

outputPattern string no The pattern to usewhen writing a fileto disk. This canuse the patternssupported by thefilename parserconfigured for thisconnector.

File To Byte Array Transformer

The file-to-byte-array-transformer element configures a transformer that reads the contents of ajava.io.File into a byte array (byte[]).

File To String Transformer

The file-to-string-transformer element configures a transformer that reads the contents of a java.io.Fileinto a java.lang.String.

Legacy Filename Parser

The legacy-filename-parser element configures the default filename parser used by the File connector. Itunderstands the following patterns:

• #[DATE] - The current date in the format dd-MM-yy_HH-mm-ss.SS• #[DATE:dd-MM-yy] - The current date using the specified format• #[SYSTIME] - The current system time milliseconds• #[UUID] - A generated universally unique ID• #[ORIGINALNAME] - The original file name if the file being written was read from another location• #[COUNT] - An incremental counter.

Expression Filename Parser

The expression-filename-parser element configures the ExpressionFilenameParser, which can use anyexpression language supported by Mule to construct a file name for the current message. Expressions canbe xpath, xquery, ognl, mvel, header, function, and more.

For example, an XPath expression can be defined to pull a message ID out of an XML message and usethat as the file name as follows:

#[xpath:/message/header/@id]

Following is an example of using the parser:

<file:connector name="FileConnector" > <file:expression-filename-parser/></file:connector>

Page 59: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 59

...<file:outbound-endpoint path="file://temp"outputPattern="#[header:originalFilename]--#[function:dateStamp].txt"/>

This parser supersedes <legacy-filename-parser> from previous releases of Mule. The followingdemonstrates how to achieve the same results when using <expression-filename-parser> over<legacy-filename-parser>.

• #[DATE] : #[function:dateStamp]• #[DATE:dd-MM-yy] : #[function:dateStamp:dd-MM-yy]• #[SYSTIME] : #[function:systime]• #[UUID] : #[function:uuid]• #[ORIGINALNAME] : #[header:originalFilename]• #[COUNT] : #[function:counter] - note that this is a global counter. If you want a local counter per

file connector then you should use the legacy-filename-parser.• #[message property name] : #[header:message property name]

Custom Filename Parser

The custom-filename-parser element allows the user to specify a custom filename parser. Theimplementation must implement org.mule.transport.file.FilenameParser.

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

Name Type Required Default Description

class name (no spaces) no Theimplementationclass name thatimplementsorg.mule.transport.file.FilenameParser.

Abstract Filenameparser

The abstract-filenameParser element is a placeholder for filename parser elements. The filename parseris set on the connector used when writing files to a directory. The parser will convert the outputPatternattribute to a string using the parser and the current message. The default implmentation used is legacy-filename-parser, but you can specify expression-filename-parser or custom-filename-parser.

Expressing File Endpoints

File endpoints can be expressed using standard File URI syntax:

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

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

Unix

file:///temp/files

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

Windows

file:///C:/temp/files

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

Page 60: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 60

To specify a relative path use:

file://./temp

or

file://temp

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

or

file://?address=./temp

To connect to a windows network drive:

file:////192.168.0.1/temp/

Page 61: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 61

FTP Transport

This page last changed on Mar 04, 2009 by jackie.wheeler.

FTP Transport

Table of Contents

Click here to expand...

• FTP Transport• ° Connector

° - Attributes of <connector...>- Child Elements of <connector...>-

Mule Enterprise Connector Attributes ° Endpoint° - Attributes of <endpoint...>° Inbound Endpoint° - Attributes of <inbound-endpoint...>° Outbound Endpoint° - Attributes of <outbound-endpoint...>° Generic FTP Endpoints° Filename Filters° - Property Overrides

The FTP transport provides connectivity to FTP servers to allow files to be read and written as messagesin Mule.

Connector

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

Attributes of <connector...>

Name Type Required Default Description

streaming boolean no Whether anInputStreamshould be sentas the messagepayload (if true)or a byte array (iffalse). Default isfalse.

connectionFactoryClassclass name no A class thatextendsFtpConnectionFactory.TheFtpConnectionFactoryis responsiblefor creating aconnection tothe server usingthe credentialsprovided bythe endpoint.

Page 62: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 62

The defaultimplementationsupplied withMule uses theCommons Netproject fromApache.

pollingFrequency long no How frequentlyin millisecondsto check theread directory.Note that theread directoryis specified bythe endpointof the listeningcomponent.

outputPattern string no The pattern to usewhen writing a fileto disk. This canuse the patternssupported by thefilename-parserconfigured for thisconnector

binary boolean no Select/disablebinary file transfertype. Default istrue.

passive boolean no Select/disablepassive protocol(more likely towork throughfirewalls). Defaultis true.

Child Elements of <connector...>

Name Cardinality Description

file:abstract-filenameParser 0..1 The filenameParser is usedwhen writing files to an FTPserver. The parser will convertthe outputPattern attribute toa string using the parser andthe current message. To add aparser to your configuration,you import the "file" namespaceinto your XML configuration.For more information aboutfilenameParsers, see the FileTransport.

Mule Enterprise Connector Attributes

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

Page 63: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 63

moveToDirectory The directory path where the file should bewritten after it has been read. If this property isnot set, the file is deleted.

moveToPattern The pattern to use when moving a read file to anew location as specified by the moveToDirectoryproperty. This property can use the patternssupported by the filenameParser configured forthis connector.

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

Endpoint

Attributes of <endpoint...>

Name Type Required Default Description

path string no A file location onthe remote server.

user string no If FTP isauthenticated,this is theusername used forauthenitcation.

password string no The password forthe user beingauthenticated.

host string no An IP address(such aswww.mulesource.com,localhost, or192.168.0.1).

port port number no The port numberto connect on.

binary boolean no Select/disablebinary file transfertype. Default istrue.

passive boolean no Select/disablepassive protocol(more likely towork throughfirewalls). Defaultis true.

pollingFrequency long no How frequentlyin millisecondsto check theread directory.Note that theread directory

Page 64: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 64

is specified bythe endpointof the listeningcomponent.

outputPattern string no The pattern to usewhen writing a fileto disk. This canuse the patternssupported by thefilename-parserconfigured for thisconnector

Inbound Endpoint

Attributes of <inbound-endpoint...>

Name Type Required Default Description

path string no A file location onthe remote server.

user string no If FTP isauthenticated,this is theusername used forauthenitcation.

password string no The password forthe user beingauthenticated.

host string no An IP address(such aswww.mulesource.com,localhost, or192.168.0.1).

port port number no The port numberto connect on.

binary boolean no Select/disablebinary file transfertype. Default istrue.

passive boolean no Select/disablepassive protocol(more likely towork throughfirewalls). Defaultis true.

pollingFrequency long no How frequentlyin millisecondsto check theread directory.Note that theread directoryis specified by

Page 65: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 65

the endpointof the listeningcomponent.

Outbound Endpoint

Attributes of <outbound-endpoint...>

Name Type Required Default Description

path string no A file location onthe remote server.

user string no If FTP isauthenticated,this is theusername used forauthenitcation.

password string no The password forthe user beingauthenticated.

host string no An IP address(such aswww.mulesource.com,localhost, or192.168.0.1).

port port number no The port numberto connect on.

binary boolean no Select/disablebinary file transfertype. Default istrue.

passive boolean no Select/disablepassive protocol(more likely towork throughfirewalls). Defaultis true.

outputPattern string no The pattern to usewhen writing a fileto disk. This canuse the patternssupported by thefilename-parserconfigured for thisconnector

Generic FTP Endpoints

FTP endpoints can be expressed using standard FTP URI syntax:

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

which would render a URI like this:

Page 66: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 66

ftp://joe:[email protected]/~

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

Escape Your Credentials

If you use a URI-style endpoint and you include the user name and password, escape anycharacters that are illegal for URIs, such as the @ character. For example, if the user nameis [email protected], you should enter it as user%40myco.com.

Filename Filters

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

<ftp:endpoint user="joe" password="123456" host="ftp.mycompany.com" path="/ftp/incoming"> <file:filename-wildcard-filter pattern="*.txt,*.xml"/></ftp:endpoint>

Property Overrides

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

For example, to set the output pattern:

<ftp:endpoint user="joe" password="123456" host="ftp.mycompany.com" path="/ftp/incoming" outputPattern="FtpFile-${DATE}.done"/>

Or to specify the same endpoint using a URI:

ftp://joe:[email protected]/ftp/done?outputPattern=FtpFile-${DATE}.done

For more information about configuring endpoints, see Configuring Endpoints.

Page 67: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 67

HTTPS Transport

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

HTTPS Transport

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

The Secure HTTP transport provides support for exposing services over HTTP and making HTTP clientrequests from Mule services to external services as part of service event flows. Mule supports secureinbound, secure outbound, and secure polling HTTP endpoints. These endpoints support all commonfeatures of the HTTP spec, such as ETag processing, cookies, and keepalive. Both HTTP 1.0 and 1.1 aresupported.

HTTPS Connector

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

Property Description

tls-client Configures the client key store with the followingattributes:

• path: The location (which will be resolvedrelative to the current classpath and filesystem, if possible) of the keystore thatcontains public certificates and private keysfor identification

• storePassword: The password used toprotect the keystore

• class: The type of keystore used (a Javaclass name)

tls-key-store Configures the direct key store with the followingattributes:

• path: The location (which will be resolvedrelative to the current classpath and filesystem, if possible) of the keystore thatcontains public certificates and private keysfor identification

• class: The type of keystore used (a Javaclass name)

• keyPassword: The password used to protectthe private key

• storePassword: The password used toprotect the keystore

• algorithm: The algorithm used by thekeystore

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

• path: The location (which will be resolvedrelative to the current classpath and file

Page 68: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 68

system, if possible) of the trust store thatcontains public certificates of trusted servers

• storePassword: The password used toprotect the trust store

• class: The type of trust store used (a Javaclass name)

• algorithm: The algorithm used by the truststore

• factory-ref: Reference to the trust managerfactory

• explicitOnly: Whether this is an explicit truststore

• requireClientAuthentication: Whether clientauthentication is required

tls-protocol-handler Configures the global Java protocol handler. Ithas one attribute, property, which specifies thejava.protocol.handler.pkgs system property.

For example:

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

Polling Connector

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

Attribute Description

pollingFrequency The time in milliseconds to wait between eachrequest to the remote http server.

checkEtag Whether the ETag header from the remote serveris processed if the header is present.

discardEmptyContent Whether Mule should discard any messagesfrom the remote server that have a zero contentlength. For many services, a zero length wouldmean there was no data to return. If the remoteHTTP server does return content to say that therequest is empty, users can configure a contentfilter on the endpoint to filter these messages out.

For example:

Page 69: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 69

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

HTTPS Endpoints

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

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

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

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

Page 70: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 70

HTTP Transport

This page last changed on Mar 19, 2009 by jackie.wheeler.

HTTP Transport

Table of Contents

Click here to expand...

• HTTP Transport• ° Connector

° - Attributes of <connector...>° Inbound Endpoint° - Attributes of <inbound-endpoint...>° Outbound Endpoint° - Attributes of <outbound-endpoint...>° Endpoint° - Attributes of <endpoint...>° Transformers° Polling Connector° - Attributes of <polling-connector...>° Rest Service Component° - Attributes of <rest-service-component...>

- Child Elements of <rest-service-component...>° Security° - Sending Credentials° Cookies° Polling HTTP Services° Handling HTTP Content-Type and Encoding° - Sending HTTP

- Receiving HTTP° Including Custom Header Properties° Handling Redirects° Getting a Hash Map of Properties

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

Note that HTTP/S endpoints are synchronous by default, so you do not have to set synchronous="true".

Connector

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

Attributes of <connector...>

Name Type Required Default Description

cookieSpec netscape/rfc2109 no The cookiespecificationto be used bythis connectorwhen cookies areenabled.

Page 71: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 71

proxyHostname string no The proxy hostname or address.

proxyPassword string no The passwordto use for proxyaccess.

proxyPort port number no The proxy portnumber.

proxyUsername string no The usernameto use for proxyaccess.

enableCookies boolean no Whether tosupport cookies.

Inbound Endpoint

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

Attributes of <inbound-endpoint...>

Name Type Required Default Description

user string no The user name(if any) thatwill be used toauthenticateagainst.

password string no The password forthe user.

host string no The host toconnect to.For inboundendpoints, thisshould be anaddress of a localnetwork interface.

port port number no The port numberto use when aconnection ismade.

path string no The path for theHTTP URL.

contentType string no The HTTPContentType touse.

method httpMethodTypes no The HTTP methodto use.

keep-alive boolean no Controls if thesocket connection

Page 72: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 72

is kept alive. If setto true, a keep-alive header withthe connectiontimeout specifiedin the connectorwill be returned.If set to false,a "Connection:close" header willbe returned.

Outbound Endpoint

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

Attributes of <outbound-endpoint...>

Name Type Required Default Description

user string no The user name(if any) thatwill be used toauthenticateagainst.

password string no The password forthe user.

host string no The host toconnect to.For inboundendpoints, thisshould be anaddress of a localnetwork interface.

port port number no The port numberto use when aconnection ismade.

path string no The path for theHTTP URL.

contentType string no The HTTPContentType touse.

method httpMethodTypes no The HTTP methodto use.

keep-alive boolean no Controls if thesocket connectionis kept alive. If setto true, a keep-alive header withthe connectiontimeout specifiedin the connector

Page 73: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 73

will be returned.If set to false,a "Connection:close" header willbe returned.

Endpoint

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

Attributes of <endpoint...>

Name Type Required Default Description

user string no The user name(if any) thatwill be used toauthenticateagainst.

password string no The password forthe user.

host string no The host toconnect to.For inboundendpoints, thisshould be anaddress of a localnetwork interface.

port port number no The port numberto use when aconnection ismade.

path string no The path for theHTTP URL.

contentType string no The HTTPContentType touse.

method httpMethodTypes no The HTTP methodto use.

keep-alive boolean no Controls if thesocket connectionis kept alive. If setto true, a keep-alive header withthe connectiontimeout specifiedin the connectorwill be returned.If set to false,a "Connection:close" header willbe returned.

Page 74: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 74

Transformers

These are transformers specific to this transport. Note that these are added automatically to the Muleregistryat start up. When doing automatic transformations these will be included when searching for the correcttransformers.

Name Description

http-response-to-object-transformer A transformer that converts an HTTP response toa Mule Message. The payload may be a String,stream, or byte array.

http-response-to-string-transformer Converts an HTTP response payload into a string.The headers of the response will be preserved onthe message.

object-to-http-request-transformer This transformer will creat a valid HTTP requestusing the current message and any HTTP headersset on the current message.

message-to-http-response-transformer This transformer will creat a valid HTTP responseusing the current message and any HTTP headersset on the current message.

Polling Connector

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

Attributes of <polling-connector...>

Name Type Required Default Description

cookieSpec netscape/rfc2109 no The cookiespecificationto be used bythis connectorwhen cookies areenabled.

proxyHostname string no The proxy hostname or address.

proxyPassword string no The passwordto use for proxyaccess.

proxyPort port number no The proxy portnumber.

proxyUsername string no The usernameto use for proxyaccess.

enableCookies boolean no Whether tosupport cookies.

Page 75: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 75

pollingFrequency long no The time inmilliseconds towait betweeneach request tothe remote HTTPserver.

checkEtag boolean no Whether the ETagheader from theremote server isprocessed if theheader is present.

discardEmptyContentboolean no Whether Muleshould discardany messagesfrom the remoteserver that havea zero contentlength. For manyservices a zerolength wouldmean there wasno data to return.If the remoteHTTP server doesreturn contentto say that thatthe request isempty, userscan configurea content filteron the endpointto filter thesemessages out.

Rest Service Component

Built-in RestServiceWrapper can be used to proxy REST style services as local Mule components.

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

Name Type Required Default Description

httpMethod GET/POST no GET The HTTP methodto use whenmaking theservice request.

serviceUrl no The service URL touse when makingthe request. Thisshould not containany parameters,since these shouldbe configured onthe component.The service URLcan contain Muleexpressions, so

Page 76: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 76

the URL can bedynamic for eachmessage request.

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

Name Cardinality Description

error-filter 0..1 An error filter can be used todetect whether the responsefrom the remote service resultedin an error.

payloadParameterName 0..* If the payload of the messageis to be attached as a URLparameter, this should be setto the parameter name. If themessage payload is an array ofobjects that multiple parameterscan be set to, use each elementin the array.

requiredParameter 0..* These are parameters that mustbe available on the currentmessage for the request to besuccessful. The Key maps tothe parameter name, the valuecan be any one of the validexpressions supported by Mule.

optionalParameter 0..* These are parameters that ifthey are on the current messagewill be added to the request,otherwise they will be ignored.The Key maps to the parametername, the value can be anyone of the valid expressionssupported by Mule.

Security

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

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

You must configure the security manager on the Mule instance against which this security filter willauthenticate. For information about security configuration options and examples, see ConfiguringSecurity.

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

Page 77: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 77

<inbound-endpoint address="user:[email protected]/secure"> <acegi:http-security-filter realm="mule-realm" /> </inbound-endpoint>

For general information about endpoint configuration, see Configuring Endpoints.

Sending Credentials

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

http://user:[email protected]/secure

Cookies

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

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

Polling HTTP Services

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

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

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

To use the connector in your endpoints, use:

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

Handling HTTP Content-Type and Encoding

Sending HTTP

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

Page 78: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 78

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

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

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

• If the Content-Type property is set on the message, send that.• Send "application/octet-stream" as Content-Type if none is set on the message.

Receiving HTTP

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

Including Custom Header Properties

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

If you do want to include HTTP headers, you can specify them as properties on the outbound endpoint asfollows:

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

Handling Redirects

To redirect an HTTP client, you must set two properties on the endpoint. First, set the http.statusproperty to '307', which instructs the client that the resource has be temporarily redirected. Alternatively,you can set the property to '301' for a permanent redirect. Second, set the Location property, whichspecifies the location where you want to redirect your client.

See the HTTP protocol specification for detailed information about status codes at http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.

Following is an example of a service that is listening on the local address http://localhost:8080/mine and will send a response with the redirection code, instructing the client to go to http://mule.mulesource.org/.

<service name="redirecter"> <inbound> <inbound-endpoint address="http://localhost:8080/mine" synchronous="true"> <property key="http.status" value="307"/> <property key="Location" value="http://mule.mulesource.org/"/> </inbound-endpoint> <inbound>

Page 79: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 79

</service>

Note that you must set the synchronous attribute to true. Otherwise, the service will be asynchronous,and a response will be immediately returned while the request is placed on an internal queue.

Getting a Hash Map of Properties

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

For example:

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

Page 80: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 80

IMAPS Transport

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

IMAPS Transport

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

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

Property Description

tls-client Configures the client key store with the followingattributes:

• path: The location (which will be resolvedrelative to the current classpath and filesystem, if possible) of the keystore thatcontains public certificates and private keysfor identification

• storePassword: The password used toprotect the keystore

• class: The type of keystore used (a Javaclass name)

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

• path: The location (which will be resolvedrelative to the current classpath and filesystem, if possible) of the trust store thatcontains public certificates of trusted servers

• storePassword: The password used toprotect the trust store

For example:

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

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

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

Page 81: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 81

IMAP Transport

This page last changed on Nov 26, 2008 by jackie.wheeler.

IMAP Transport

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

The Javadoc for this provider can be found here .

IMAP Connector

The IMAP connector supports all the common connector attributes and properties and the followingadditional attributes:

Attribute Description Default Required

backupEnabled Whether to save copiesto the backup folder.

False No

backupFolder The folder wheremessages are movedfor audit purposes afterthey have been read.

No

checkFrequency Determines how often(in milliseconds) theIMAP mailbox is polledfor new messages.

60000 Yes

mailboxFolder The remote folder tocheck for email.

INBOX No

deleteReadMessages Whether to deletemessages after theyhave been downloaded.If set to false, themessages are set toSEEN.

true No

Endpoints

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

• user: the user name of the mailbox owner• password: the password of the user• host: the IP address of the IMAP server, such as www.mulesource.com, localhost, or 127.0.0.1• port: the port number of the IMAP server. If not set for the IMAPS connector, the default port is 993.

For example:

<imap:inbound-endpoint user="bob" password="password" host="localhost" port="65433" checkFrequency="3000"/>

or for IMAPS:

Page 82: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 82

<imaps:inbound-endpoint user="bob" password="password" host="localhost" port="65433" checkFrequency="3000"/>

This will log into the bob mailbox on localhost on port 65433 using password password and will checkthe mailbox for new messages every 30 seconds. You can also specify the endpoint settings using a URI,but the above syntax is easier to read.

Escape Your Credentials

If you use a URI-style endpoint and you include the user name and password, escape anycharacters that are illegal for URIs, such as the @ character. For example, if the user nameis [email protected], you should enter it as user%40myco.com.

Page 83: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 83

JDBC Transport

This page last changed on Mar 25, 2009 by jwheeler.

JDBC Transport

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

Introduction

The JDBC Transport allows you to send and receive messages with a database using the JDBC protocol.Common usage includes retrieving, inserting, updating, and deleting database records, as well asinvoking stored procedures (e.g., to create new tables dynamically).

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

Features

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

Feature Summary Mule Community Mule Enterprise

Inbound SELECTQueries

Retrieve recordsusing the SQL SELECTstatement configuredon inbound endpoints.

x x

Large Dataset Retrieval Enables retrievalarbitrarily largedatasets by consumingrecords in smallerbatches.

x

AcknowledgmentStatements

Supports ACK SQLstatements that updatethe source or othertable after a record isread.

x x

Basic Insert/Update/Delete Statements

Individual SQL INSERT,UPDATE, and DELETEqueries specified onoutbound endpoints.One statement isexecuted at a time.

x x

Batch Insert/Update/Delete Statements

Support for JDBC batchINSERT, UPDATE, andDELETE statements, sothat many statementscan be executedtogether.

x

Advanced JDBC-relatedTransformers

XML and CSVtransformers for easily

x

Page 84: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 84

converting to andfrom datasets in thesecommon formats.

Outbound SELECTQueries

Retrieve records usingSQL SELECT statementconfigured on outboundendpoints. Supportssynchronous querieswith dynamic runtimeparameters.

x

Stored ProcedureSupport - Basic

Ability to invoke storedprocedures. SupportsIN parameters but notOUT parameters.

x x

Stored ProcedureSupport - Advanced

Same as Basic butincludes both INand OUT parametersupport. OUTparameters can besimple data types orcursors

x

Unnamed Queries Queries thatcan be invokedprogrammaticallyfrom within servicecomponents or otherJava code. This is themost flexible option,but also requireswriting code.

x x

Flexible Data SourceConfiguration

Support forconfiguration of datasources through JNDI,XAPool, or Spring.

x x

Transactions Support fortransactions viaunderlying TransactionManager.

x x

Important Note on Namespaces

When using JDBC EE features, you will need to import the EE namespace for the JDBC transport, whichhas .com instead of .org in the URL, and the XSD name is mule-jdbc-ee.xsd instead of mule-jdbc.xsd.For example, in Mule 2.1:

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

As of Mule EE 2.2, the path is slightly different (.org instead of .com, addition of /ee in path):

<mule xmlns:jdbc="http://www.mulesource.org/schema/mule/ee/jdbc/2.2"

Page 85: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 85

xsi:schemaLocation="http://www.mulesource.org/schema/mule/ee/jdbc/2.2 http://www.mulesource.org/schema/mule/ee/jdbc/2.2/mule-jdbc-ee.xsd">

If you are not using JDBC EE features, you can use the normal CE namespace:

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

Inbound SELECT Queries

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

Here is an example:

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

In this example, the inboundSelectQuery would be invoked every 10 seconds (pollingFrequency=10000ms). Each record from the result set is converted into a Map (consisting of column/value pairs), and thispayload is sent to the VM endpoint shown above.

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

Page 86: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 86

Large Dataset Retrieval

Overview

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

When To Use It

• When the dataset to be retrieved is large enough to overwhelm memory and connection resources.• When preserving the order of messages is important.• When resumable processing is desired (that is, retrieval of the dataset can pick up where it left off,

even after service interruption).• When load balancing the data retrieval among clustered Mule nodes.

How It Works

Large dataset retrieval does not use conventional inbound SELECT queries to retrieve data. Instead, ituses a Batch Manager component to compute ID ranges for the next batch of records to be retrieved. Anoutbound SELECT query uses this range to actually fetch the records. The Batch Manager also controlsbatch processing flow to make sure that it does not process the next batch until the previous batch hasfinished processing.

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

Important Limitations

Large dataset retrieval requires that:

1. The source data contains a unique, sequential numeric ID. Records should also be fetched inascending order with respect to this ID.

2. There are no large gaps in these IDs (no larger than the configured batch size).

In Combination with Batch Inserts

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

Acknowledgment (ACK) Statements

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

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

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

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

</jdbc:connector>

Page 87: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 87

...

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

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

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

Basic Insert/Update/Delete Statements

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

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

For example, when a message with a java.util.Map payload is sent to a basic insert/update/deleteendpoint, the parameters in the statement are bound with corresponding entries in the Map. In theconfiguration below, if the message contains a Map payload with {ID=1,TYPE=1,DATA=hello,ACK=0}, thefollowing insert will be issued: "INSERT INTO TEST (ID,TYPE,DATA,ACK) values (1,1,'hello',0)".

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

Batch Insert/Update/Delete Statements

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

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

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

Page 88: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 88

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

Advanced JDBC-related Transformers

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

XML-JDBC Transformer

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

Transformer Details:

Name Class Input Output

XML -> Maps org.mule.providers.jdbc.transformers.XMLToMapsTransformerjava.lang.String (XML) java.util.List(List of Maps. EachMap corresponds to a"record" in the XML.)

Maps -> XML org.mule.providers.jdbc.transformers.MapsToXMLTransformerjava.util.List(List of Maps. Each Mapwill be converted into a"record" in the XML)

java.lang.String (XML)

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

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

Here is an example of a valid XML instance:

Page 89: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 89

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

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

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

CSV-JDBC Transformer

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

Transformer Details:

Name Class Input Output

CSV -> Maps org.mule.providers.jdbc.transformers.CSVToMapsTransformerjava.lang.String(CSV data)

java.util.List(List of Maps. EachMap corresponds to a"record" in the CSV)

Maps -> CSV org.mule.providers.jdbc.transformers.MapsToCSVTransformerjava.util.List(List of Maps. Each Mapwill be converted into a"record" in the CSV)

java.lang.String(CSV data)

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

Property Description

delimiter The delimiter character used in the CSV file.Defaults to comma.

qualifier The qualifier character used in the CSV file.Used to signify if text contains the delimitercharacter.Defaults to double quote.

ignoreFirstRecord Instructs transformer to ignore the first record.Defaults to false.

mappingFile Location of Mapping file. Required. Can eitherbe physical file location or classpath resourcename. The DTD format of the Mapping File canbe found at: http://flatpack.sourceforge.net/flatpack.dtd. For examples of this format, seehttp://flatpack.sourceforge.net/documentation/index.html.

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

Page 90: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 90

Outbound SELECT Queries

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

1. Support synchronous invocation of queries. For example, you can implement the classic use case ofa web page that serves content from a database using an HTTP inbound endpoint and an outboundSELECT query endpoint.

2. Allows parameters so that values can be bound to the query at runtime. This requires that themessage contain a Map payload containing key names that match the parameter names. Forexample, the following configuration could be used to retrieve an outbound SELECT query:

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

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

key=IDvalue=3

The following query is executed:

SELECT * FROM mule_source WHERE ID between 0 and 3

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

Stored Procedure Support - Basic

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

<jdbc:connector name="jdbcConnector" pollingFrequency="10000" dataSource-ref="jdbcDataSource"> <jdbc:query key="storedProc" value="CALL addField()"/>

Page 91: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 91

</jdbc:connector>

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

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

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

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

If you do not want to poll the database, you can write a stored procedure that uses HTTPto start a Mule service. The stored procedure can be called from an Oracle trigger. If youtake this approach, make sure the Mule service is asynchronous. Otherwise, the trigger/transaction won't commit until the HTTP post returns.

Stored Procedure Support - Advanced

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

OUT Parameters

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

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

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

See Example #3 for more examples.

Oracle Cursor Support

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

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

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

Page 92: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 92

<jdbc:connector name="jdbcConnector" pollingFrequency="1000" cursorTypeConstant="-10" dataSource-ref="jdbcDataSource"> <jdbc:query key="SingleCursor" value="call TEST_CURSOR(#[mules;resultSet;out])"/></jdbc:connector> <custom-transformer class="org.mule.transformer.simple.MapLookup" name="MapLookup"> <spring:property name="key" value="mules"/> </custom-transformer> <jdbc:resultset-to-maps-transformer name="ResultSet2Maps"/> <model name="SPModel"> <service name="cursorOutputAsMaps"> <inbound> <vm:inbound-endpoint path="returns.maps" responseTransformer-refs="MapLookup ResultSet2Maps"/> </inbound> <outbound> <pass-through-router> <jdbc:outbound-endpoint queryKey="SingleCursor"/> </pass-through-router> </outbound> </service> <service name="cursorOutputAsResultSet"> <inbound> <vm:inbound-endpoint path="returns.resultset" responseTransformer-refs="MapLookup"/> </inbound> <outbound> <pass-through-router> <jdbc:outbound-endpoint queryKey="SingleCursor"/> </pass-through-router> </outbound> </service> </model>

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

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

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

Unnamed Queries

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

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

Page 93: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 93

Flexible Data Source Configuration

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

<jdbc:connector name="jdbcConnector" pollingFrequency="10000" dataSource-ref="myDataSource"> ...</jdbc:connector>

You can also create a JDBC connection pool so that you don't create a new connection to the database foreach message. You can easily create a pooled data source in Spring using xapool. The following exampleshows how to create the Spring bean right in the Mule configuration file.

<spring:bean id="pooledDS" class="org.enhydra.jdbc.standard.StandardDataSource" destroy-method="shutdown"> <spring:property name="driverName" value="oracle.jdbc.driver.OracleDriver"/> <spring:property name="url" value="jdbc:oracle:thin:user/pass@host:1521:db"/></spring:bean>

If you need more control over the configuration of the pool, you can use the standard JDBC classes. Forexample, you could create the following beans in the Spring configuration file (you could also create themin the Mule configuration file by prefixing everything with the Spring namespace):

//create the data source that will establish the connection <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/> <property name="url" value="jdbc:oracle:thin:@mydb:1521:orcl"/> <property name="username" value="my_user"/> <property name="password" value="xyz123"/> </bean>

//create the pool

<bean id="pool" class="org.apache.commons.pool.impl.GenericObjectPool"> <property name="minEvictableIdleTimeMillis" value="300000" /> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <property name="maxActive" value="256"/> <property name="maxIdle" value="100"/> <property name="whenExhaustedAction" value="2"/> </bean>

//create a connection factory for the data source <bean id="dsConnectionFactory" class="org.apache.commons.dbcp.DataSourceConnectionFactory"> <constructor-arg><ref bean="dataSource"/></constructor-arg> </bean>

//create a poolable connection factory based on the above pool and connection factory <bean id="poolableConnectionFactory" class="org.apache.commons.dbcp.PoolableConnectionFactory"> <constructor-arg index="0"><ref bean="dsConnectionFactory"/></constructor-arg> <constructor-arg index="1"><ref bean="pool"/></constructor-arg> <constructor-arg index="2"><null/></constructor-arg> <constructor-arg index="3"><null/></constructor-arg> <constructor-arg index="4"><value>false</value></constructor-arg> <constructor-arg index="5"><value>true</value></constructor-arg> </bean>

//create pooling data source based on the poolable connection factory and pool

Page 94: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 94

<bean id="pooledDS" class="org.apache.commons.dbcp.PoolingDataSource" depends-on="poolableConnectionFactory"> <constructor-arg><ref bean="pool"/></constructor-arg> </bean>

You could then reference the pooledDS bean in your Mule configuration:

<jdbc:connector name="jdbcConnector" dataSource-ref="pooledDS"/>

To retrieve the data source from a JNDI repository, you would configure the connector as follows:

<spring:beans> <jee:jndi-lookup id="myDataSource" jndi-name="yourJndiName" environment-ref="yourJndiEnv" /> <util:map id="jndiEnv"> <spring:entry key="java.naming.factory.initial" value="yourJndiFactory" /> </util:map></spring:beans>

The above example shows how to create the Spring beans right in the Mule configuration file. Thisapproach would require the following namespaces:

<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.mulesource.org/schema/mule/jdbc/2.2" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/jdbc/2.2 http://www.mulesource.org/schema/mule/jdbc/2.2/mule-jdbc.xsd">

Transactions

Transactions are supported on JDBC Endpoints. See Transaction Management for details.

API Documentation and Notes

Connector Properties

You can set the following properties on the JDBC connector.

Property Description Default Required

Page 95: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 95

dataSource-ref Reference to theJDBC data sourceto use. When usingXA transactions, anXADataSource objectmust be provided.

Yes

pollingFrequency The delay inmilliseconds that willbe used during twosubsequent polls to thedatabase

No

resultSetHandler-ref Reference toResultSetHandler usedto pass back queryresults. For moreinformation aboutthis object, see theexamples.

org.apache.commons.dbutils.handlers.MapListHandler

No

queryRunner-ref Reference to theQueryRunner to usewhen executing aQuery. For moreinformation aboutthis object, see theexamples.

org.apache.commons.dbutils.QueryRunner

no

transactionPerMessage Whether each databaserecord should bereceived in a separatetransaction. If false,there will be a singletransaction for theentire result set.

true No

Extending the SQL Strategy

As of Mule 2.2, you can use the <sqlStatementStrategyFactory> child element to override the defaultSqlStatementStrategyFactory using the class or ref attribute. It determines the execution strategybased on the SQL provided. For example:

<jdbc:connector name="jdbcConnector4" dataSource-ref="testDS2"> <jdbc:sqlStatementStrategyFactory class="org.mule.transport.jdbc.config.JdbcNamespaceHandlerTestCase$TestSqlStatementStrategyFactory"/></jdbc:connector>

<jdbc:connector name="jdbcConnector5" dataSource-ref="testDS2"> <jdbc:sqlStatementStrategyFactory ref="sqlStatementStrategyFactory"/></jdbc:connector>

Notes on Configuring Queries

SQL queries are used by endpoints and should be configured on the connector using the "query" element:

Page 96: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 96

<jdbc:query key="myQuery" value="select * from blah"/>

The queries can be parameterized using the #[...] pattern that follows the Expression EvaluationFramework.

Runnable Examples

For examples of using the Mule Enterprise version of the JDBC transport, see JDBC Transport Examples.

Performance Results

For information on performance testing on the Mule Enterprise version of the JDBC transport, see JDBCTransport Performance Benchmark Results.

Page 97: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 97

JDBC Transport Examples

This page last changed on Feb 24, 2009 by jackie.wheeler.

JDBC Transport Examples

This page describes the examples you can run for the Mule Enterprise JDBC transport. These examplesare designed to work with Oracle databases only.

Setup

The Mule Enterprise JDBC Examples are located in your installation at $MULE_HOME/examples/jdbc.

1. Before running any examples, do the following:

• Run the statements in scripts/tables.ddl to create tables in your favorite database.• Edit the conf/db.properties file with your database connection configuration.• Copy your database driver to your $MULE_HOME/lib/user directory.

2. Run the examples using the "jdbc.bat" or "jdbc" shell script provided in this directory. After running thescript, you will see the following:

$ ./jdbc.batExamples require that you set up your database first. See README for more details.After your database is set up, choose one of the following examples to run:1. Mules are born. Read in 50 baby mules from a CSV File and create records in mule_source table.2. View Mules. Generate an XML report of Mules. (http://localhost:8080/first20)3. Clone Mules. Clone mules using a Stored Procedure. (http://localhost:8080/clone)4. Retire Mules. Send mules to a retirement ranch (a.k.a the mule_target table).5. Cleanup Mules. Reset tables to run examples again (http://localhost:8080/cleanup).Select the one you wish to execute and press Enter...

3. Choose the number of the Example you want to run.

The examples are designed to be run in order.

Example 1 - Mules Are Born

This example loads records from a CSV file to the database. The CSV file ("data/mules.csv") containsinformation about 50 baby mules born at various local ranches. The goal is to upload these records into adatabase table called "mule_source".

Configuration

See conf/jdbc-csv.xml

Features Used

This example uses the CSV Transformer to convert the CSV file into JDBC-format Maps and inserts theserecords into the database using a batch INSERT.

Running the Example

To run the example, choose option "1" after starting the Mule server. When the server starts, Mule willimmediately load all the records.

To verify that the example loaded correctly, use your favorite database tool to see that there were 50records inserted into the mule_source table.

SQL> select count(1) from mule_source;

Page 98: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 98

COUNT(1)----------50

If you want to run the example again, first delete the records from mule_source.

Example 2 - See the Baby Mules

This example displays the mule records loaded into the database in Example 1.

Configuration

See conf/jdbc-xml-report.xml

Features Used

This example uses an outbound SELECT query to synchronously query the database. The results aretransformed into XML using the XML transformer.

Running the Example

Start the Mule server and choose Example 2. Then, enter the URL http://localhost:8080/first20 into yourweb browser. You should see the first 20 mule records presented in XML format.

Example 3 - Mule Cloning

The following example assumes that you are using an Oracle database. However, you canadapt the stored procedure for other database platforms.

This example shows how to invoke a stored procedure in Mule. This particular stored procedure clonesthe records in the mule_source database (doubling the size of the table each time it is run). The goal is tocreate a large dataset that we can use in Example 4.

Configuration

See conf/jdbc-stored-procedure.xml

Features Used

This page uses an outbound SELECT query and stored procedure support to synchronously call a storedprocedure.

Running the Example

Before running this example, run the statements in the scripts/oracle_procs.ddl to create the storedprocedure and sequence.

Start the Mule server and choose Example 3. Then, enter the URL http://localhost:8080/clone intoyour web browser. You should see the current count of the number of mules in mule_source. Each timeyou refresh the page, the number of mules should double. Try refreshing several times until there arethousands or even millions of mules or more in the table. The mules multiply quickly!

Example 4 - Mass Mule Retirement

This example retires all our mules by transferring them from one database table (mule_source) toanother (mule_target). We can think of this as a simple ETL use case.

Page 99: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 99

Configuration

See conf/jdbc-etl.xml

Features Used

This page uses large dataset retrieval, an outbound SELECT query, and batch INSERT statements totransfer arbitrarily large numbers of records from one table another.

Running the Example

Before running this example, you can optionally change the location of the ID store in jdbc-etl.xml:

<spring:bean id="idStore" class="org.mule.transport.jdbc.util.IdStore"> <spring:property name="fileName" value="/tmp/eg-batches.txt"/> </spring:bean>

The default location is /tmp/eg-batches.txt on Linux/Unix and c:/tmp/eg-batches.txt on Windows.

Next, for better visibility into batch activity, add the following line to your log4j.properties file (in$MULE_HOME/conf):

log4j.logger.org.mule.providers.jdbc.components=DEBUG

Finally, start the server and choose Example 4. You should see the batches of records being processed inthe logs:

DEBUG 2008-04-10 20:20:03,625 \[next_batch.2\] org.mule.transport.jdbc.components.BatchManager: Processing next batchDEBUG 2008-04-10 20:20:03,625 \[next_batch.2\] org.mule.transport.jdbc.components.BatchManager: Next range: {lowerId=1, upperId=3000}DEBUG 2008-04-10 20:20:04,531 \[next_batch.2\] org.mule.transport.jdbc.components.BatchManager: Processing next batchDEBUG 2008-04-10 20:20:04,531 \[next_batch.2\] org.mule.transport.jdbc.components.BatchManager: Next range: {lowerId=3001, upperId=6000}DEBUG 2008-04-10 20:20:05,531 \[next_batch.2\] org.mule.transport.jdbc.components.BatchManager: Processing next batchDEBUG 2008-04-10 20:20:05,531 \[next_batch.2\] org.mule.transport.jdbc.components.BatchManager: Next range: {lowerId=6001, upperId=9000}

In this example, batches are configured to occur every 1 second, with a batch size of 3000.

Note that if you stop and restart the Mule server, the batches should resume processing where they leftoff.

Re-running the Examples

If you want to run these examples again, just delete all records from both mule_source and mule_targettables, and remove the file "/tmp/eg-batches.txt". In Oracle, this may be most efficiently done by usingtruncate, e.g. truncate table mule_source.

Alternatively, if on Oracle, start the server choose "Example 5" to cleanup the tables mule_source andmule_target. You still need to manually remove the file "/tmp/eg-batches.txt".

Page 100: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 100

JDBC Transport Performance Benchmark Results

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

JDBC Transport Performance BenchmarkResults

This page describes the performance benchmark results for the Mule Enterprise JDBC transport.

Configuration

Mule Enterprise 1.6 (default 512mb max heap size)

JDK 1.5.0.11

OS Red Hat Enterprise 4.0

Mule CPUs 4-CPU Dell

Database Oracle 10g (separate 4-CPU host)

Mule Configuration See Examples in $MULE_HOME/examples/jdbc.Used "Simple ETL" use case for this benchmark

Scenario Details

The ETL use case from the Examples directory was used for this benchmark. This example retrievesrecords from a table called mule_source and inserts them into a table called mule_target.

The scenario involves processing a backlog of 10 million records in the mule_source table. Records areread from the source table once every 1 second, at a batch size of 3000 records per read and 3000records per commit.

Results

Mule took 55 minutes to complete processing of the 10 million record backlog. Therefore, with thisconfiguration, the Mule Enterprise JDBC Transport could move over 10 million records an hour.

Comparison to Mule Community Edition

Page 101: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 101

Page 102: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 102

Jetty Transport

This page last changed on Feb 20, 2009 by jackie.wheeler.

Jetty Transport

[ Connector ] [ Endpoints ] [ Using Web Services over Jetty ]

The Jetty transport provides support for exposing services over HTTP by embedding a light-weight Jettyserver. The Jetty SSL transport works the same way but over SSL. You can only define inbound endpointswith this transport.

The Javadoc for this transport can be found here .

Connector

Allows Mule to expose Mule Services over HTTP using a Jetty HTTP server. A single Jetty server is createdfor each connector instance. One connector can serve many endpoints. Users should rarely need to havemore than one Jetty connector. The Jetty connector can be configured using a Jetty XML config file, butthe default configuration is sufficient for most scenarios.

Attributes of <connector...>

Name Type Required Default Description

configFile string no The location of theJetty config fileto configure thisconnector with.

useContinuations boolean no Whether to usecontinuationsto free upconnectionsin high loadsituations.

For example:

<?xml version="1.0" encoding="UTF-8" ?> <mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jetty="http://www.mulesource.org/schema/mule/jetty/2.2" xsi:schemaLocation="http://www.mulesource.org/schema/mule/jetty/2.2 http://www.mulesource.org/schema/mule/jetty/2.2/mule-jetty.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd"> <jetty:connector name="httpConnector" useContinuations="true" /> ...

Endpoints

Jetty endpoints are configured the same way as HTTP endpoints. Note that only inbound endpoints canuse the Jetty transport.

For example:

Page 103: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 103

<jetty:endpoint name="serverEndpoint" host="localhost" port="60203" path="services/Foo" synchronous="false" /> <model name="main"> <service name="testComponent"> <inbound> <inbound-endpoint ref="serverEndpoint" /> </inbound> <test:component appendString="Received" /> </service></model>

Using Web Services over Jetty

Mule supports using web services over Jetty. This allows you to achieve improved HTTP performance andscalability due to Jetty's NIO support.

Using the Jetty transport simply requires that you use the "jetty://" URL scheme as opposed to theregular HTTP scheme. For example:

<service name="greeterService"> <inbound> <cxf:inbound-endpoint address="jetty://localhost:63081/services/greeter" synchronous="true" /> </inbound> <component> <singleton-object class="org.apache.hello_world_soap_http.GreeterImpl"/> </component></service>

Due to limitations of the CXF and HTTP transports, if you are talking to outbound endpointsthat do not use a CXF client underneath and are of the form "cxf:http://locahost/service?method=echo", this will not work. We hope to address this during a future refactoring ofthe HTTP transport.

Page 104: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 104

Jetty SSL transport

This page last changed on Feb 20, 2009 by jackie.wheeler.

Jetty SSL Transport

The Jetty SSL transport works exactly the same way as the HTTPS Transport with one additional optionalattribute, configFile, which allows you to specify the location of the Jetty config file to configure thisconnector with.

For example, the following configuration specifies the HTTPS and Jetty-SSL connectors:

<?xml version="1.0" encoding="UTF-8" ?> <mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:https="http://www.mulesource.org/schema/mule/https/2.2" xmlns:jetty="http://www.mulesource.org/schema/mule/jetty-ssl/2.2" xmlns:test="http://www.mulesource.org/schema/mule/test/2.0" xsi:schemaLocation="http://www.mulesource.org/schema/mule/test/2.2 http://www.mulesource.org/schema/mule/test/2.0/mule-test.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/https/2.2 http://www.mulesource.org/schema/mule/https/2.2/mule-https.xsd http://www.mulesource.org/schema/mule/jetty-ssl/2.2 http://www.mulesource.org/schema/mule/jetty-ssl/2.2/mule-jetty-ssl.xsd"> <https:connector name="httpConnector"> <https:tls-client path="clientKeystore" storePassword="mulepassword" /> <https:tls-key-store path="serverKeystore" keyPassword="mulepassword" storePassword="mulepassword" /> <https:tls-server path="trustStore" storePassword="mulepassword" /> </https:connector> <jetty:connector name="jettyConnector"> <jetty:tls-client path="clientKeystore" storePassword="mulepassword" /> <jetty:tls-key-store path="serverKeystore" keyPassword="mulepassword" storePassword="mulepassword" /> <jetty:tls-server path="trustStore" storePassword="mulepassword" /> </jetty:connector> <https:endpoint name="clientEndpoint" host="localhost" port="60202" synchronous="true" connector-ref="httpConnector" /> <model name="main"> <custom-service name="testComponent" class="org.mule.tck.testmodels.mule.TestSedaService"> <inbound> <jetty:inbound-endpoint host="localhost" port="60202" synchronous="true" connector-ref="jettyConnector" /> </inbound> <test:component appendString="Received" /> </custom-service> </model></mule>

If you do not need this level of security, you can use the Jetty Transport instead.

Page 105: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 105

JMS Transport

This page last changed on Mar 19, 2009 by jackie.wheeler.

JMS Transport

Table of Contents

Click here to expand...

• JMS Transport• ° JMS Configuration

° - Using Topics, Queues, or Both- Specifying Credentials- Specifying Additional Information- JMS Selectors- Durable Subscribers- Overloading JMS Behavior- Looking Up JMS Objects from JNDI- JMS Transformers- JMS Header Properties

° Configuring Specific JMS Servers° Schema Reference° Connector° - Attributes of <connector...>° Custom Connector° - Attributes of <custom-connector...>° Activemq Connector° - Attributes of <activemq-connector...>° Activemq Xa Connector° - Attributes of <activemq-xa-connector...>° Weblogic Connector° - Attributes of <weblogic-connector...>° Transaction° Client Ack Transaction° Jmsmessage To Object Transformer° Object To Jmsmessage Transformer° Inbound Endpoint° - Attributes of <inbound-endpoint...>° Outbound Endpoint° - Attributes of <outbound-endpoint...>° Endpoint° - Attributes of <endpoint...>° Property Filter° - Attributes of <property-filter...>

This page describes the JMS transport, which provides a standard JMS 1.0.2b and 1.1 connector. Thisconnector exposes all features defined in the 1.0.2b/1.1 specification. It also provides links to informationon configuring various types of JMS, such as ActiveMQ. Note that if you are using Oracle AQ, you can usethe JMS transport without any special configuration if you are using Oracle 10 or later. For details, see theexample on the Mule Cookbook.

For information on managing JMS local and distributed (XA) transactions, as well as multi-resourcetransactions (for Mule Enterprise Edition users), see Transaction Management.

Additionally, the Error Handler Example and Loan Broker Example demonstrate using the Active MQconnector and various JMS transformers.

The Javadoc for the JMS transport can be found here .

Page 106: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 106

JMS Configuration

This section provides general information about JMS configuration with Mule. For links to information onspecific JMS servers, see Configuring Specific JMS Servers below.

Using Topics, Queues, or Both

When specifying a destination name in a URI, and JNDI destinations are not being used, the defaultdestination created is a queue. For example, the following JMS endpoint will manifest itself as a JMSqueue called my.destination.

jms://my.destination

To make this destination a topic instead of a queue, you must prepend the destination name withtopic: in the URI. In transport-specific endpoints, you set the topic and queue attributes explicitly. Forexample:

jms://topic:my.destination

or

<jms:inbound-endpoint topic="my.destination"/><jms:outbound-endpoint queue="my.destination"/>

Note that topics are not officially supported with Mule and WebSphere MQ.

If you are using a JMS 1.1 compliant server, you can use the same JMS connector for both queuesand topics. If you are using a JMS 1.0.2b server, and you want to use both queues and topics in yourMule configuration, you must create two JMS connectors: one with a JNDI connection factory thatreferences a QueueConnectionFactory, and another that references a TopicConnectionfactory. EachJMS endpoint must reference the correct connector depending on whether the destination is a topic or aqueue. To specify the connector on a JMS endpoint, you add the connector parameter to the URI or theconnector-ref attribute on a transport-specific endpoint:

jms://my.destination?connector=jmsQueueConnectorjms://topic:my.destination?connector=jmsTopicConnector

or

<jms:outbound-endpoint queue="my.destination" connector-ref="jmsQueueConnector"/><jms:inbound-endpoint topic="my.destination" connector-ref="jmsTopicConnector"/>

Specifying Credentials

Client connections might require a username and password when creating a connection. This informationcan be specified on the URI or transport-specific endpoint as follows:

Page 107: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 107

jms://ross:secret@topic:my.destination

or

<jms:inbound-endpoint topic="my.destination" username="ross" password="secret"/>

Specifying Additional Information

When creating JMS connectors, more information is needed such as ConnectionFactory JNDI details.This information can be set as parameters on the URI, but this can get difficult to manage and read.The recommend approach is to set default properties on the connector as described in Looking Up JMSObjects from JNDI below.

JMS Selectors

You can set a JMS selector as a filter on an endpoint. The JMS selector simply sets the filter expression onthe consumer.

<jms:endpoint queue="important.queue" connector-ref="..."> <jms:selector expression="JMSPriority=9"/></jms:endpoint>

Durable Subscribers

You can use durable subscribers by setting the durable attribute on the JMS connector. This attributetells the connector to make all topic subscribers durable (it does not apply to queues). You can overridethe connector's durable attribute at the endpoint level. For example, you can set durable to false on theconnector and set it to true just on the endpoints that require it.

<jms:connector name="jmsTopicConnector" durable="false"/>...<jms:inbound-endpoint topic=durable.topic" connector-ref="jmsTopicConnector"> <property key="durable" value="true"/></endpoint>

When using a durable subscription, the JMS server requires a durable name to identify this subscriber. Bydefault, Mule generates the durable name in the following format:

mule.<connector name>.<topic name>

If you want to set the durable name yourself, you can set the durableName property on the endpoint.

<jms:inbound-endpoint topic="durable.topic" connector-ref="jmsTopicConnector"> <property key="durable" value="true"/> <property key="durableName" value="myDurableSubscription"/></jms:inbound-endpoint>

The URI equivalent would be:

Page 108: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 108

jms://topic:durable.topic?durableName=myDurableSubscription

Overloading JMS Behavior

Some JMS servers require a different sequence of calls when creating JMS resources. For example,Oracle's Advanced Queuingrequires that the connection is started before listeners can be registered.In this scenario the user can overload the JmsSupport class to customize the way JMS resources areinitialized. Configuring this customization requires that you tell the JMS connector to use a customJmsSupport class.

<spring:bean id="customJmsSupport" class="org.foo.jms.CustomJmsSupport"/>

<jms:connector name="jmsConnector"> <property key="jmsSupport" ref="customJmsSupport"/></jms:connector>

For more information about configuring specific JMS servers, see Configuring Specific JMS Servers below.

Looking Up JMS Objects from JNDI

Mule can be configured to look up connection factories, queues, and topics from JNDI. Use the followingconnector attributes to configure your JNDI connection:

Connector Attribute Description

jndiInitialFactory Class name of the InitialContextFactory

jndiProviderUrl URL for the JNDI connection

jndiProviderProperties-ref Reference to a Spring map with additionalproperties that will be passed on when creatingthe InitialContext

connectionFactoryJndiName JNDI lookup name of the connection factory

jndiDestinations Set this flag to true to look up queues ortopics from JNDI. If a queue cannot be foundon JNDI, it well be created using the existingJMS session (you can prevent this by using theforceJndiDestinations attribute). The default isfalse.

forceJndiDestinations Set this connector property to false if you wantMule to fail if a queue or topic could not be lookedup in JNDI. The default is false.

Note that JNDI configuration on the connector takes precedence over a Spring-configured connectionfactory.

Configuration example:

<jms:connector name="jmsJndiConnector" jndiInitialFactory="com.sun.jndi.ldap.LdapCtxFactory" jndiProviderUrl="ldap://localhost:10389/" connectionFactoryJndiName="cn=ConnectionFactory,dc=example,dc=com" jndiDestinations="true"

Page 109: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 109

forceJndiDestinations="true"/>

JMS Transformers

Transformers for the JMS provider can be found at org.mule.transport.jms.transformers .

Transformer Description

AbstractJmsTransformer This is a base class that provides general JMSmessage transformation support. You canextend this class to create your own specializedJMS transformers, but usually the defaults aresufficient.

JMSMessageToObject Converts a javax.jms.Message or sub-type intoan object by extracting the message payload.Users of this transformer can set different returntypes on the transformer to control the way itbehaves:javax.jms.TextMessage - java.lang.Stringjavax.jms.ObjectMessage - java.lang.Objectjavax.jms.BytesMessage - Byte[]. Note thatthe transformer will check if the payload iscompressed and automatically decompress themessage.javax.jms.MapMessage - java.util.Mapjavax.jms.StreamMessage - java.util.Vector ofobjects from the Stream Message.

ObjectToJMSMessage Converts any object to a javax.jms.Messageor sub-type. One of the following types of JMSmessages will be created based on the type ofobject passed in:java.lang.String - javax.jms.TextMessagebyte[] - javax.jms.BytesMessagejava.util.Map - javax.jms.MapMessagejava.io.InputStream - javax.jms.StreamMessagejavalang.Object - javax.jms.ObjectMessage

JMS Header Properties

When the message is received and transformed, all the message properties are still available via theMuleMessage object. To access standard JMS properties such as JMSCorrelationID and JMSRedelivered,simply use the property name, as shown in the following example:

String corrId = (String) muleMessage.getProperty("JMSCorrelationID");boolean redelivered = muleMessage.getBooleanProperty("JMSRedelivered");

You can access any custom header properties on the message in the same way.

Configuring Specific JMS Servers

The following links describe how to set up various JMS servers in Mule. Note that the configurationsprovided are just examples. Configuration values will change depending on your application environment.

• ActiveMQ

Page 110: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 110

• FioranoMQ• JBoss MQ• OpenJms• Open MQ• Oracle AQ• SeeBeyond• SonicMQ• Sun JMS Grid• SwiftMQ• Tibco EMS• WebLogic JMS

Additionally, if you are using Mule Enterprise Edition, you can use the Mule WMQ Transport to integratewith WebSphere MQ.

Schema Reference

Connector

The connector element configures a generic connector for sending and receiving messages over JMSqueues.

Attributes of <connector...>

Name Type Required Default Description

connectionFactory-ref

name (no spaces) no Reference tothe connectionfactory, whichis required fornon-vendor JMSconfigurations.

redeliveryHandlerFactory-ref

name (no spaces) no Reference to theredelivery handler.

acknowledgementModeAUTO_ACKNOWLEDGE/CLIENT_ACKNOWLEDGE/DUPS_OK_ACKNOWLEDGE

no AUTO_ACKNOWLEDGETheacknowledgementmode to use:AUTO_ACKNOWLEDGE,CLIENT_ACKNOWLEDGE,orDUPS_OK_ACKNOWLEDGE.

clientId string no The ID of the JMSclient.

durable boolean no Whether tomake all topicsubscribersdurable.

noLocal boolean no If set to true,a subscriberwill not receivemessages thatwere publishedby its ownconnection.

Page 111: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 111

persistentDelivery boolean no If set to true, theJMS provider logsthe message tostable storage asit is sent so that itcan be recoveredif delivery isunsuccessful.A client marksa message aspersistent if itfeels that theapplication willhave problemsif the messageis lost in transit.A client marksa message asnon-persistentif an occasionallost message istolerable. Clientsuse deliverymode to tell aJMS providerhow to balancemessage transportreliability/throughput.Delivery modeonly covers thetransport ofthe message toits destination.Retention of amessage at thedestination untilits receipt isacknowledged isnot guaranteedby a PERSISTENTdelivery mode.Clients shouldassume thatmessage retentionpolicies are setadministratively.Message retentionpolicy governsthe reliability ofmessage deliveryfrom destinationto messageconsumer. Forexample, if aclient's messagestorage spaceis exhausted,some messages asdefined by a sitespecific messageretention policymay be dropped.

Page 112: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 112

A message isguaranteed to bedelivered once-and-only-once bya JMS Provider ifthe delivery modeof the messge ispersistent and ifthe destinationhas a sufficientmessage retentionpolicy.

honorQosHeaders boolean no If set to true,the message'sQoS headers arehonored. If false(the default), theconnector settingsoverride themessage headers.

maxRedelivery integer no The maximumnumber of timesto try to redelivera message.

cacheJmsSessions boolean no Whether to cacheand re-use theJMS sessionobject insteadof recreating theconnection eachtime.

eagerConsumer boolean no Whether to createa consumerright when theconnection iscreated insteadof using lazyinstantiation in thepoll loop.

specification 1.0.2b/1.1 no 1.0.2b The JMSspecification touse: 1.0.2b (thedefault) or 1.1

username string no The user name forthe connection

password string no The password forthe connection

numberOfConsumersinteger no The numberof concurrentconsumers thatwill be usedto receive JMSmessages.(Note: If you usethis attribute,you should not

Page 113: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 113

configure the'numberOfConcurrentTransactedReceivers',which has thesame effect.)

jndiInitialFactory string no The initial factoryclass to use whenconnecting toJNDI.

jndiProviderUrl string no The URL to usewhen connectingto JNDI.

jndiProviderProperties-ref

string no Reference to aMap that containsadditional providerproperties.

connectionFactoryJndiNamestring no The name to usewhen looking upthe connectionfactory from JNDI.

jndiDestinations boolean no Set this attributeto true if you wantto look up queuesor topics fromJNDI instead ofcreating themfrom the session.

forceJndiDestinationsboolean no If set to true, Mulefails when a topicor queue cannotbe retrieved fromJNDI. If set tofalse, Mule willcreate a topic orqueue from theJMS session if theJNDI lookup fails.

disableTemporaryReplyToDestinationsboolean no If this is setto false (thedefault), whenMule performsrequest/responsecalls a temporarydestination willautomatically beset up to receive aresponse from theremote JMS call.

Custom Connector

The custom-connector element configures a custom connector for sending and receiving messages overJMS queues.

Page 114: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 114

Attributes of <custom-connector...>

Name Type Required Default Description

redeliveryHandlerFactory-ref

name (no spaces) no Reference to theredelivery handler.

acknowledgementModeAUTO_ACKNOWLEDGE/CLIENT_ACKNOWLEDGE/DUPS_OK_ACKNOWLEDGE

no AUTO_ACKNOWLEDGETheacknowledgementmode to use:AUTO_ACKNOWLEDGE,CLIENT_ACKNOWLEDGE,orDUPS_OK_ACKNOWLEDGE.

clientId string no The ID of the JMSclient.

durable boolean no Whether tomake all topicsubscribersdurable.

noLocal boolean no If set to true,a subscriberwill not receivemessages thatwere publishedby its ownconnection.

persistentDelivery boolean no If set to true, theJMS provider logsthe message tostable storage asit is sent so that itcan be recoveredif delivery isunsuccessful.A client marksa message aspersistent if itfeels that theapplication willhave problemsif the messageis lost in transit.A client marksa message asnon-persistentif an occasionallost message istolerable. Clientsuse deliverymode to tell aJMS providerhow to balancemessage transportreliability/throughput.Delivery modeonly covers the

Page 115: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 115

transport ofthe message toits destination.Retention of amessage at thedestination untilits receipt isacknowledged isnot guaranteedby a PERSISTENTdelivery mode.Clients shouldassume thatmessage retentionpolicies are setadministratively.Message retentionpolicy governsthe reliability ofmessage deliveryfrom destinationto messageconsumer. Forexample, if aclient's messagestorage spaceis exhausted,some messages asdefined by a sitespecific messageretention policymay be dropped.A message isguaranteed to bedelivered once-and-only-once bya JMS Provider ifthe delivery modeof the messge ispersistent and ifthe destinationhas a sufficientmessage retentionpolicy.

honorQosHeaders boolean no If set to true,the message'sQoS headers arehonored. If false(the default), theconnector settingsoverride themessage headers.

maxRedelivery integer no The maximumnumber of timesto try to redelivera message.

cacheJmsSessions boolean no Whether to cacheand re-use theJMS sessionobject insteadof recreating the

Page 116: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 116

connection eachtime.

eagerConsumer boolean no Whether to createa consumerright when theconnection iscreated insteadof using lazyinstantiation in thepoll loop.

specification 1.0.2b/1.1 no 1.0.2b The JMSspecification touse: 1.0.2b (thedefault) or 1.1

username string no The user name forthe connection

password string no The password forthe connection

numberOfConsumersinteger no The numberof concurrentconsumers thatwill be usedto receive JMSmessages.(Note: If you usethis attribute,you should notconfigure the'numberOfConcurrentTransactedReceivers',which has thesame effect.)

jndiInitialFactory string no The initial factoryclass to use whenconnecting toJNDI.

jndiProviderUrl string no The URL to usewhen connectingto JNDI.

jndiProviderProperties-ref

string no Reference to aMap that containsadditional providerproperties.

connectionFactoryJndiNamestring no The name to usewhen looking upthe connectionfactory from JNDI.

jndiDestinations boolean no Set this attributeto true if you wantto look up queuesor topics fromJNDI instead ofcreating themfrom the session.

Page 117: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 117

forceJndiDestinationsboolean no If set to true, Mulefails when a topicor queue cannotbe retrieved fromJNDI. If set tofalse, Mule willcreate a topic orqueue from theJMS session if theJNDI lookup fails.

disableTemporaryReplyToDestinationsboolean no If this is setto false (thedefault), whenMule performsrequest/responsecalls a temporarydestination willautomatically beset up to receive aresponse from theremote JMS call.

Activemq Connector

The activemq-connector element configures an ActiveMQ version of the JMS connector.

Attributes of <activemq-connector...>

Name Type Required Default Description

connectionFactory-ref

name (no spaces) no Optional referenceto the connectionfactory. A defaultconnection factoryis providedfor vendor-specific JMSconfigurations.

redeliveryHandlerFactory-ref

name (no spaces) no Reference to theredelivery handler.

acknowledgementModeAUTO_ACKNOWLEDGE/CLIENT_ACKNOWLEDGE/DUPS_OK_ACKNOWLEDGE

no AUTO_ACKNOWLEDGETheacknowledgementmode to use:AUTO_ACKNOWLEDGE,CLIENT_ACKNOWLEDGE,orDUPS_OK_ACKNOWLEDGE.

clientId string no The ID of the JMSclient.

durable boolean no Whether tomake all topicsubscribersdurable.

Page 118: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 118

noLocal boolean no If set to true,a subscriberwill not receivemessages thatwere publishedby its ownconnection.

persistentDelivery boolean no If set to true, theJMS provider logsthe message tostable storage asit is sent so that itcan be recoveredif delivery isunsuccessful.A client marksa message aspersistent if itfeels that theapplication willhave problemsif the messageis lost in transit.A client marksa message asnon-persistentif an occasionallost message istolerable. Clientsuse deliverymode to tell aJMS providerhow to balancemessage transportreliability/throughput.Delivery modeonly covers thetransport ofthe message toits destination.Retention of amessage at thedestination untilits receipt isacknowledged isnot guaranteedby a PERSISTENTdelivery mode.Clients shouldassume thatmessage retentionpolicies are setadministratively.Message retentionpolicy governsthe reliability ofmessage deliveryfrom destinationto messageconsumer. Forexample, if a

Page 119: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 119

client's messagestorage spaceis exhausted,some messages asdefined by a sitespecific messageretention policymay be dropped.A message isguaranteed to bedelivered once-and-only-once bya JMS Provider ifthe delivery modeof the messge ispersistent and ifthe destinationhas a sufficientmessage retentionpolicy.

honorQosHeaders boolean no If set to true,the message'sQoS headers arehonored. If false(the default), theconnector settingsoverride themessage headers.

maxRedelivery integer no The maximumnumber of timesto try to redelivera message.

cacheJmsSessions boolean no Whether to cacheand re-use theJMS sessionobject insteadof recreating theconnection eachtime.

eagerConsumer boolean no Whether to createa consumerright when theconnection iscreated insteadof using lazyinstantiation in thepoll loop.

specification 1.0.2b/1.1 no 1.0.2b The JMSspecification touse: 1.0.2b (thedefault) or 1.1

username string no The user name forthe connection

password string no The password forthe connection

Page 120: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 120

numberOfConsumersinteger no The numberof concurrentconsumers thatwill be usedto receive JMSmessages.(Note: If you usethis attribute,you should notconfigure the'numberOfConcurrentTransactedReceivers',which has thesame effect.)

jndiInitialFactory string no The initial factoryclass to use whenconnecting toJNDI.

jndiProviderUrl string no The URL to usewhen connectingto JNDI.

jndiProviderProperties-ref

string no Reference to aMap that containsadditional providerproperties.

connectionFactoryJndiNamestring no The name to usewhen looking upthe connectionfactory from JNDI.

jndiDestinations boolean no Set this attributeto true if you wantto look up queuesor topics fromJNDI instead ofcreating themfrom the session.

forceJndiDestinationsboolean no If set to true, Mulefails when a topicor queue cannotbe retrieved fromJNDI. If set tofalse, Mule willcreate a topic orqueue from theJMS session if theJNDI lookup fails.

disableTemporaryReplyToDestinationsboolean no If this is setto false (thedefault), whenMule performsrequest/responsecalls a temporarydestination willautomatically beset up to receive aresponse from theremote JMS call.

Page 121: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 121

brokerURL string no The URL used toconnect to theJMS server. If notset, the default isvm://localhost?broker.persistent=false&broker.useJmx=false.

Activemq Xa Connector

The activemq-xa-connector element configures an ActiveMQ version of the JMS connector with XAtransaction support.

Attributes of <activemq-xa-connector...>

Name Type Required Default Description

connectionFactory-ref

name (no spaces) no Optional referenceto the connectionfactory. A defaultconnection factoryis providedfor vendor-specific JMSconfigurations.

redeliveryHandlerFactory-ref

name (no spaces) no Reference to theredelivery handler.

acknowledgementModeAUTO_ACKNOWLEDGE/CLIENT_ACKNOWLEDGE/DUPS_OK_ACKNOWLEDGE

no AUTO_ACKNOWLEDGETheacknowledgementmode to use:AUTO_ACKNOWLEDGE,CLIENT_ACKNOWLEDGE,orDUPS_OK_ACKNOWLEDGE.

clientId string no The ID of the JMSclient.

durable boolean no Whether tomake all topicsubscribersdurable.

noLocal boolean no If set to true,a subscriberwill not receivemessages thatwere publishedby its ownconnection.

persistentDelivery boolean no If set to true, theJMS provider logsthe message tostable storage asit is sent so that itcan be recoveredif delivery isunsuccessful.

Page 122: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 122

A client marksa message aspersistent if itfeels that theapplication willhave problemsif the messageis lost in transit.A client marksa message asnon-persistentif an occasionallost message istolerable. Clientsuse deliverymode to tell aJMS providerhow to balancemessage transportreliability/throughput.Delivery modeonly covers thetransport ofthe message toits destination.Retention of amessage at thedestination untilits receipt isacknowledged isnot guaranteedby a PERSISTENTdelivery mode.Clients shouldassume thatmessage retentionpolicies are setadministratively.Message retentionpolicy governsthe reliability ofmessage deliveryfrom destinationto messageconsumer. Forexample, if aclient's messagestorage spaceis exhausted,some messages asdefined by a sitespecific messageretention policymay be dropped.A message isguaranteed to bedelivered once-and-only-once bya JMS Provider ifthe delivery modeof the messge ispersistent and ifthe destination

Page 123: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 123

has a sufficientmessage retentionpolicy.

honorQosHeaders boolean no If set to true,the message'sQoS headers arehonored. If false(the default), theconnector settingsoverride themessage headers.

maxRedelivery integer no The maximumnumber of timesto try to redelivera message.

cacheJmsSessions boolean no Whether to cacheand re-use theJMS sessionobject insteadof recreating theconnection eachtime.

eagerConsumer boolean no Whether to createa consumerright when theconnection iscreated insteadof using lazyinstantiation in thepoll loop.

specification 1.0.2b/1.1 no 1.0.2b The JMSspecification touse: 1.0.2b (thedefault) or 1.1

username string no The user name forthe connection

password string no The password forthe connection

numberOfConsumersinteger no The numberof concurrentconsumers thatwill be usedto receive JMSmessages.(Note: If you usethis attribute,you should notconfigure the'numberOfConcurrentTransactedReceivers',which has thesame effect.)

jndiInitialFactory string no The initial factoryclass to use whenconnecting toJNDI.

Page 124: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 124

jndiProviderUrl string no The URL to usewhen connectingto JNDI.

jndiProviderProperties-ref

string no Reference to aMap that containsadditional providerproperties.

connectionFactoryJndiNamestring no The name to usewhen looking upthe connectionfactory from JNDI.

jndiDestinations boolean no Set this attributeto true if you wantto look up queuesor topics fromJNDI instead ofcreating themfrom the session.

forceJndiDestinationsboolean no If set to true, Mulefails when a topicor queue cannotbe retrieved fromJNDI. If set tofalse, Mule willcreate a topic orqueue from theJMS session if theJNDI lookup fails.

disableTemporaryReplyToDestinationsboolean no If this is setto false (thedefault), whenMule performsrequest/responsecalls a temporarydestination willautomatically beset up to receive aresponse from theremote JMS call.

brokerURL string no The URL used toconnect to theJMS server. If notset, the default isvm://localhost?broker.persistent=false&broker.useJmx=false.

Weblogic Connector

The weblogic-connector element configures a WebLogic version of the JMS connector.

Attributes of <weblogic-connector...>

Name Type Required Default Description

Page 125: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 125

connectionFactory-ref

name (no spaces) no Optional referenceto the connectionfactory. A defaultconnection factoryis providedfor vendor-specific JMSconfigurations.

redeliveryHandlerFactory-ref

name (no spaces) no Reference to theredelivery handler.

acknowledgementModeAUTO_ACKNOWLEDGE/CLIENT_ACKNOWLEDGE/DUPS_OK_ACKNOWLEDGE

no AUTO_ACKNOWLEDGETheacknowledgementmode to use:AUTO_ACKNOWLEDGE,CLIENT_ACKNOWLEDGE,orDUPS_OK_ACKNOWLEDGE.

clientId string no The ID of the JMSclient.

durable boolean no Whether tomake all topicsubscribersdurable.

noLocal boolean no If set to true,a subscriberwill not receivemessages thatwere publishedby its ownconnection.

persistentDelivery boolean no If set to true, theJMS provider logsthe message tostable storage asit is sent so that itcan be recoveredif delivery isunsuccessful.A client marksa message aspersistent if itfeels that theapplication willhave problemsif the messageis lost in transit.A client marksa message asnon-persistentif an occasionallost message istolerable. Clientsuse deliverymode to tell aJMS providerhow to balancemessage transport

Page 126: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 126

reliability/throughput.Delivery modeonly covers thetransport ofthe message toits destination.Retention of amessage at thedestination untilits receipt isacknowledged isnot guaranteedby a PERSISTENTdelivery mode.Clients shouldassume thatmessage retentionpolicies are setadministratively.Message retentionpolicy governsthe reliability ofmessage deliveryfrom destinationto messageconsumer. Forexample, if aclient's messagestorage spaceis exhausted,some messages asdefined by a sitespecific messageretention policymay be dropped.A message isguaranteed to bedelivered once-and-only-once bya JMS Provider ifthe delivery modeof the messge ispersistent and ifthe destinationhas a sufficientmessage retentionpolicy.

honorQosHeaders boolean no If set to true,the message'sQoS headers arehonored. If false(the default), theconnector settingsoverride themessage headers.

maxRedelivery integer no The maximumnumber of timesto try to redelivera message.

Page 127: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 127

cacheJmsSessions boolean no Whether to cacheand re-use theJMS sessionobject insteadof recreating theconnection eachtime.

eagerConsumer boolean no Whether to createa consumerright when theconnection iscreated insteadof using lazyinstantiation in thepoll loop.

specification 1.0.2b/1.1 no 1.0.2b The JMSspecification touse: 1.0.2b (thedefault) or 1.1

username string no The user name forthe connection

password string no The password forthe connection

numberOfConsumersinteger no The numberof concurrentconsumers thatwill be usedto receive JMSmessages.(Note: If you usethis attribute,you should notconfigure the'numberOfConcurrentTransactedReceivers',which has thesame effect.)

jndiInitialFactory string no The initial factoryclass to use whenconnecting toJNDI.

jndiProviderUrl string no The URL to usewhen connectingto JNDI.

jndiProviderProperties-ref

string no Reference to aMap that containsadditional providerproperties.

connectionFactoryJndiNamestring no The name to usewhen looking upthe connectionfactory from JNDI.

jndiDestinations boolean no Set this attributeto true if you want

Page 128: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 128

to look up queuesor topics fromJNDI instead ofcreating themfrom the session.

forceJndiDestinationsboolean no If set to true, Mulefails when a topicor queue cannotbe retrieved fromJNDI. If set tofalse, Mule willcreate a topic orqueue from theJMS session if theJNDI lookup fails.

disableTemporaryReplyToDestinationsboolean no If this is setto false (thedefault), whenMule performsrequest/responsecalls a temporarydestination willautomatically beset up to receive aresponse from theremote JMS call.

Transaction

The transaction element configures a transaction. Transactions allow a series of operations to be groupedtogether so that they can be rolled back if a failure occurs. Set the action (such as ALWAYS_BEGIN orJOIN_IF_POSSIBLE) and the timeout setting for the transaction.

Client Ack Transaction

The client-ack-transaction element configures a client acknowledgment transaction, which is identicalto a transaction but with message acknowledgements. There is no notion of rollback with clientacknowledgement, but this transaction can be useful for controlling how messages are consumed from adestination.

Jmsmessage To Object Transformer

The jmsmessage-to-object-transformer element configures a transformer that converts a JMS messageinto an object by extracting the message payload.

Object To Jmsmessage Transformer

The object-to-jmsmessage-transformer element configures a transformer that converts an objectinto one of five types of JMS messages, depending on the object passed in: java.lang.String ->javax.jms.TextMessage, byte[] -> javax.jms.BytesMessage, java.util.Map -> javax.jms.MapMessage,java.io.InputStream -> javax.jms.StreamMessage, and java.lang.Object -> javax.jms.ObjectMessage.

Inbound Endpoint

The inbound-endpoint element configures an endpoint on which JMS messages are received.

Page 129: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 129

Attributes of <inbound-endpoint...>

Name Type Required Default Description

queue string no The queue name.This attributecannot be usedwith the topicattribute (the twoare exclusive).

topic string no The topic name.The "topic:" prefixwill be addedautomatically.This attributecannot be usedwith the queueattribute (the twoare exclusive).

disableTemporaryReplyToDestinationsboolean no If this is setto false (thedefault), whenMule performsrequest/responsecalls a temporarydestination willautomatically beset up to receive aresponse from theremote JMS call.

Outbound Endpoint

The inbound-endpoint element configures an endpoint to which JMS messages are sent.

Attributes of <outbound-endpoint...>

Name Type Required Default Description

queue string no The queue name.This attributecannot be usedwith the topicattribute (the twoare exclusive).

topic string no The topic name.The "topic:" prefixwill be addedautomatically.This attributecannot be usedwith the queueattribute (the twoare exclusive).

Page 130: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 130

disableTemporaryReplyToDestinationsboolean no If this is setto false (thedefault), whenMule performsrequest/responsecalls a temporarydestination willautomatically beset up to receive aresponse from theremote JMS call.

Endpoint

The endpoint element configures a global JMS endpoint definition.

Attributes of <endpoint...>

Name Type Required Default Description

queue string no The queue name.This attributecannot be usedwith the topicattribute (the twoare exclusive).

topic string no The topic name.The "topic:" prefixwill be addedautomatically.This attributecannot be usedwith the queueattribute (the twoare exclusive).

disableTemporaryReplyToDestinationsboolean no If this is setto false (thedefault), whenMule performsrequest/responsecalls a temporarydestination willautomatically beset up to receive aresponse from theremote JMS call.

Property Filter

The property-filter element configures a filter that allows you to filter messages based on a JMS property.

Attributes of <property-filter...>

Name Type Required Default Description

Page 131: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 131

propertyName string no The name of theJMS property.

propertyClass string no The class type ofthe JMS property.

expression string no The expression tosearch for in theproperty.

pattern string no The regularexpression patternto search for inthe property. Inmost cases, ifyou set both theexpression andpattern attributes,only the pattern isused.

Page 132: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 132

Mule WMQ Transport

This page last changed on Mar 24, 2009 by jwheeler.

Mule WMQ Transport

[ Setting Up the Mule WMQ Transport ] [ Using the Mule WMQ Transport ] [ Inbound Message Handling] [ Outbound Message Handling ] [ Retrieving the Connection Factory from JNDI ] [ Transformers ] [Transactions ] [ Known Limitations ] [ Configuration Reference ] [ Connector ] [ Xa Connector ] [ InboundEndpoint ] [ Outbound Endpoint ] [ Endpoint ] [ Message To Object Transformer ] [ Object To MessageTransformer ] [ Transaction ]

The Mule Enterprise transport for IBM® WebSphere® MQ (Mule WMQ transport) provides the followingfunctionality:

• Bi-directional request-response messaging between Websphere MQ and Mule JMS using native MQpoint-to-point.

• Synchronous and asynchronous request-response communications using JMSReplyTo.

This page describes how to configure and use this transport and its connector. It assumes that youalready understand how to configure and use WebSphere MQ. For complete information on WebSphereMQ, refer to the WebSphere MQ Information Center.

Note: The Mule WMQ transport is available only with Mule Enterprise Edition version 1.6 or later. If youare using Mule Community Edition and are working with JMS messages only, use the JMS Transportinstead.

Setting Up the Mule WMQ Transport

In Mule 2.x, before you can use the Mule WMQ transport, you must copy the following JARs from thejava/lib directory under your WebSphere MQ home directory into the lib/user directory under yourMule home directory:

• com.ibm.mq.jar• com.ibm.mqetclient.jar (if using remote XA transactions)• com.ibm.mq.jmqi.jar (WebSphere MQ version 7 only)• com.ibm.mqjms.jar• dhbcore.jar

Additionally, if you are using local bindings (transportType="BINDINGS_MQ"), you must set the followingenvironment variable:

export LD_LIBRARY_PATH=/opt/mqm/java/lib

Set this variable to the location of the Java library directory that shipped with the WebSphere MQ serverinstallation. For more information about the bindings types, see the WebSphere MQ documentation.

Using the Mule WMQ Transport

The following configuration example configures a service named test, which picks up messages fromthe native WebSphere MQ endpoint (wmq://REQUEST.QUEUE) and forwards them to another nativeWebSphere MQ endpoint, wmq://RESPONSE.QUEUE. All JMS semantics apply, and settings such as replyToand QoS properties are read from the message properties, or defaults are used (according to the JMSspecification).

Page 133: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 133

By default, messages sent from Mule to WebSphere MQ are sent in native format, and JMS (RFH2)headers are suppressed. This configuration is applied transparently to the configuration below by theconnector appending a parameter to the WebSphere MQ destination URI (?targetClient=1). To forceJMS behavior on the receiving WebSphere MQ (that is, to use non-native format), use the followingattribute setting in the WMQ connector declaration:

<wmq:connector name="..." ... targetClient="JMS_COMPLIANT" .../>

Note: The targetClient attribute must be set to JMS_COMPLIANT when the message payload is anobject.

Note the following additional points about the configuration:

• The wmq URI scheme for endpoints indicates that the WebSphere MQ transport should be used.• The queueManager property in the WMQ connector declaration matches the WebSphere MQ

QueueManager set up previously.• The local queues REQUEST.QUEUE and RESPONSE.QUEUE were set up previously using the runmqsc

utility. If you were running on a remote queue, you could specify the channel with the channelattribute.

<?xml version="1.0" encoding="UTF-8"?><mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:wmq="http://www.mulesource.org/schema/mule/ee/wmq/2.2" xmlns:test="http://www.mulesource.org/schema/mule/test/2.2"

xsi:schemaLocation=" http://www.mulesource.org/schema/mule/test/2.2 http://www.mulesource.org/schema/mule/test/2.2/mule-test.xsd http://www.mulesource.org/schema/mule/ee/wmq/2.2 http://www.mulesource.org/schema/mule/ee/wmq/2.2/mule-wmq-ee.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd">

<wmq:connector name="wmqConnector" hostName="winter" port="1414" queueManager="HELLO.QMGR" transportType="CLIENT_MQ_TCPIP" specification="1.1" disableTemporaryReplyToDestinations="true" username="" password="" numberOfConsumers="1"> </wmq:connector>

<model> <service name="test"> <inbound> <wmq:inbound-endpoint queue="REQUEST.QUEUE"/> </inbound> <test:component/> <outbound> <pass-through-router enableCorrelation="NEVER"> <wmq:outbound-endpoint queue="MIDDLE.QUEUE"/> </pass-through-router> </outbound>

<async-reply failOnTimeout="true" timeout="5000"> <wmq:inbound-endpoint queue="RESPONSE.QUEUE"/>

Page 134: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 134

<single-async-reply-router/> </async-reply> </service> <service name="Responder"> <inbound> <wmq:inbound-endpoint queue="MIDDLE.QUEUE"/> </inbound> </service> </model></mule>

The log output would confirm that the message was received and would indicate the content (in this case,the test component creates a simple string "Hello"). It would also specify that a reply message was sent:

...********************************************************************************* Message received in component: test. Content is: 'Hello' *********************************************************************************INFO 2009-03-10 13:59:56,487 [test.2] org.mule.transport.DefaultReplyToHandler: Reply Message sent to: queue://HELLO.QMGR/RESPONSE.QUEUE?targetClient=1

If you were running on a remote queue MYREMOTE.QUEUE, you would receive the following on thereceiving side:

[mqm@spring ~]$ /opt/mqm/samp/bin/amqsget MYREMOTE.QUEUESample AMQSGET0 startmessage <Hello>

no more messagesSample AMQSGET0 end

You can use the WebSphere MQ utility amqsget to verify that the message was received on the remotequeue.

Inbound Message Handling

The inbound messages are received by the connector and delivered to the component. If theuseRemoteQueueDefinitons connector attribute is not set to true and the inbound message type isMQMT_REQUEST, the message returned by the component will be sent to the queue specified in theJMSReplyTo property of the original message. However, if the outbound WebSphere MQ endpoint exists inthe component, it will override the replyto handler functionality. By default, useRemoteQueueDefinitonsis set to false.

Page 135: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 135

Outbound Message Handling

The outbound endpoint behavior depends on the WebSphere MQ message type. If the message type isMQMT_REPLY or MQMT_DATAGRAM, other properties will be copied over from the original message and themessage will be dispatched to the queue.

If the message type is MQMT_REQUEST, the connector will check for the existence of the JMSReplyTosetting on the message. If it is not set, the temporary queue will be created. If the endpoint issynchronous, the connector will wait for a response. The timeout can be set using the responseTimeoutsetting. If a response is received by the connector, it will be returned by the component.

Page 136: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 136

Retrieving the Connection Factory from JNDI

To support the case where a JNDI registry has been configured to store the connection factory, theconnector declaration should include the following parameters. This is the same as the regular JMStransport documented here.

<wmq:connector ... jndiInitialFactory="com.sun.jndi.ldap.LdapCtxFactory" jndiProviderUrl="ldap://localhost:10389/" connectionFactoryJndiName="cn=ConnectionFactory,dc=example,dc=com"

Transformers

The WMQ transport provides a transformer for converting a com.ibm.jms.JMSMessage or sub-type intoan object by extracting the message payload. It also provides a transformer to convert the object back toa message. You use the <message-to-object-transformer> and <object-to-message-transformer>elements to configure these transformers. Note that object payloads work only when targetClient is setto JMS_COMPLIANT.

Page 137: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 137

Transactions

You can configure single-resource (local), multi-resource, and XA transactions on WMQ transportendpoints using the standard transaction configuration elements. For example, you might configure an XAtransaction on an outbound endpoint as follows:

<jbossts:transaction-manager/>

<wmq:xa-connector name="wmqConnector" hostName="winter" ...>... <outbound> <pass-through-router> <wmq:outbound-endpoint queue="out"> <xa-transaction action="ALWAYS_BEGIN"/> </wmq:outbound-endpoint> </pass-through-router> </outbound>...

Note that if you are using XA transactions, and you are connecting to a queue that requires thequeue manager to connect to a remote resource, you must use the extended transactional client fromWebSphere MQ (mqetclient.jar). For more information, see What is an extended transactional client? inthe WebSphere MQ 7 help.

For more information on using transactions, see Transaction Management.

Known Limitations

Following are the features that have not been fully tested with the Mule WMQ transport or are notsupported:

• Remote queues (tested only in previous releases)• Exit handler support (not tested)• Topics (not tested)• MQMT_REPORT message type support (not supported)• Native WMQ connection pool support (not supported)• SSL connection support (not supported)• Data compression over channels for performance throughput gain (not supported)

Configuration Reference

Connector

The default WebSphere MQ connector.

Attributes of <connector...>

Name Type Required Default Description

queueManager string no The name of theQueueManager touse.

hostName string no The hostname of the

Page 138: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 138

QueueManager touse.

port port number no The port of theQueueManager touse.

temporaryModel string no The temporarydestinationmodel to usewhen creatingtemporarydestinations fromthis connector.

ccsId integer no The WebSphereMQ CCS ID.

transportType no Whether to usea local binding orclient/server TCPbinding. Possiblevalues are:BINDINGS_MQ,CLIENT_MQ_TCPIP,DIRECT_HTTP,DIRECT_TCPIP,and MQJD.

channel string no The name of thechannel used tocommunicatewith theQueueManager.

propagateMQEvents boolean no

useRemoteQueueDefinitionsboolean no When usingremote queuedefinitions,WMQ uses theJMSReplyTopropertyto channelresponses.When set to truethis propertywill causeMule to ignoreReplyTo queuedestinations andnot interferewith WMQ'sremote queuemechanism. Bydefault this isset to false. Thisalso means thatby using WMQ'sremote queuedefinitions it is notpossible to usesome of Mule'srequest/response

Page 139: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 139

patterns when thisproperrty is true.

receiveExitHandler class name no The fully qualifiedclass nameof the receiveexit handlerimplementation.

receiveExitHandlerInitclass name no An initializationparameter forthe receive exithandler.

sendExitHandler class name no The fully qualifiedclass name of thesend exit handlerimplementation.

sendExitHandlerInit class name no An initializationparameter for thesend exit handler.

securityExitHandler class name no The fully qualifiedclass name ofthe securityexit handlerimplementation.

securityExitHandlerInitclass name no An initializationparameter forthe security exithandler.

targetClient no Specifies whetherthis is in JMSor non-JMSformat. Possiblevalues are:JMS_COMPLIANTor NONJMS_MQ(default).

Xa Connector

The WebSphere MQ connector for XA transactions.

Attributes of <xa-connector...>

Name Type Required Default Description

queueManager string no The name of theQueueManager touse.

hostName string no The hostname of theQueueManager touse.

Page 140: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 140

port port number no The port of theQueueManager touse.

temporaryModel string no The temporarydestinationmodel to usewhen creatingtemporarydestinations fromthis connector.

ccsId integer no The WebSphereMQ CCS ID.

transportType no Whether to usea local binding orclient/server TCPbinding. Possiblevalues are:BINDINGS_MQ,CLIENT_MQ_TCPIP,DIRECT_HTTP,DIRECT_TCPIP,and MQJD.

channel string no The name of thechannel used tocommunicatewith theQueueManager.

propagateMQEvents boolean no

useRemoteQueueDefinitionsboolean no When usingremote queuedefinitions,WMQ uses theJMSReplyTopropertyto channelresponses.When set to truethis propertywill causeMule to ignoreReplyTo queuedestinations andnot interferewith WMQ'sremote queuemechanism. Bydefault this isset to false. Thisalso means thatby using WMQ'sremote queuedefinitions it is notpossible to usesome of Mule'srequest/responsepatterns when thisproperrty is true.

Page 141: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 141

receiveExitHandler class name no The fully qualifiedclass nameof the receiveexit handlerimplementation.

receiveExitHandlerInitclass name no An initializationparameter forthe receive exithandler.

sendExitHandler class name no The fully qualifiedclass name of thesend exit handlerimplementation.

sendExitHandlerInit class name no An initializationparameter for thesend exit handler.

securityExitHandler class name no The fully qualifiedclass name ofthe securityexit handlerimplementation.

securityExitHandlerInitclass name no An initializationparameter forthe security exithandler.

targetClient no Specifies whetherthis is in JMSor non-JMSformat. Possiblevalues are:JMS_COMPLIANTor NONJMS_MQ(default).

Inbound Endpoint

An endpoint on which WMQ messages are received.

Attributes of <inbound-endpoint...>

Name Type Required Default Description

queue string no The queue name.

Outbound Endpoint

An endpoint to which WMQ messages are sent.

Page 142: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 142

Attributes of <outbound-endpoint...>

Name Type Required Default Description

queue string no The queue name.

disableTemporaryReplyToDestinationsboolean no If this is setto false (thedefault), whenMule performsrequest/responsecalls a temporarydestination willautomatically beset up to receive aresponse from theremote WMQ call.

correlationId string no A client can usethe correlation IDheader field to linkone message toanother. A typicaluse case is tolink a responsemessage with itsrequest message.The CorrelationIDmust be a 24-byteString. WebSpherewill pad shortervalues withzeroes so thatthe fixed length isalways 24 bytes.Because eachmessage sent bya WMQ provideris assigned amessage ID value,it is convenientto link messagesvia the messageID. All messageID values muststart with the 'ID:'prefix.

messageType no Indicatesthe messagetype. Each ofthe messagetypes havespecific behaviorassociatedwith them. Thefollowing messagetypes are defined:MQMT_REQUEST:The messagerequires a reply.Specify the name

Page 143: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 143

of the replyqueue usingthe <ReplyTo>element ofoutbound routers.Mule handlesthe underlyingconfiguration.MQMT_DATAGRAM:The messagedoes notrequire a reply.MQMT_REPLY: Themessage is thereply to an earlierrequest message(MQMT_REQUEST).The messagemust be sentto the queueindicated bythe <ReplyTo>configured on theoutbound router.Mule automaticallyconfigures therequest to controlhow to set theMessageId andCorrelationIdof the reply.MQMT_REPORT:The messageis reporting onsome expectedor unexpectedoccurrence,usually relatedto some othermessage (forexample, arequest messagewas receivedthat containeddata that was notvalid). Sends themessage to thequeue indicatedby the <ReplyTo>configurationof the messagedescriptor of theoriginal message.

characterSet integer no If set, thisproperty overridesthe codedcharacter setproperty of thedestination queueor topic.

persistentDelivery boolean no If set to true, theJMS provider logs

Page 144: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 144

the message tostable storage asit is sent so that itcan be recoveredif delivery isunsuccessful.A client marksa message aspersistent if theapplication willhave problemsif the messageis lost in transit.A client marksa message asnon-persistentif an occasionallost message istolerable. Clientsuse deliverymode to tell aJMS providerhow to balancemessage transportreliability/throughput.Delivery modeonly covers thetransport ofthe message toits destination.Retention of amessage at thedestination untilits receipt isacknowledged isnot guaranteedby a PERSISTENTdelivery mode.Clients shouldassume thatmessage retentionpolicies are setadministratively.Message retentionpolicy governsthe reliability ofmessage deliveryfrom destinationto messageconsumer. Forexample, if aclient's messagestorage spaceis exhausted,some messages asdefined by a site-specific messageretention policymay be dropped.A message isguaranteed to bedelivered onceand only once by

Page 145: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 145

a JMS provider ifthe delivery modeof the messageis persistent andif the destinationhas a sufficientmessage retentionpolicy.

timeToLive long no Define the defaultlength of time inmilliseconds fromits dispatch timethat a producedmessage shouldbe retained by themessage system.Time to live is setto zero (forever)by default.

priority substitutablePriorityNumberno Sets the messagepriority. JMSdefines a ten-levelpriority value with0 as the lowestpriority and 9 asthe highest. Inaddition, clientsshould considerpriorities 0-4 asgradations ofnormal priorityand priorities 5-9as gradationsof expeditedpriority. JMSdoes not requirethat a providerstrictly implementpriority orderingof messages.However, it shoulddo its best todeliver expeditedmessagesahead of normalmessages.

targetClient no Specifies whetherthis is in JMSor non-JMSformat. Possiblevalues are:JMS_COMPLIANTor NONJMS_MQ(default).

Endpoint

A global WMQ endpoint definition. Note that global endpoints are like endpoint factories from whichnew endpoints can be created. As such this endpoint has a union of inbound and outbound endpointproperties. Depending on how this endpoint is used the unneeded properties will ignored.

Page 146: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 146

Attributes of <endpoint...>

Name Type Required Default Description

queue string no The queue name.

disableTemporaryReplyToDestinationsboolean no If this is setto false (thedefault), whenMule performsrequest/responsecalls a temporarydestination willautomatically beset up to receive aresponse from theremote WMQ call.

correlationId string no A client can usethe correlation IDheader field to linkone message toanother. A typicaluse case is tolink a responsemessage with itsrequest message.The CorrelationIDmust be a 24-byteString. WebSpherewill pad shortervalues withzeroes so thatthe fixed length isalways 24 bytes.Because eachmessage sent bya WMQ provideris assigned amessage ID value,it is convenientto link messagesvia the messageID. All messageID values muststart with the 'ID:'prefix.

messageType no Indicatesthe messagetype. Each ofthe messagetypes havespecific behaviorassociatedwith them. Thefollowing messagetypes are defined:MQMT_REQUEST:The messagerequires a reply.Specify the name

Page 147: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 147

of the replyqueue usingthe <ReplyTo>element ofoutbound routers.Mule handlesthe underlyingconfiguration.MQMT_DATAGRAM:The messagedoes notrequire a reply.MQMT_REPLY: Themessage is thereply to an earlierrequest message(MQMT_REQUEST).The messagemust be sentto the queueindicated bythe <ReplyTo>configured on theoutbound router.Mule automaticallyconfigures therequest to controlhow to set theMessageId andCorrelationIdof the reply.MQMT_REPORT:The messageis reporting onsome expectedor unexpectedoccurrence,usually relatedto some othermessage (forexample, arequest messagewas receivedthat containeddata that was notvalid). Sends themessage to thequeue indicatedby the <ReplyTo>configurationof the messagedescriptor of theoriginal message.

characterSet integer no If set, thisproperty overridesthe codedcharacter setproperty of thedestination queueor topic.

persistentDelivery boolean no If set to true, theJMS provider logs

Page 148: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 148

the message tostable storage asit is sent so that itcan be recoveredif delivery isunsuccessful.A client marksa message aspersistent if theapplication willhave problemsif the messageis lost in transit.A client marksa message asnon-persistentif an occasionallost message istolerable. Clientsuse deliverymode to tell aJMS providerhow to balancemessage transportreliability/throughput.Delivery modeonly covers thetransport ofthe message toits destination.Retention of amessage at thedestination untilits receipt isacknowledged isnot guaranteedby a PERSISTENTdelivery mode.Clients shouldassume thatmessage retentionpolicies are setadministratively.Message retentionpolicy governsthe reliability ofmessage deliveryfrom destinationto messageconsumer. Forexample, if aclient's messagestorage spaceis exhausted,some messages asdefined by a site-specific messageretention policymay be dropped.A message isguaranteed to bedelivered onceand only once by

Page 149: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 149

a JMS provider ifthe delivery modeof the messageis persistent andif the destinationhas a sufficientmessage retentionpolicy.

timeToLive long no Define the defaultlength of time inmilliseconds fromits dispatch timethat a producedmessage shouldbe retained by themessage system.Time to live is setto zero (forever)by default.

priority substitutablePriorityNumberno Sets the messagepriority. JMSdefines a ten-levelpriority value with0 as the lowestpriority and 9 asthe highest. Inaddition, clientsshould considerpriorities 0-4 asgradations ofnormal priorityand priorities 5-9as gradationsof expeditedpriority. JMSdoes not requirethat a providerstrictly implementpriority orderingof messages.However, it shoulddo its best todeliver expeditedmessagesahead of normalmessages.

targetClient no Specifies whetherthis is in JMSor non-JMSformat. Possiblevalues are:JMS_COMPLIANTor NONJMS_MQ(default).

Message To Object Transformer

Converts a com.ibm.jms.JMSMessage or sub-type into an object by extracting the message payload.

Page 150: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 150

Object To Message Transformer

Converts an object back into a com.ibm.jms.JMSMessage.

Transaction

Transactions allow a series of operations to be grouped together so that they can be rolled back if afailure occurs. Set the action (such as ALWAYS_BEGIN or JOIN_IF_POSSIBLE) and the timeout setting forthe transaction.

Page 151: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 151

Multicast Transport

This page last changed on Mar 04, 2009 by jackie.wheeler.

Multicast Transport

The Multicast transport sends and receives Mule events using IP multicasting. The Javadoc for thistransport can be found here .

Connector

The Multicast <connector> element extends the UDP connector with additional optional attributes:

Attribute Description

timeToLive Set the time-to-live value for Multicast packets tocontrol their scope. It must be in the range 0 to255 (inclusive).

loopback Whether to enable local loopback of Multicastdatagrams. The option is used by the platformnetworking code as a hint for setting whetherMulticast data will be looped back to the localsocket.

Endpoints

You configure Multicast endpoints just as you would with any other transport, with the following additionalattributes:

• host: the IP address of the server, such as www.mulesource.com, localhost, or 127.0.0.1• port: the port number of the server.

For example, you could configure a global endpoint as follows:

<multicast:endpoint host="224.0.0.1" port="60131" name="serverEndpoint" />

Transformers

The following transformers are used by default for this connector unless a transformer is explicitly set onthe provider.

Transformer Description

ByteArrayToString Converts a byte array to a String

StringToByteArray Converts a String to a byte array

Page 152: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 152

POP3S Transport

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

POP3S Transport

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

The POP3s connector enables POP3 over SSL using the javax.mail APIs. It supports all the elements andattributes of the POP3 connector plus some required properties for setting up the client key store and thetrust store for the SSL connection.

Property Description

tls-client Configures the client key store with the followingattributes:

• path: The location (which will be resolvedrelative to the current classpath and filesystem, if possible) of the keystore thatcontains public certificates and private keysfor identification

• storePassword: The password used toprotect the keystore

• class: The type of keystore used (a Javaclass name)

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

• path: The location (which will be resolvedrelative to the current classpath and filesystem, if possible) of the trust store thatcontains public certificates of trusted servers

• storePassword: The password used toprotect the trust store

For example:

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

For information on configuring endpoints using the POP3S connector, see POP3 Transport.

The POP3S transport supports the same filters and transformers as the Email Transport.

Page 153: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 153

POP3 Transport

This page last changed on Nov 26, 2008 by jackie.wheeler.

POP3 Transport

The POP3 transport can be used for receiving messages from POP3 inboxes. The POP3S Transportconnects to POP3 mailboxes using SSL (POP3s) using the javax.mail API. The POP3 transport uses thesame filters and transformers as the Email Transport.

The Javadoc for this provider can be found here .

POP3 Connector

The POP3 connector supports all the common connector attributes and properties and the followingadditional attributes:

Attribute Description Default Required

backupEnabled Whether to save copiesto the backup folder.

False No

backupFolder The folder wheremessages are movedfor audit purposes afterthey have been read.

No

checkFrequency Determines how often(in milliseconds) thePOP3 mailbox is polledfor new messages.

60000 Yes

mailboxFolder The remote folder tocheck for email.

INBOX No

deleteReadMessages Whether to deletemessages after theyhave been downloaded.If set to false, themessages are set toSEEN.

true No

Endpoints

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

• user: the user name of the mailbox owner• password: the password of the user• host: the IP address of the POP3 server, such as www.mulesource.com, localhost, or 127.0.0.1• port: the port number of the POP3 server. If not set for the POP3S connector, the default port is 995.

For example:

<pop3:inbound-endpoint user="bob" password="foo" host="pop.gmail.com" checkFrequency="3000" />

or:

<pop3s:inbound-endpoint user="bob" password="foo" host="pop.gmail.com" checkFrequency="3000" />

Page 154: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 154

This will log into the bob mailbox on pop.gmail.com using password foo (using the default port 995 forthe POP3S endpoint) and will check the mailbox for new messages every 30 seconds. You can also specifythe endpoint settings using a URI, but the above syntax is easier to read.

Escape Your Credentials

If you use a URI-style endpoint and you include the user name and password, escape anycharacters that are illegal for URIs, such as the @ character. For example, if the user nameis [email protected], you should enter it as user%40myco.com.

Page 155: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 155

Quartz Transport

This page last changed on Mar 02, 2009 by jackie.wheeler.

Quartz Transport

[ About Cron Expressions ] [ About Jobs ] [ Connector ] [ Outbound Endpoint ] [ Inbound Endpoint ] [Endpoint ] [ Abstract Job ] [ Abstract Inbound Job ] [ Event Generator Job ] [ Endpoint Polling Job ] [Scheduled Dispatch Job ] [ Custom Job ] [ Custom Job From Message ]

The Quartz transport provides support for scheduling events and for triggering new events. An inboundquartz endpoint can be used to trigger inbound events that can be repeated, such as every second.Outbound quartz endpoints can be used to schedule an existing event to fire at a later date. Users cancreate schedules using cron expressions, and events can be persisted in a database.

This transport makes use of the Quartz Project at Open Symphony. The Quartz site has more genericinformation about how to work with Quartz.

About Cron Expressions

A cron expression is a string comprised by six or seven fields separated by white space. Fields cancontain any of the allowed values, along with various combinations of the allowed special characters forthat field. The fields are as follows:

Field Name Mandatory Allowed Values Allowed SpecialChars

Seconds YES 0-59 , - * /

Minutes YES 0-59 , - * /

Hours YES 0-23 , - * /

Day of Month YES 1-31 , - * ? / L W C

Month YES 1-12 or JAN-DEC , - * /

Day of Week YES 1-7 or SUN-SAT , - * ? / L C #

Year NO empty, 1970-2099 , - * /

Cron expressions can be as simple as this:* * * * ? *

or more complex, like this:0 0/5 14,18,3-39,52 ? JAN,MAR,SEP MON-FRI 2002-2010.

Following are some examples:

Expression Behavior

0 0 12 * * ? Fire at 12pm (noon) every day

0 15 10 ? * * Fire at 10:15am every day

0 15 10 * * ? Fire at 10:15am every day

0 15 10 * * ? * Fire at 10:15am every day

Page 156: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 156

0 15 10 * * ? 2005 Fire at 10:15am every day during the year 2005

0 * 14 * * ? Fire every minute starting at 2pm and ending at2:59pm, every day

0 0/5 14 * * ? Fire every 5 minutes starting at 2pm and endingat 2:55pm, every day

If you are not familiar with cron syntax, here is a good tutorial.

About Jobs

Jobs are used to perform an action when a time trigger occurs from the Quartz transport. Mule provides anumber of jobs for generating and scheduling events. These are detailed below. Users can also write theirown jobs and hook them in using the custom-job type included with Mule.

Connector

The Quartz connector is used to configure the default behavior for Quartz endpoints that referencethe connector. Note if there is only one Quartz connector configured, all Quartz endpoints will use thatconnector.

Attributes of <connector...>

Name Type Required Default Description

scheduler-ref name (no spaces) no Provides animplementationof the QuartzSchedulerinterface. If novalue is provided,a scheduler isretrieved from theStdSchedulerFactory.If no propertiesare provided, thegetDefaultSchedulermethod is called.Otherwise, a newfactory instance iscreated using thegiven properties,and a scheduleris retrieved usingthe getSchedulermethod.

Child Elements of <connector...>

Name Cardinality Description

factory-property 0..* Set a property on the factory(see scheduler-ref).

Page 157: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 157

Outbound Endpoint

An outbound Quartz endpoint allows existing events to be stored and fired at a later time/date. If youare using a persistent event store, the payload of the event must implement java.io.Serializable. Youconfigure an org.quartz.Job implementation on the endpoint to tell it what action to take. Mule has somedefault jobs, but you can also write your own.

Attributes of <outbound-endpoint...>

Name Type Required Default Description

jobName string no The name toassociate withthe job on theendpoint. This isonly really usedinternally whenstoring events.

cronExpression string no The cronexpression toschedule eventsat specifieddates/times.This attribute orrepeatInterval isrequired.

repeatInterval long no The number ofmillisecondsbetween twoevents. Thisattribute orcronExpression isrequired.

repeatCount integer no The number ofevents to bescheduled. Thisvalue defaults to-1, which meansthat the eventswill be scheduledindefinitely.

startDelay long no The number ofmilliseconds thatwill elapse beforethe first event isfired.

Child Elements of <outbound-endpoint...>

Name Cardinality Description

abstract-job 1..1 A placeholder for Quartz jobsthat can be set on the endpoint.

Page 158: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 158

Inbound Endpoint

A Quartz inbound endpoint can be used to generate events. It is most useful when you want to trigger aservice at a given interval (or cron expression) rather than have an external event trigger the service.

Attributes of <inbound-endpoint...>

Name Type Required Default Description

jobName string no The name toassociate withthe job on theendpoint. This isonly really usedinternally whenstoring events.

cronExpression string no The cronexpression toschedule eventsat specifieddates/times.This attribute orrepeatInterval isrequired.

repeatInterval long no The number ofmillisecondsbetween twoevents. Thisattribute orcronExpression isrequired.

repeatCount integer no The number ofevents to bescheduled. Thisvalue defaults to-1, which meansthat the eventswill be scheduledindefinitely.

startDelay long no The number ofmilliseconds thatwill elapse beforethe first event isfired.

Child Elements of <inbound-endpoint...>

Name Cardinality Description

abstract-job 1..1 A placeholder for Quartz jobsthat can be set on the endpoint.

Page 159: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 159

Endpoint

A global endpoint that can be used as a template to create inbound and outbound Quartz endpoints.Common configuration can be set on a global endpoint and then referenced using the @ref attribute onthe local endpoint. Note that because jobs sometimes only work on inbound or outbound endpoints, theyhave to be set on the local endpoint.

Attributes of <endpoint...>

Name Type Required Default Description

jobName string no The name toassociate withthe job on theendpoint. This isonly really usedinternally whenstoring events.

cronExpression string no The cronexpression toschedule eventsat specifieddates/times.This attribute orrepeatInterval isrequired.

repeatInterval long no The number ofmillisecondsbetween twoevents. Thisattribute orcronExpression isrequired.

repeatCount integer no The number ofevents to bescheduled. Thisvalue defaults to-1, which meansthat the eventswill be scheduledindefinitely.

startDelay long no The number ofmilliseconds thatwill elapse beforethe first event isfired.

Child Elements of <endpoint...>

Name Cardinality Description

abstract-job 0..1 A placeholder for Quartz jobsthat can be set on the endpoint.

Page 160: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 160

Abstract Job

A placeholder for Quartz jobs that can be set on the endpoint.

Attributes of <abstract-job...>

Name Type Required Default Description

groupName string no The group nameof the scheduledjob

jobGroupName string no The job groupname of thescheduled job.

Abstract Inbound Job

A placeholder for Quartz jobs that can be set on inbound endpoints only.

Attributes of <abstract-inbound-job...>

Name Type Required Default Description

groupName string no The group nameof the scheduledjob

jobGroupName string no The job groupname of thescheduled job.

Event Generator Job

An inbound endpoint job that will trigger a new event for the service according to the schedule on theendpoint. This is useful for periodically triggering a service without the need for an external event tooccur.

Child Elements of <event-generator-job...>

Name Cardinality Description

payload 0..1 The payload of the newlycreated event. The payload canbe a reference to a file, fixedstring, or object configuredas a Spring bean. If thisvalue is not set, an eventwill be generated with anorg.mule.transport.NullPayloadinstance.

Following is an example:

Page 161: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 161

Click here to expand...

<service name="testService1"> <description> This configuration will create an inbound event for testService1 at 12 noon every day. The event payload will always have the same value 'foo'. </description>

<inbound> <quartz:inbound-endpoint name="qEP1" cronExpression="0 0 12 * * ?" jobName="job1" connector-ref="quartzConnector1"> <quartz:event-generator-job> <quartz:payload>foo</quartz:payload> </quartz:event-generator-job> </quartz:inbound-endpoint> </inbound></service>

<service name="testService2"> <description> This configuration will create an inbound event for testService2 every 1 second indefinitely. The event payload will always have the same value, which the contents of the file 'payload-data.txt'. The file can be on the classpath of on the local file system. </description>

<inbound> <quartz:inbound-endpoint name="qEP2" repeatCount="10" repeatInterval="1000" jobName="job2" connector-ref="quartzConnector1"> <quartz:event-generator-job > <quartz:payload file="payload-data.txt"/> </quartz:event-generator-job> </quartz:inbound-endpoint> </inbound></service>

Endpoint Polling Job

An inbound endpoint job that can be used to periodically read from an external source (via anotherendpoint). This can be useful for triggering time-based events from sources that do not support polling orfor simply controlling the rate in which events are received from the source.

Child Elements of <endpoint-polling-job...>

Name Cardinality Description

job-endpoint 0..1 A reference to anotherconfigured endpoint from whichevents will be received.

For example:

Click here to expand...

<service name="testService5"> <description> The endpoint polling Job will try and perform a 'request' on any Mule endpoint. If a result is received it will be handed off to this 'testService5' service for processing. The trigger will fire every 5 minutes starting at 2pm

Page 162: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 162

and ending at 2:55pm, every day. during this period the job will check the file directory /N/drop-data/in every 5 minutes to see if any event data is available. The request will timeout after 4 seconds if there are no files in the directory. </description>

<inbound> <quartz:inbound-endpoint name="qEP5" cronExpression="0 0/5 14 * * ?" jobName="job5" connector-ref="quartzConnector1"> <quartz:endpoint-polling-job> <quartz:job-endpoint address="file:///N/drop-data/in" timeout="4000"/> </quartz:endpoint-polling-job> </quartz:inbound-endpoint> </inbound></service>

Scheduled Dispatch Job

An outbound job that will schedule a job for dispatch at a later time/date. The event will get dispatchedusing the configured endpoint reference.

Child Elements of <scheduled-dispatch-job...>

Name Cardinality Description

job-endpoint 0..1 The endpoint used to dispatchthe scheduled event. Thepreferred approach is to createa global endpoint and referenceit using the ref attribute.However, you can also use theaddress attribute to define aURI endpoint. You can use thetimeout attribute to specifyan arbitrary time-out valueassociated with the endpointthat can be used by jobs thatblock waiting to receive events.

For example:

Click here to expand...

<service name="testService6"> <description> This outbound Quartz endpoint will receive an event after the component has processed it and store it in the event store. When the trigger kicks in at 10:15am everyday it will dispatch the event on the endpoint referenced as 'scheduledDispatchEndpoint'. Since the 'repeatCount' is set to 0, the event will only be sent out once. </description>

<inbound> <inbound-endpoint address="test://inbound6"/> </inbound> <test:component/> <outbound> <pass-through-router> <quartz:outbound-endpoint name="qEP6" repeatCount="0" cronExpression="0 15 10 * * ? *" jobName="job6" connector-ref="quartzConnector1"> <quartz:scheduled-dispatch-job>

Page 163: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 163

<quartz:job-endpoint ref="scheduledDispatchEndpoint"/> </quartz:scheduled-dispatch-job> </quartz:outbound-endpoint> </pass-through-router> </outbound></service>

Custom Job

A custom job can be configured on inbound or outbound endpoints. You can create and configure yourown job implementation and use it on a Quartz endpoint. A custom job can be configured as a bean inthe XML configuration and referenced using this job.

Attributes of <custom-job...>

Name Type Required Default Description

groupName string no The group nameof the scheduledjob

jobGroupName string no The job groupname of thescheduled job.

job-ref string no The bean name orID of the customjob to use whenthis job getsexecuted.

For example:

Click here to expand...

<service name="testService5"> <description> The endpoint polling Job will try and perform a 'request' on any Mule endpoint. If a result is received it will be handed off to this 'testService5' service for processing. The trigger will fire every 5 minutes starting at 2pm and ending at 2:55pm, every day. during this period the job will check the file directory /N/drop-data/in every 5 minutes to see if any event data is available. The request will timeout after 4 seconds if there are no files in the directory. </description>

<inbound> <quartz:inbound-endpoint name="qEP5" cronExpression="0 0/5 14 * * ?" jobName="job5" connector-ref="quartzConnector1"> <quartz:endpoint-polling-job> <quartz:job-endpoint address="file:///N/drop-data/in" timeout="4000"/> </quartz:endpoint-polling-job> </quartz:inbound-endpoint> </inbound></service>

Page 164: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 164

Custom Job From Message

Allows a job to be stored on the current message. This can only be used on outbound endpoints. Whenthe message is received, the job is read and the job is added to the scheduler with the current message.This allows for custom scheduling behavior determined by the message itself. Usually the service or atransformer would create the job on the message based on application-specific logic. Any Mule-supportedexpressions can be used to read the job from the message. Typically, you add the job as a header, but anattachment could also be used.

Attributes of <custom-job-from-message...>

Name Type Required Default Description

groupName string no The group nameof the scheduledjob

jobGroupName string no The job groupname of thescheduled job.

For example:

Click here to expand...

<service name="testService3"> <description> This configuration will process a message and find a Job configured as a header called 'jobConfig' on the current message. We're using the test component here, but a real implementation will need to set a custom {{org.quartz.Job}} implementation as a header on the current message. Note that other expressions could be used to extract the job from an attachment or even a property within the payload itself. </description>

<inbound> <inbound-endpoint address="test://inbound3"/> </inbound> <test:component/> <outbound> <pass-through-router> <quartz:outbound-endpoint name="qEP3" repeatInterval="1000" jobName="job3" connector-ref="quartzConnector1"> <quartz:custom-job-from-message evaluator="header" expression="jobConfig"/> </quartz:outbound-endpoint> </pass-through-router> </outbound></service>

Page 165: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 165

RMI Transport

This page last changed on Feb 20, 2009 by jackie.wheeler.

RMI Transport

The RMI transport can be used to send and receive Mule events over JRMP. This transport has adispatcher that invokes an RMI method and a polling receiver that repeatedly does the same.

You configure the RMI transport as follows:

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

<spring:bean name="jndiFactory" class="org.mule.transport.rmi.MuleRMIFactory"/>

<spring:bean name="jndiContext" factory-bean="jndiFactory" factory-method="create"/>

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

<rmi:endpoint name="hello" host="localhost" port="1099" object="HelloServer" method="hello" methodArgumentTypes="java.lang.String"/>

The connector looks for the method and methodArgumentTypes. It uses the payload as the argument.

JNP Connector

If you want to use the Java naming protocol to bind to remote objects, you can use the JNP connectorinstead simply by using the jnp namespace.

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

<spring:bean name="jndiFactory" class="org.mule.transport.rmi.MuleRMIFactory"/> <spring:bean name="jndiContext" factory-bean="jndiFactory" factory-method="create"/>

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

Page 166: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 166

<jnp:endpoint name="Sender2" host="localhost" port="1099" object="MatchingUMO" method="reverseString"/>...

Configuration Reference

Connector

Attributes of <connector...>

Name Type Required Default Description

pollingFrequency long no Period (ms)between pollingconnections.

securityManager-ref

name (no spaces) no Bean referenceto the securitymanager thatshould be used.

securityPolicy string no The securitypolicy (file name)used to enableconnections.

serverClassName name (no spaces) no The target classname.

serverCodebase string no The targetmethod.

Endpoint

Attributes of <endpoint...>

Name Type Required Default Description

host string no The endpoint hostname.

port port number no The port numberto use when aconnection ismade.

object string no The class nameof the object thatis being invokedover RMI.

method string no The name of themethod to invoke.

Page 167: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 167

methodArgumentTypesstring no Comma separatedargument typesof the methodto invoke.For example,"java.lang.String".

Page 168: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 168

Servlet Transport

This page last changed on Mar 04, 2009 by jackie.wheeler.

Servlet Transport

The Servlet transport provides integration with a servlet implementation. The implementing servlet doesthe work of receiving a request, and the Servlet transport then hands off the request to any receiversregistered with it. There is no notion of a dispatcher for this connector, as it is triggered by a request andmay or may not return a response. You specify the servlet URL as part of the connector configuration andthen specify the endpoints just like any other HTTP endpoints.

The Javadoc for this transport can be found here . For more information about using Mule with servletcontainers, see Embedding Mule in a Java Application or Webapp. For information on using the RESTletconnector, click here.

Connector

Servlet connector is a channel adapter between Mule and a servlet engine. It allows theMuleReceiverServlet to look up components interested in requests it receives via the servlet container.

Attributes of <connector...>

Name Type Required Default Description

servletUrl no The real URLon which theservlet containeris bound. If thisis not set, theWSDL may notbe generatedcorrectly.

For example:

<servlet:connector name="servletConnector" servletUrl="http://localhost:8180/path/" />

You can also specify the servlet URL as part of the endpoint:

<servlet:inbound-endpoint path="foo" />

or:

<inbound-endpoint address="servlet://foo" />

Servlet endpoints are identical to HTTP endpoints with the exception that they use the servlet: prefixinstead of http:. For more information, see HTTP Transport.

Page 169: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 169

SMTPS Transport

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

SMTPS Transport

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

The SMTPS connector enables SMTP over SSL using the javax.mail APIs. It supports all the elementsand attributes of the SMTP connector plus some required properties for setting up the client key store andthe trust store for the SSL connection.

Property Description

tls-client Configures the client key store with the followingattributes:

• path: The location (which will be resolvedrelative to the current classpath and filesystem, if possible) of the keystore thatcontains public certificates and private keysfor identification

• storePassword: The password used toprotect the keystore

• class: The type of keystore used (a Javaclass name)

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

• path: The location (which will be resolvedrelative to the current classpath and filesystem, if possible) of the trust store thatcontains public certificates of trusted servers

• storePassword: The password used toprotect the trust store

For example:

<smtps:connector name="smtpsConnector"> <smtps:tls-client path="clientKeystore" storePassword="mulepassword" /> <smtps:tls-trust-store path="greenmail-truststore" storePassword="password" /> </smtps:connector><model name="test"> <service name="relay"> <inbound> <vm:inbound-endpoint path="send" /> </inbound> <outbound> <outbound-pass-through-router> <smtps:outbound-endpoint host="localhost" port="65439" to="[email protected]" /> </outbound-pass-through-router> </outbound>...

For information on configuring endpoints using the SMTPS connector, see SMTP Transport.

Page 170: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 170

The SMTPS transport supports the same filters and transformers as the Email Transport.

Page 171: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 171

SMTP Transport

This page last changed on Feb 20, 2009 by jackie.wheeler.

SMTP Transport

The SMTP transport can be used for sending messages over SMTP using the javax.mail API. Seethe SMTPS Transport for a secure version. The implementation supports CC/BCC/ReplyTo addresses,attachments, custom Header properties, and customizable authentication. It also provides support forjavax.mail.Message transformation.

The Javadoc for this transport can be found here .

SMTP Connector

The SMTP connector supports all the common connector attributes and properties and the followingoptional element and attributes:

<connector ...>

Attributes

Name Type Required Default Description

bccAddresses string no Comma separatedlist of addressesfor blind copies.

ccAddresses string no Comma separatedlist of addressesfor copies.

contentType string no Mime type forthe outgoingmessage.

fromAddress string no The from addressfor the outgoingmessage.

replyToAddresses string no The reply-toaddress forthe outgoingmessage.

subject string no The defaultsubject for theoutgoing messageif none is set inthe message.

Page 172: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 172

Child Elements

Name Cardinality Description

header 1..1 Additional header name andvalue, added to the message.

For example:

<smtp:connector name="smtpConnector" bccAddresses="[email protected]" ccAddresses="[email protected]" contentType="foo/bar" fromAddress="[email protected]" replyToAddresses="[email protected]" subject="subject"> <smtp:header key="foo" value="bar" /> <smtp:header key="baz" value="boz" /> </smtp:connector>

Endpoints

SMTP endpoints describe details about the SMTP server and the recipients of messages sent fromthe SMTP endpoint. You configure the endpoints just as you would with any other transport, with thefollowing additional attributes:

Attribute Description

user The user name of the mailbox owner

password The password of the user

host The IP address of the SMTP server, such aswww.mulesource.com, localhost, or 127.0.0.1

port The port number of the SMTP server

to The destination for the email

from The address of the sender of the email

subject The email subject

cc A comma-separated list of email addresses tocopy on this email

bcc A comma-separated list of email addresses toblind-copy on this email

replyTo The address used by default if someone replies tothe email

For example:

<outbound> <outbound-pass-through-router> <smtp:outbound-endpoint host="localhost" port="65437" from="[email protected]" to="[email protected]" subject="Please verify your account details"/>

Page 173: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 173

</outbound-pass-through-router></outbound>

If you only need a few attributes, you can specify the endpoint as a URI. However, the above syntax isrecommended for easier readability. The URI syntax is as follows:

smtp://[user:password@]<smtp server>[MULE::port]?address=<recipient address>

The format is the same for SMTPS:

smtps://[user:password@]<smtp server>[MULE::port]?address=<recipient address>

For example:

smtp://muletestbox:[email protected][email protected]

This will send mail using smtp.mail.yahoo.co.uk (using the default SMTP port) to the [email protected]. The SMTP request is authenticated using the username muletestbox and thepassword 123456.

Escape Your Credentials

If you use a URI-style endpoint and you include the user name and password, escape anycharacters that are illegal for URIs, such as the @ character. For example, if the user nameis [email protected], you should enter it as user%40myco.com.

So far, all configuration has been static, in that you define all the information in the configuration of theendpoint. However, you can set the connector properties to control the settings of the outgoing message.These properties will override the endpoint properties. If you always want to set the email addressdynamically, you can leave out the to attribute (or the address parameter if you're using URIs} on theSMTP endpoint.

Page 174: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 174

SOAP Transport

This page last changed on Dec 18, 2008 by jackie.wheeler.

SOAP Transport

The SOAP transport is deprecated and will be desupported in a future release. Werecommend that you either use the CXF Transport or the Axis Transport to build webservices from now on.

The SOAP transport enables your components to be exposed as web services and to act as SOAP clients.The SOAP transport provides support for the CFX and Axis transports.

The Javadoc for the SOAP transport can be found here .

Endpoints

You configure a SOAP endpoint as follows:

soap:http://localhost:1234/MyService

The actual SOAP stack used to execute this service will be discovered based on the first SOAP stackavailable on the class path. Alternatively, an implementation can be specified directly.

Transformer

The SOAP transport provides a single transformer, http-to-soap-request-transformer, which convertsan HTTP GET request into a SOAP request. It does so according to the following template:

<?xml version=\"1.0\" encoding=\"{0}\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <soap:Body> <NAMESPACE:METHOD> <NAMESPACE:PROPERTY1>VALUE1</NAMESPACE:PROPERTY1> <NAMESPACE:PROPERTY2>VALUE1</NAMESPACE:PROPERTY2> ... </NAMESPACE:METHOD> </soap:Body></soap:Envelope>

...where namespace is a property on the endpoint, the method is the "method" property set on themessage, and the properties are from the HTTP GET request.

For example, given the following transformer configuration:

<custom-transformer class="org.mule.transport.soap.transformers.HttpRequestToSoapRequest"> <spring:property name="namespace" value="http://acme.com/hello"></custom-transformer>

Page 175: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 175

...and a GET request of "http://foo.com/hello?method=sayHello&name=Dan&salutation=Bonjour", thefollowing SOAP message would be generated:

<?xml version=\"1.0\" encoding=\"{0}\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <soap:Body> <sayHello xmlns="http://acme.com/hello"> <name>Dan</name> <salutation>Bonjour</salutation> </sayHello> </soap:Body></soap:Envelope>

Page 176: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 176

SSL Transport

This page last changed on Mar 19, 2009 by jackie.wheeler.

SSL Transport

The SSL transport can be used for secure socket communication using SSL or TLS.

The Javadoc for this transport can be found here .

Connector

Connects Mule to an SSL socket to send or receive data via the network.

Child Elements of <connector...>

Name Cardinality Description

client 0..1 The client key store. SSL andTLS connections are made onbehalf of an entity, which canbe anonymous or identifiedby a certificate. This interfacespecifies how a keystore can beused to provide the certificates(and associated private keys)necessary for identification.

key-store 0..1 The key store information,including location, key storetype, and algorithm.

server 0..1 The server trust store. TLSconnections are made to trustedsystems - the public certificatesof trusted systems are stored ina keystore (called a trust store)and used to verify that theconnection made to a remotesystem really is the expectedidentity.

protocol-handler 0..1 Configures the global Javaprotocol handler by settingthe java.protocol.handler.pkgssystem property.

Endpoint

Attributes of <endpoint...>

Name Type Required Default Description

host string no

Page 177: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 177

port port number no

Inbound Endpoint

Attributes of <inbound-endpoint...>

Name Type Required Default Description

host string no

port port number no

Outbound Endpoint

Attributes of <outbound-endpoint...>

Name Type Required Default Description

host string no

port port number no

To configure the SSL connector:

<?xml version="1.0" encoding="UTF-8" ?> <mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ssl="http://www.mulesource.org/schema/mule/ssl/2.2" xsi:schemaLocation="http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/ssl/2.2 http://www.mulesource.org/schema/mule/ssl/2.2/mule-ssl.xsd"> <ssl:connector name="SslConnector" keepSendSocketOpen="true"> <ssl:client path="clientKeyStore" storePassword="mulepassword" /> <ssl:key-store path="serverKeystore" storePassword="mulepassword" keyPassword="mulepassword" /> <ssl:server path="trustStore" storePassword="mulepassword" /> </ssl:connector> <endpoint name="sendEndpoint" address="ssl://localhost:60198"/> ...

Note that you do not have to set sychronous="true", as endpoints using the SSL protocol aresynchronous by default.

To configure the TLS connector instead of the SSL connector, specify the tls namespace and schema,configure the connector, and then use the tls prefix for endpoints:

<?xml version="1.0" encoding="UTF-8" ?> <mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tls="http://www.mulesource.org/schema/mule/tls/2.2" xsi:schemaLocation="http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/tls/2.2

Page 178: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 178

http://www.mulesource.org/schema/mule/tls/2.2/mule-tls.xsd"> <tls:connector name="tlsConnector" keepSendSocketOpen="true"> <tls:client path="clientKeyStore" storePassword="mulepassword" /> <tls:key-store path="serverKeystore" storePassword="mulepassword" keyPassword="mulepassword" /> <tls:server path="trustStore" storePassword="mulepassword" /> </tls:connector> <tls:endpoint name="sendEndpoint" connector-ref="tlsConnector" address="tls://localhost:60198" synchronous="true" /> ...

Page 179: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 179

STDIO Transport

This page last changed on Feb 20, 2009 by jackie.wheeler.

STDIO Transport

The STDIO Transport allows the reading and writing of streaming data to Java's System.out andSystem.in objects for debugging.

Connector

Attributes of <connector...>

Name Type Required Default Description

messageDelayTime long no Delay inmillisecondsbefore printing theprompt to stdout.

outputMessage string no Text printed tostdout when amessage is sent.

promptMessage string no Text printed tostdout whenwaiting for input.

promptMessageCode string no Code used toretrieve promptmessage fromresource bundle.

outputMessageCode string no Code used toretrieve outputmessage fromresource bundle.

resourceBundle string no Resource bundleto provideprompt withpromptMessageCode.

To configure the STDIO connector:

<?xml version="1.0" encoding="UTF-8" ?> <mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:stdio="http://www.mulesource.org/schema/mule/stdio/2.2" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/stdio/2.2 http://www.mulesource.org/schema/mule/stdio/2.2/mule-stdio.xsd"> <stdio:connector name="stdioConnector" messageDelayTime="1234" outputMessage="abc" promptMessage="bcd" promptMessageCode="456" resourceBundle="dummy-messages" />

Page 180: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 180

<model name="model"> <service name="service"> <inbound> <stdio:inbound-endpoint name="in" system="IN" connector-ref="stdioConnector" /> </inbound> <outbound> <multicasting-router> <stdio:outbound-endpoint name="out" system="OUT" connector-ref="stdioConnector" /> <stdio:outbound-endpoint name="err" system="ERR" connector-ref="stdioConnector" /> </multicasting-router> </outbound> </service> </model> </mule>

Transformers

There are no built-in transformers for the STDIO transport.

Internationalizing Messages

If you are internationalizing your application, you can also internationalize the promptMessages andoutputMessages for the STDIO connector. (This assumes that you have already created a resource bundlethat contains your messages as described on that page.)

To internationalize, you must specify both the resourceBundle parameter and the promptMessageCodeand/or outputMessageCode parameters. The resourceBundle parameter will contain the key to theresource bundle itself. The promptMessageCode provides the key to the message in the bundle forthe prompt message. In the snippet above, the "dummy-messages" resource bundle means that theprompt message "456" will be expected in the bundle META-INF/services/org/mule/i18n/dummy-messages<langCode>.properties.

Page 181: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 181

TCP Transport

This page last changed on Mar 04, 2009 by jackie.wheeler.

TCP Transport

[ Connector ] [ Streaming Protocol ] [ Xml Protocol ] [ Xml Eof Protocol ] [ Eof Protocol ] [ Direct Protocol] [ Safe Protocol ] [ Length Protocol ] [ Custom Protocol ] [ Inbound Endpoint ] [ Outbound Endpoint ] [Endpoint ] [ Transformers ]

The TCP transport enables events to be sent and received over TCP sockets.

Connector

Connects Mule to a TCP socket to send or receive data via the network.

Child Elements of <connector...>

Name Cardinality Description

abstract-protocol 0..1 The class name for the protocolhandler. This controls how theraw data stream is convertedinto messages. By default,messages are constructedas dara is received, with nocorrection for multiple packetsor fragmentation. Typically,change this value, or usea transport that includes aprotocol like HTTP.

Streaming Protocol

TCP does not guarantee that data written to a socket is transmitted in a single packet, so if you want totransmit entire Mule messages reliably, you must specify an additional protocol. However, this is not anissue with streaming, so the streaming-protocol element is an alias for the "direct" (null) protocol.

Xml Protocol

TCP does not guarantee that data written to a socket is transmitted in a single packet, so if you wantto transmit entire Mule messages reliably, you must specify an additional protocol. The xml-protocolelement configures the XML protocol, which uses XML syntax to isolate messages from the stream ofbytes received, so it will only work with well-formed XML.

Xml Eof Protocol

Similar to xml-protocol, the xml-eof-protocol element configures the XML protocol, but it will also usesocket closure to terminate a message (even if the XML is not well-formed).

Eof Protocol

TCP does not guarantee that data written to a socket is transmitted in a single packet, so if you want totransmit entire Mule messages reliably, you must specify an additional protocol. The eof-protocol element

Page 182: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 182

configures a protocol that simply accumulates all data until the socket closes and places it in a singlemessage.

Attributes of <eof-protocol...>

Name Type Required Default Description

payloadOnly boolean no Sends only thepayload, notthe entire Mulemessage object orits properties. Thisdefaults to truewhen the protocolis not specifiedexplicitly (whenthe safe protocolis used).

Direct Protocol

TCP does not guarantee that data written to a socket is transmitted in a single packet. Using the direct-protocol element to configure the "null" protocol does not change the normal TCP behavior, so messagefragmentation may occur. For example, a single sent message may be received in several pieces, each asa separate received message. Typically, it is not a good choice for messaging within Mule, but it may benecessary to interface with external TCP-based protocols.

Attributes of <direct-protocol...>

Name Type Required Default Description

payloadOnly boolean no Sends only thepayload, notthe entire Mulemessage object orits properties. Thisdefaults to truewhen the protocolis not specifiedexplicitly (whenthe safe protocolis used).

Safe Protocol

Similar to length-protocol, safe-protocol also includes a prefix. Verification of the prefix allows mis-matched protocols to be detected and avoids interpreting "random" data as a message length (which maygive out-of-memory errors). This is the default protocol in Mule 2.x.

Attributes of <safe-protocol...>

Name Type Required Default Description

payloadOnly boolean no Sends only thepayload, not

Page 183: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 183

the entire Mulemessage object orits properties. Thisdefaults to truewhen the protocolis not specifiedexplicitly (whenthe safe protocolis used).

maxMessageLength integer no An optionalmaximum lengthfor the numberof bytes in asingle message.Messages largerthan this willtrigger an error inthe receiver, but itgive an assurancethat no out-of-memory error willoccur.

Length Protocol

The length-protocol element configures the length protocol, which precedes each message with thenumber of bytes sent so that an entire message can be constructed on the received.

Attributes of <length-protocol...>

Name Type Required Default Description

payloadOnly boolean no Sends only thepayload, notthe entire Mulemessage object orits properties. Thisdefaults to truewhen the protocolis not specifiedexplicitly (whenthe safe protocolis used).

maxMessageLength integer no An optionalmaximum lengthfor the numberof bytes in asingle message.Messages largerthan this willtrigger an error inthe receiver, but itgive an assurancethat no out-of-memory error willoccur.

Page 184: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 184

Custom Protocol

The custom-protocol element allows you to configure your own protocol implementation.

Attributes of <custom-protocol...>

Name Type Required Default Description

class class name no A class thatimplementsthe TcpProtocolinterface.

Inbound Endpoint

The inbound-endpoint element configures the endpoint on which the messages are received.

Attributes of <inbound-endpoint...>

Name Type Required Default Description

host string no The host of theTCP socket.

port port number no The port of theTCP socket.

Outbound Endpoint

The outbound-endpoint element configures the endpoint where the messages are sent.

Attributes of <outbound-endpoint...>

Name Type Required Default Description

host string no The host of theTCP socket.

port port number no The port of theTCP socket.

Endpoint

The endpoint element configures a global TCP endpoint definition.

Attributes of <endpoint...>

Name Type Required Default Description

host string no The host of theTCP socket.

Page 185: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 185

port port number no The port of theTCP socket.

Transformers

The following transformers are used by default for the TCP transport unless a transformer is explicitly seton the connector or service.

Transformer Description

ByteArrayToString Converts a byte array to a String

StringToByteArray Converts a String to a byte array

Page 186: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 186

UDP Transport

This page last changed on Feb 20, 2009 by jackie.wheeler.

UDP Transport

The UDP transport enables events to be sent and received as Datagram packets.

The Javadoc for this transport can be found here .

Connector

Attributes of <connector...>

Name Type Required Default Description

receiveBufferSize integer no The size of thereceiving bufferfor the socket.

receiveTimeout long no The amount oftime after whicha Receive call willtime out.

sendBufferSize integer no The size of thesending buffer forthe socket.

sendTimeout long no The amount oftime after which aSend call will timeout.

socketLinger long no The amount oftime the socketwill remain openafter a closesocketcall.

broadcast boolean no Whether to enablethe socket to sendbroadcast data.

keepSendSocketOpenboolean no Whether to keepthe Sendingsocket open.

Endpoints

You configure UDP endpoints just as you would with any other transport, with the following additionalattributes:

• host: the IP address of the server, such as www.mulesource.com, localhost, or 127.0.0.1• port: the port number of the server.

For example:

Page 187: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 187

<udp:inbound-endpoint host="${hostname}" port="61000" />

Message Payload

The default message payload of the UDP transport for incoming messages is a byte[] array.

Page 188: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 188

VM Transport

This page last changed on Feb 24, 2009 by jackie.wheeler.

VM Transport

The VM transport is used for intra-VM communication between components managed by Mule. Theconnector provides options for configuring VM transient or persistent queues.

The Javadoc for this transport can be found here .

Using VM Queues

When using a synchronous VM endpoint, messages are delivered in memory from one component toanother (asynchronous endpoints introduce a queue that threads can consume from). However, when thequeueEvents property is set, messages can be stored in arbitrary memory queues and consumed later byclients 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 thatshould queue messages must use a VM connector that has queueEvents enabled. You cannot set thequeueEvents property on the endpoint. For example:

<?xml version="1.0" encoding="UTF-8"?><mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.2" xmlns:test="http://www.mulesource.org/schema/mule/test/2.2" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/test/2.2 http://www.mulesource.org/schema/mule/test/2.2/mule-test.xsd http://www.mulesource.org/schema/mule/vm/2.2 http://www.mulesource.org/schema/mule/vm/2.2/mule-vm.xsd">

<vm:connector name="asynchVm" queueEvents="true"/> <model> <service name="myAsynchService"> <inbound> <vm:inbound-endpoint path="in" connector-ref="asynchVm"/> </inbound>

<test:component> <test:return-data>Polo</test:return-data> </test:component> <outbound> <outbound-pass-through-router> <vm:outbound-endpoint path="out" connector-ref="asynchVm"/> </outbound-pass-through-router> </outbound> </service> </model></mule>

Notice that the inbound endpoint explicitly tells Mule to use the asynchVm connector. Otherwise, Mule willlook for the first connector that matches the protocol for the endpoint.

Page 189: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 189

For more information on queues, see Configuring Queues.

Using Persistent Queues

A VM queue can be made persistent so that its state can be maintained between server shutdowns. Tomake VM queues persistent, you enable the persistent property in the queue profile on the model orservice.

Using Transactions

VM queues can take part in distributed XA transactions. To make a VM endpoint transactional, use thefollowing configuration:

<inbound> <vm:inbound-endpoint address="vm://dispatchInQueue" connector-ref="vmQueue"> <vm:transaction action="BEGIN_OR_JOIN"/> </vm:inbound-endpoint></inbound>

You must add a transaction manager to your configuration. For more information, see TransactionManagement.

Using VM with CXF

You can use the VM transport with CXF to take advantage of its support for web service integration. Tocreate a VM/CXF endpoint, declare the CXF schema and namespace, and then create the connector andendpoints as follows:

<cxf:connector name="cxf" defaultFrontend="simple"/> <model name="test"> <service name="mycomponent"> <inbound> <inbound-endpoint address="cxf:vm://mycomponent"/> </inbound> <component> <singleton-object class="org.mule.tck.testmodels.services.TestServiceComponent"/> </component> </service> <service name="httpBridge"> <inbound> <inbound-endpoint address="http://localhost:63081/test" synchronous="true"/> </inbound> <outbound> <outbound-pass-through-router> <outbound-endpoint address="vm://mycomponent"/> </outbound-pass-through-router> </outbound> </service> </model>

Transformers

There are no specific transformers for the VM transport.

Page 190: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 190

Configuration Reference

Following are the elements and attributes you can set for the VM transport.

Connector

Attributes of <connector...>

Name Type Required Default Description

queueEvents boolean no Determineswhether queuesshould be set upfor listeners onthe connector.If set to false,the connectorsimply forwardsmesssages tocomponents viathe Mule server.If it is set totrue, the queuesare configuredusing the queuingprofile.

queueTimeout positiveInteger no The timeoutsetting for thequeue.

Child Elements of <connector...>

Name Cardinality Description

queueProfile 0..1 DEPRECATED. USE "<queue-profile>" instead.

queue-profile 0..1 Configures the properties ofthis connector's queue (seeConfiguring Queues).

Inbound Endpoint

The endpoint on which this connector receives messages from the transport.

Attributes of <inbound-endpoint...>

Name Type Required Default Description

path string no The queuepath, such asdispatchInQueueto create the

Page 191: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 191

address vm://dispatchInQueue.

Outbound Endpoint

The endpoint to which this connector sends messages.

Attributes of <outbound-endpoint...>

Name Type Required Default Description

path string no The queuepath, such asdispatchInQueueto create theaddress vm://dispatchInQueue.

Endpoint

An endpoint "template" that can be used to construct an inbound or outbound endpoint elsewhere in theconfiguration by referencing the endpoint name.

Attributes of <endpoint...>

Name Type Required Default Description

path string no The queuepath, such asdispatchInQueueto create theaddress vm://dispatchInQueue.

Transaction

The transaction element configures a transaction. Transactions allow a series of operations to be groupedtogether so that they can be rolled back if a failure occurs. For more information, see TransactionManagement.

Page 192: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 192

WSDL Transport

This page last changed on Feb 20, 2009 by jackie.wheeler.

WSDL Transport

[ Generic WSDL Endpoints ] [ Transformers ] [ Specifying an Alternate WSDL Location ] [ Example of theCXF WSDL Endpoint ]

The WSDL transport can be used to for invoking remote web services by obtaining the service WSDL.Mule will create a dynamic proxy for the service and then invoke it.

The Javadoc for this transport can be found here for the Axis version and here for the CXF version.

Generic WSDL Endpoints

A WSDL endpoint enables you to easily invoke web services without generating a client. At startup, itreads the WSDL to determine how to invoke the remote web service during runtime. When a message issent through the WSDL endpoint, it is able to construct a SOAP message using the message payload andits knowledge of the expected payload format from the WSDL.

You must provide the full URL to the WSDL of the service to invoke, and you must supply a 'method'parameter that tells Mule which operation to invoke on the service:

wsdl:http://www.webservicex.net/stockquote.asmx?WSDL&method=GetQuote

The WSDL URL is prepended with the wsdl: prefix. Mule checks your class path to see if there is a WSDLprovider that it can use to create a client proxy from the WSDL. Mule supports both Axis and CXF asWSDL providers. If you want to use a specific one, you can specify it on the URL as follows:

wsdl-cxf:http://www.webservicex.net/stockquote.asmx?WSDL&method=GetQuote

or

wsdl-axis:http://www.webservicex.net/stockquote.asmx?WSDL&method=GetQuote

In general, you should use the CXF WSDL endpoint. The one limitation of the CXF WSDL provider isthat it does not allow you to use non-Java primitives (objects that are not a String, int, double, and soon). Sometimes the Axis WSDL generation will not work (incorrect namespaces are used), so you canexperiment with each one to see which works best.

Transformers

There are no specific transformers to set on WSDL endpoints.

Specifying an Alternate WSDL Location

By default, the WSDL provider will look for your WSDL by taking the endpoint address and appending?wsdl to it. With the CXF transport, you have the option of specifying a location for the WSDL that isdifferent from that specified with the ?wsdl parameter. This may be useful in cases where the WSDL isn'tavailable the normal way, either because the SOAP engine doesn't provide it or the provider does notwant to expose the WSDL publicly.

Page 193: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 193

In these cases, you can specify the wsdlLocation property of the CXF endpoint as follows:

<endpoint address="wsdl-cxf:http://localhost:8080/book/services/BookService?method=getBooks"> <properties> <property name="wsdlLocation" value="file:///c:/BookService.wsdl"/> </properties></endpoint>

In this case, the WSDL CXF endpoint works as it normally does, except that it reads the WSDL from thelocal drive.

Example of the CXF WSDL Endpoint

This example demonstrates how to take multiple arguments from the console, invoke a web service, andprint the output to the screen. It uses the Currency Convertor web service on www.webservicex.net.

This service requires two arguments: the "from" currency code and the "to" currency code. When the CXFdispatcher prepares arguments for the invocation of the service, it expects to find a message payload ofObject[] - that is, an Object array. In the case of the Currency Convertor, this should be an array of twoObjects - the "from" currency and the "to" currency.

There are several ways to construct this object array, but the easiest way is to use the customtransformer StringToObjectArrayTransformer , which translates a delimited String into an Object array. Inthe example below, you simply type in a String in the format of <fromCurrency>,<toCurrency>.

<?xml version="1.0" encoding="UTF-8"?><mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd">

<model name="sample">

<service name="inputService"> <inbound> <inbound-endpoint address="stdio://System.in?promptMessage=Enter from and to currency symbols, separated by a comma:" synchronous="true"> <transformers> <!-- Convert the input to an object array --> <custom-transformer class="org.mule.transformer.simple.StringToObjectArray"> <spring:property name="delimiter" value=","/> </custom-transformer> </transformers> </inbound-endpoint> </inbound> <outbound> <chaining-router> <outbound-endpoint address="wsdl-cxf:http://www.webservicex.net/CurrenyConvertor.asmx?WSDL&amp;method=ConversionRate" synchronous="true"/> <outbound-endpoint address="stdio://System.out"/> </chaining-router> </outbound>

Page 194: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 194

</service> </model></mule>

For example, type "EUR,USD" to get the conversion rate for Euros to US Dollars, and you'll get somethinglike this:

Enter from and to currency symbols, separated by a comma:EUR,USD1.3606

Page 195: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 195

XMPP Transport

This page last changed on Feb 20, 2009 by jackie.wheeler.

XMPP Transport

[ Inbound Endpoint ] [ Outbound Endpoint ] [ Endpoint ] [ Transformers ] [ Filters ]

The XMPP transport enables the XMPP (Jabber) instant messaging protocol. The XMPPS connectorprovides a secure implementation.

The Javadoc for the XMPP transport can be found here .

Inbound Endpoint

The endpoint on which this connector receives messages from the transport.

Attributes of <inbound-endpoint...>

Name Type Required Default Description

user string no The user name touse to connect tothe XMPP server.

password string no The password touse with the username.

host string no The host ofthe XMPPserver, such aswww.mulesource.com,localhost, or127.0.0.1.

port port number no The port numberof the XMPPserver, such as5222.

recipient string no The ID ofthe intendedrecipient of themessages, such [email protected].

groupChat boolean no Whether to start agroup chat.

nickname string no The user'snickname.

resource string no The resourceportion of theaddress, suchas user@host/resource ordomain/resource.

Page 196: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 196

thread string no The threadto which themessage belongs.

to string no The user to whomthe message wassent.

from string no The user who sentthe message.

Outbound Endpoint

The endpoint to which this connector sends messages.

Attributes of <outbound-endpoint...>

Name Type Required Default Description

user string no The user name touse to connect tothe XMPP server.

password string no The password touse with the username.

host string no The host ofthe XMPPserver, such aswww.mulesource.com,localhost, or127.0.0.1.

port port number no The port numberof the XMPPserver, such as5222.

recipient string no The ID ofthe intendedrecipient of themessages, such [email protected].

groupChat boolean no Whether to start agroup chat.

nickname string no The user'snickname.

resource string no The resourceportion of theaddress, suchas user@host/resource ordomain/resource.

Page 197: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 197

thread string no The threadto which themessage belongs.

to string no The user to whomthe message wassent.

from string no The user who sentthe message.

Endpoint

An endpoint "template" that can be used to construct an inbound or outbound endpoint elsewhere in theconfiguration by referencing the endpoint name.

Attributes of <endpoint...>

Name Type Required Default Description

user string no The user name touse to connect tothe XMPP server.

password string no The password touse with the username.

host string no The host ofthe XMPPserver, such aswww.mulesource.com,localhost, or127.0.0.1.

port port number no The port numberof the XMPPserver, such as5222.

recipient string no The ID ofthe intendedrecipient of themessages, such [email protected].

groupChat boolean no Whether to start agroup chat.

nickname string no The user'snickname.

resource string no The resourceportion of theaddress, suchas user@host/resource ordomain/resource.

Page 198: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 198

thread string no The threadto which themessage belongs.

to string no The user to whomthe message wassent.

from string no The user who sentthe message.

You configure the XMPP connector as follows:

<?xml version="1.0" encoding="UTF-8"?><mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:xmpp="http://www.mulesource.org/schema/mule/xmpp/2.2" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/xmpp/2.2 http://www.mulesource.org/schema/mule/xmpp/2.2/mule-xmpp.xsd">

<xmpp:endpoint name="noNicknameEndpoint" host="localhost" port="1234" user="mule" password="secret" recipient="recipient" groupChat="true"/>

</mule>

If you want to use secure XMPP, specify the xmpps namespace instead, specifying the schema as follows,and then use the xmpps prefix on the endpoints:

http://www.mulesource.org/schema/mule/xmpps/2.2 http://www.mulesource.org/schema/mule/xmpps/2.2/mule-xmpps.xsd

Transformers

There are two transformers provided with the XMPP transport:

Transformer Description

org.mule.transport.xmpp.transformers.XmppPacketToStringConverts an XMPP Packet to a String, returning ajava.lang.String object.

org.mule.transport.xmpp.transformers.ObjectToXmppPacketAccepts a String or an XMPP Packet and returnsan XMPP Packet. This transformer doesn't acceptall objects, only Strings and XMPP Packets.

Filters

There are several filters in the org.mule.transport.xmpp.filters package that filter XMPP messages.AbstractXmppFilter is an abstract filter adapter that allows Smack filters to be configured as Mulefilters. The following filter classes extend the abstract filter:

Page 199: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 199

• XmppAndFilter• XmppFromContainsFilter• XmppMessageTypeFilter• XmppNotFilter• XmppOrFilter• XmppPacketIDFilter• XmppPacketTypeFilter• XmppThreadFilter• XmppToContainsFilter

Page 200: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 200

Bootstrapping the Registry

This page last changed on Feb 09, 2009 by jackie.wheeler.

Bootstrapping the Registry

Mule provides a mechanism for adding objects to the Mule registry as soon as a module or transport isloaded. This is useful for registering shared transformers or expression evaluators.

All objects you add to the registry using this mechanism must have a default constructor. They canimplement injection interfaces such as org.mule.MuleContextAware and lifecycle interfaces such asorg.mule.api.lifecycle.Initialisable .

Specifying the Objects to Bootstrap

To load an object into the Mule registry using the bootstrap mechanism, you specify the object in theproperties file registry-bootstrap.properties, which you then store in the META-INF directory for thetransport or module. For example:

src/main/resources/META-INF/services/org/mule/config/registry-bootstrap.properties

Each entry in the registry-bootstrap.properties file is a simple key/value pair that defines theobject:

myobject=org.foo.MyObject

If this file is in a module or transport's META-INF directory, Mule will register an instance oforg.foo.MyObject with a key of 'myobject' into the local registry when that module or transport isloaded.

If you want to ensure that the object gets a unique ID in the local registry, you can use object.n for thekey, where n is a sequential number:

object.1=org.foo.MyObjectobject.2=org.bar.MyObject

Adding Transformers

When adding transformers, you can also define the returnClass and name of the transformer asparameters:

transformer.1=org.mule.transport.jms.transformers.JMSMessageToObject,returnClass=byte[]transformer.2=org.mule.transport.jms.transformers.JMSMessageToObject,returnClass=java.lang.String, name=JMSMessageToStringtransformer.3=org.mule.transport.jms.transformers.JMSMessageToObject,returnClass=java.util.Hashtable)

Note that the key used for transformers must be transformer.n where n is a sequential number.

Page 201: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 201

If the transformer name is not specified, Mule will automatically generate the name as JMSMessageToXXXwhere XXX is the return class name, such as JMSMessageToString. If no returnClass is specified, thedefault value in the transformer will be used.

Page 202: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 202

Choosing the Right Topology

This page last changed on Nov 25, 2008 by jackie.wheeler.

Choosing the Right Topology

[ About Clustering ] [ JMS Queues ] [ Load Balancers ] [ Maintaining State in a Database ] [ HandlingStateful Components ] [ Example Architectures ] [ Related Topics ]

As you build your Mule application, it is important to think critically about how best to architect yourapplication to achieve the desired availability, fault tolerance, and performance characteristics. This pageoutlines some of the solutions for achieving the right blend of these characteristics through clusteringand other techniques. There is no one correct approach for everyone, and designing your system is bothan art and a science. If you need more assistance, MuleSource Professional Services can help you byreviewing your architecture plan or designing it for you. For more information, contact us.

About Clustering

Clustering an application is useful for achieving the following:

• High availability (HA): Making your system continually available in the event that one or moreservers or a data center fails.

• Fault tolerance (FT): The ability to recover from failure of an underlying component. Typically, therecovery is achieved through transaction rollback or compensating actions.

This page describes several possible clustering solutions. Please note that as of the current release,MuleSource does not support any specific clustering solution, although many users have successfully setup Mule in a clustered environment.

JMS Queues

JMS can be used to achieve HA & FT by routing messages through JMS queues. In this case, eachmessage is routed through a JMS queue whenever it moves from component to component.

Pros:

• Easy to do• Well understood by developers

Cons:

• Requires lots of transactions, and transactions can be complicated• Performance hit if you're using XA

Load Balancers

Load balancers simply route requests to different servers based on the the current load of each serverand which servers are currently up. Load balancers can be software or hardware based. This approach iscommonly used with clustered databases (see below).

Page 203: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 203

Pros:

• Straightforward to do• Well understood by developers

Cons:

• Not a complete solution on its own, doesn't provide fault tolerance.

Maintaining State in a Database

If you have a clustered database, one option for your application is to simply store all state in thedatabase and rely on it to replicate the data consistently across servers.

Pros:

• Straightforward to do• Well understood by developers

Cons:

• Not all state is amenable to being stored in the database

Handling Stateful Components

While most applications can be supported by the above techniques, some require sharing state betweenJVMs more deeply.

One common example of this is an aggregator component. For example, assume you have an aggregatorthat is aggregating messages from two different producers. Producer #1 sends a message to theaggregator, which receives it and holds it in memory until Producer #2 sends a message.

Producer #1 ---> |----------| |Aggregator| --> Some other componentProducer #2 ---> |----------|

If the server with the aggregator goes down between Producer #1 sending a message and Producer #2sending a message, Producer #2 can't just send its message to a different server because that server willnot have the message from Producer #1.

The solution to this is to share the state of the aggregator component across different machines throughclustering software such as Terracotta, Tangosol Coherence, JGroups, etc. By using one of these tools,Producer #2 can simply fail over to a different server. Note that MuleSource has not tested Mule withthese tools and does not officially support them.

Pros:

• Works for all clustering cases• Can work as a cache as well

Cons:

• Not officially supported by MuleSource• Requires performance tuning to get things working efficiently

Page 204: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 204

Example Architectures

HTTP + JMS Queues

In this example architecture, HTTP requests come in through a load balancer and are immediately put ona JMS queue. The JMS queue is clustered between the different servers. A server will start processing amessage off the JMS queue and wrap everything in a transaction.

If the server goes down, the transaction will roll back and another server will pick up the message andstart processing it.

Note: If the HTTP connection is open for the duration of this process, this approach will not work, as theload balancer will not transparently switch connections between servers. In this case, the HTTP client willneed to retry the request.

Terracotta

Terracotta is an open source JVM clustering technology. It is able to replicate the state of yourcomponents across JVMs. In this example architecture, there is a load balancer that is proxying requestsbetween multiple servers.

If one of the servers goes down, the load balancer automatically routes requests to a server that is up.Because all the state of your components is shared between the different servers, your internal processcan continue on another server.

Page 205: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 205

Note: If the HTTP connection is open for the duration of this process, this approach will not work, as theload balancer will not transparently switch connections between servers. In this case, the HTTP client willneed to retry the request.

Related Topics

As you design your topology, there are several other topics to keep in mind that are beyond the scope ofthis documentation:

• Maintaining geo-distributed clusters• Data partitioning• ACID vs. BASE transactions• Compensation and transactions

Page 206: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 206

Configuration Overview

This page last changed on Feb 24, 2009 by jackie.wheeler.

Configuration Overview

[ Configuration Files ] [ Configuration Builders ] [ Accessing the Configuration Programmatically ] [Configuring System Properties ]

By default, Mule starts up with a simple configuration in which only some system-level services areconfigured. You must configure services, transports, and the rest of the elements required for yourapplication. Following is an overview of configuration in Mule.

Configuration Files

In most cases, you will configure Mule using XML files. These files are based on Spring and make it veryeasy to set up your Mule instance in a short time. For complete information on setting the options in theconfiguration file, see XML Configuration.

When you start Mule from the command line, you simply specify the configuration file(s) with the -config parameter:

mule -config foo-config.xml

mule -config foo-config.xml,bar-config.xml

If you want to start Mule by calling it from your code, you specify the configuration file as a parameter tothe ConfigurationBuilder:

MuleContext context = new DefaultMuleContextFactory().createMuleContext(new SpringXmlConfigurationBuilder("foo-config.xml"));context.start();

If you have multiple configuration files, you can also import them into one configuration file so that youonly have to specify one configuration file at the command line or from your code. For example:

<?xml version="1.0" encoding="UTF-8"?><mule xmlns=http://www.mulesource.org/schema/mule/core/2.2 ....> <spring:beans> <spring:import resource="mule-sub-config1.xml" /> <spring:import resource="mule-sub-config2.xml" /> </spring:beans>...

Configuration Builders

The configuration builder is responsible for creating the configuration that's used at run time from theconfiguration files you provide. Mule provides two standard configuration builders, or you can create yourown.

Page 207: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 207

SpringXmlConfigurationBuilder

The default configuration builder used to configure Mule is the SpringXmlConfigurationBuilder. Thisconfiguration builder uses Spring 2.0 to configure Mule based on one or more XML files leveraging customMule namespaces. For more information, see XML Configuration.

ScriptConfigurationBuilder

This configuration builder allows a JSR-223 compliant script engine (e.g., Groovy, Jython) to configureMule. For more information, see Scripting Module.

Custom Configuration Builders

You can easily create your own custom configuration builder by implementing the ConfigurationBuilderinterface, which has a method configure. Typically, you call configure(MuleContextmuleContext.getRegistry()) to get access to Mule's internal registry, which contains the configurationinformation, and to register services and other elements.

In most cases, you will want to inherit from the class AbstractResourceConfigurationBuilder , whichwill make any configuration files specified on the command line available in an instance variable calledconfigResources.

Specifying the Configuration Builder

SpringXmlConfigurationBuilder is the default configuration builder. If you want to use anotherconfiguration builder, you can specify it on the command line at startup with the -builder parameter:

mule -builder org.mule.module.scripting.builders.ScriptConfigurationBuilder -config mule-config.groovy

You can also specify the configuration builder as a parameter to the MuleContextFactory when startingMule programatically:

MuleContext context = new DefaultMuleContextFactory().createMuleContext(new ScriptConfigurationBuilder("mule-config.groovy"));context.start();

Accessing the Configuration Programmatically

All Mule configuration is accessible from a single object: org.mule.api.config.MuleConfiguration .Configurations in a MuleConfiguration are set when a MuleContext is created. The object becomesimmutable after it is started and can be accessed using the following:

MuleContext context = MuleServer.getMuleContext();MuleConfiguration configuration = context.getConfiguration();

Configuring System Properties

There are several system properties that are immutable after startup, such as the server ID. Tospecify these properties, you can use the -M-Dmule.<propertyName> command (such as -M-Dmule.serverId=YOUR_MULE_SERVER_ID) or by setting -Dmule.<propertyName> in wrapper.conf if youare running Mule from the command line. To set these properties programmatically, you customize the

Page 208: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 208

MuleConfiguration using the set method for the property (such as setId for the system ID), create aMuleContextBuilder, load the configuration to the builder, and then create the context from the builder.

For example:

SpringXmlConfigurationBuilder configBuilder = new SpringXmlConfigurationBuilder("my-config.xml");DefaultMuleConfiguration muleConfig = new DefaultMuleConfiguration();muleConfig.setId("MY_SERVER_ID");MuleContextBuilder contextBuilder = new DefaultMuleContextBuilder();contextBuilder.setMuleConfiguration(muleConfig);MuleContextFactory contextFactory = new DefaultMuleContextFactory();MuleContext muleContext = contextFactory.createMuleContext(configBuilder, contextBuilder);muleContext.start();

For more information on the system properties you can set programmatically, seeDefaultMuleConfiguration .

Page 209: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 209

Configuration Reference

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

Configuration Reference

• Global Settings Configuration Reference• Model Configuration Reference• Service Configuration Reference• Endpoint Configuration Reference• Routers

° Inbound Router Configuration Reference° Outbound Router Configuration Reference° Asynchronous Reply Router Configuration Reference° Catch All Strategy Configuration Reference

• Filters Configuration Reference• Transformers Configuration Reference• Component Configuration Reference• Entry Point Resolver Configuration Reference• Exception Strategy Configuration Reference• Properties Configuration Reference• Notifications Configuration Reference• Transactions Configuration Reference• Expressions Configuration Reference

For configuration reference on transports, see Available Transports. For modules, see Using Mule Modules.

For transports and modules contributed by the community, see MuleForge Active Projects.

Page 210: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 210

Asynchronous Reply Router Configuration Reference

This page last changed on Feb 20, 2009 by jackie.wheeler.

Asynchronous Reply Router ConfigurationReference

This page provides details on the elements you configure for asynchronous reply routers. This informationis pulled directly from mule.xsd and is cached. If the information appears to be out of date, refresh thepage. For more information on routers, see Using Message Routers.

<single-async-reply-router ...>

Configures a Single Response Router. This will return the first message it receives on a reply endpoint andwill discard the rest.

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

abstract-inbound-endpoint

0..* The endpoint usedto receive theresponse(s) on.

A placeholder forinbound endpointelements. Inboundendpoints receivemessages fromthe underlyingtransport. Themessage payloadis then deliveredto the componentfor processing.

abstract-message-info-mapping

0..1 The message infomapper used toextract key bitsof the messageinformation, suchas Message ID orCorrelation ID.these propertiesare used bysome routersand this mappinginformation tellsMule where to getthe informationfrom in thecurrent message.

Page 211: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 211

Maps theattributes of thecurrent messageto known messageelements inMule, namelyMessage ID andCorrrelationID.

<collection-async-reply-router ...>

Configures a Collection Response Router. This will return a MuleMessageCollection message type that willcontain all messages received for the current correlation.

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

abstract-inbound-endpoint

0..* The endpoint usedto receive theresponse(s) on.

A placeholder forinbound endpointelements. Inboundendpoints receivemessages fromthe underlyingtransport. Themessage payloadis then deliveredto the componentfor processing.

abstract-message-info-mapping

0..1 The message infomapper used toextract key bitsof the messageinformation, suchas Message ID orCorrelation ID.these propertiesare used bysome routersand this mappinginformation tellsMule where to getthe informationfrom in thecurrent message.

Maps theattributes of thecurrent messageto known messageelements in

Page 212: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 212

Mule, namelyMessage ID andCorrrelationID.

<custom-async-reply-router ...>

Attributes

Name Type Required Default Description

class class name no A fully qualifiedJava class name ofthe router to use.The router shouldeither extend{{org.mule.routing.response.AbstractResponseRouter}}or{{org.mule.routing.response.AbstractResponseAggregator}}.

Child Elements

Name Cardinality Description

abstract-inbound-endpoint 0..* The endpoint used to receive theresponse(s) on.

A placeholder for inboundendpoint elements. Inboundendpoints receive messagesfrom the underlying transport.The message payload is thendelivered to the component forprocessing.

abstract-message-info-mapping 0..1 The message info mapperused to extract key bits of themessage information, such asMessage ID or Correlation ID.these properties are used bysome routers and this mappinginformation tells Mule where toget the information from in thecurrent message.

Maps the attributes of thecurrent message to knownmessage elements in Mule,namely Message ID andCorrrelationID.

spring:property 0..* Spring-style property elementsso that custom configuration canbe configured on the customrouter.

Page 213: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 213

Catch All Strategy Configuration Reference

This page last changed on Feb 20, 2009 by jackie.wheeler.

Catch All Strategy Configuration Reference

This page provides details on the elements you configure for catch-all strategies. This information ispulled directly from mule.xsd and is cached. If the information appears to be out of date, refresh thepage.

<logging-catch-all-strategy ...>

Does nothing with the message but simply logs (using the WARN log level) the fact that the message wasnot dispatched because no routing path was defined.

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

<custom-catch-all-strategy ...>

Attributes

Name Type Required Default Description

class class name no Fully qualifiedclass name of thecustom catch-all strategy to beused.

Child Elements

Name Cardinality Description

spring:property 0..*

<forwarding-catch-all-strategy ...>

Forwards the message to the specified endpoint if no outbound routers match.

Page 214: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 214

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

abstract-outbound-endpoint

0..* A placeholder foroutbound endpointelements.Outboundendpoints dispatchmessages tothe underlyingtransport.

<custom-forwarding-catch-all-strategy ...>

Attributes

Name Type Required Default Description

class class name no Fully qualifiedclass name of thecustom forwardingcatch-all strategyto be used.

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 0..* A placeholder for outboundendpoint elements. Outboundendpoints dispatch messages tothe underlying transport.

spring:property 0..*

Page 215: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 215

Component Configuration Reference

This page last changed on Feb 20, 2009 by jackie.wheeler.

Component Configuration Reference

This page provides details on the elements you configure for components. This information is pulleddirectly from mule.xsd and is cached. If the information appears to be out of date, refresh the page. Formore information on components, see Configuring Components.

<component ...>

A simple POJO (Plain Old Java Object) component that will be invoked by Mule when a message isreceived. The class or object instance to be used can be specified using a child object factory element,or via the 'class' attribute. If the 'class' attribute is used, an object factory cannot be configured as well.Using the 'class' attribute is equivilant to using the propotype object factory ('prototype-object' childelement).

Attributes

Name Type Required Default Description

class class name no Specifies acomponent class.This is a shortcutthat is equivalentto providing a'prototype-object'element.

Child Elements

Name Cardinality Description

abstract-interceptor 1..1 A placeholder for an interceptorelement.

interceptor-stack 1..1 A reference to a stack ofintereceptors defined globally.

abstract-object-factory 0..1 Object factory used to obtainthe object instance that willbe used for the componentimplementation. The objectfactory is responsible for objectcreation and may implementdifferent patterns, such assingleton or prototype, or lookup an instance from other objectcontainers.

abstract-lifecycle-adapter-factory

0..1

binding 0..* A binding associates a Muleendpoint with an injected Java

Page 216: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 216

interface. This is like usingSpring to inject a bean, butinstead of calling a method onthe bean, a message is sent toan endpoint.

abstract-entry-point-resolver-set 0..1 A placeholder for entry pointresolver set elements. Thesecombine a group of entry pointresolvers, trying them in turnuntil one succeeds.

abstract-entry-point-resolver 0..1 A placeholder for an entry pointresolver element. Entry pointresolvers define how payloadsare delivered to Java code bychoosing the method to call.

<pooled-component ...>

A pooled POJO (Plain Old Java Object) component that will be invoked by Mule when a message isreceived. The instance can be specified via a factory or a class.

Attributes

Name Type Required Default Description

class class name no Specifies acomponent class.This is a shortcutthat is equivalentto providing a'prototype-object'element.

Child Elements

Name Cardinality Description

abstract-interceptor 1..1 A placeholder for an interceptorelement.

interceptor-stack 1..1 A reference to a stack ofintereceptors defined globally.

abstract-object-factory 0..1 Object factory used to obtainthe object instance that willbe used for the componentimplementation. The objectfactory is responsible for objectcreation and may implementdifferent patterns, such assingleton or prototype, or lookup an instance from other objectcontainers.

abstract-lifecycle-adapter-factory

0..1

Page 217: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 217

binding 0..* A binding associates a Muleendpoint with an injected Javainterface. This is like usingSpring to inject a bean, butinstead of calling a method onthe bean, a message is sent toan endpoint.

abstract-entry-point-resolver-set 0..1 A placeholder for entry pointresolver set elements. Thesecombine a group of entry pointresolvers, trying them in turnuntil one succeeds.

abstract-entry-point-resolver 0..1 A placeholder for an entry pointresolver element. Entry pointresolvers define how payloadsare delivered to Java code bychoosing the method to call.

abstract-pooling-profile 0..1 Characteristics of the objectpool.

<pooling-profile ...>

A pooling profile is used to configure the pooling behaviour of Mule components. Each component canhave its own pooling profile.

Attributes

Name Type Required Default Description

maxActive string no Controls themaximumnumber of Mulecomponents thatcan be borrowedfrom a sessionat one time.When set to anegative value,there is no limitto the number ofcomponents thatmay be active atone time. WhenmaxActive isexceeded, thepool is said to beexhausted.

maxIdle string no Controls themaximumnumber of Mulecomponents thatcan sit idle in thepool at any time.When set to anegative value,there is no limit

Page 218: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 218

to the number ofMule componentsthat may be idleat one time.

initialisationPolicy INITIALISE_NONE/

INITIALISE_ONE/

INITIALISE_ALL

no INITIALISE_ONE Determines howcomponents ina pool shouldbe initialized.The possiblevalues are:INITIALISE_NONE(will not loadany componentsinto the poolon startup),INITIALISE_ONE(will load oneinitial componentinto the poolon startup), orINITIALISE_ALL(will load allcomponents in thepool on startup)

exhaustedActionWHEN_EXHAUSTED_GROW/

WHEN_EXHAUSTED_WAIT/

WHEN_EXHAUSTED_FAIL

no WHEN_EXHAUSTED_GROWSpecifies thebehavior of theMule componentpool when thepool is exhausted.Possiblevalues are:"WHEN_EXHAUSTED_FAIL",which will throw aNoSuchElementException,"WHEN_EXHAUSTED_WAIT",which will blockby invokingObject.wait(long)until a new oridle object isavailable, orWHEN_EXHAUSTED_GROW,which will create anew Mule instanceand returnit, essentiallymaking maxActivemeaningless. If apositive maxWaitvalue is supplied,it will block for atmost that manymilliseconds,after which aNoSuchElementExceptionwill be thrown. IfmaxThreadWaitis a negativevalue, it will blockindefinitely.

Page 219: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 219

maxWait string no Specifies thenumber ofmilliseconds towait for a pooledcomponent tobecome availablewhen the pool isexhausted and theexhaustedActionis set toWHEN_EXHAUSTED_BLOCK.

Child Elements

Name Cardinality Description

<bridge-component ...>

Transfers a message from inbound to outbound endpoints. This element is provided for backwardcompatibility - it is equivalent to not specifying any component.

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

abstract-interceptor

1..1 A placeholder foran interceptorelement.

interceptor-stack 1..1 A referenceto a stack ofintereceptorsdefined globally.

<echo-component ...>

Logs the message and returns the payload as the result.

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

abstract-interceptor

1..1 A placeholder foran interceptorelement.

Page 220: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 220

interceptor-stack 1..1 A referenceto a stack ofintereceptorsdefined globally.

<log-component ...>

Logs the message content (or content length if it is a large message).

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

abstract-interceptor

1..1 A placeholder foran interceptorelement.

interceptor-stack 1..1 A referenceto a stack ofintereceptorsdefined globally.

<null-component ...>

Throws an exception if it receives a message.

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

abstract-interceptor

1..1 A placeholder foran interceptorelement.

interceptor-stack 1..1 A referenceto a stack ofintereceptorsdefined globally.

<spring-object ...>

Object factory used to obtain Spring bean instances. This object factory does not create any instances butrather looks them up from Spring.

Page 221: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 221

Attributes

Name Type Required Default Description

bean name (no spaces) no Name of Springbean to look up.

Child Elements

Name Cardinality Description

property 0..* Sets a Mule property. This is aname/value pair that can be seton components, services, etc.,and which provide a genericway of configuring the system.Typically, you shouldn't need touse a generic property like this,since almost all functionalityis exposed via dedicatedelements. However, it can beuseful in configuring obscureor overlooked options and inconfiguring transports from thegeneric endpoint elements.

properties 0..1 A map of Mule properties.

<singleton-object ...>

Object factory that creates and always returns a singleton object instance.

Attributes

Name Type Required Default Description

class class name no Class name

Child Elements

Name Cardinality Description

property 0..* Sets a Mule property. This is aname/value pair that can be seton components, services, etc.,and which provide a genericway of configuring the system.Typically, you shouldn't need touse a generic property like this,since almost all functionalityis exposed via dedicatedelements. However, it can beuseful in configuring obscureor overlooked options and in

Page 222: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 222

configuring transports from thegeneric endpoint elements.

properties 0..1 A map of Mule properties.

<prototype-object ...>

Object factory that creates and returns a new 'prototype' object instance every time it is called.

Attributes

Name Type Required Default Description

class class name no Class name

Child Elements

Name Cardinality Description

property 0..* Sets a Mule property. This is aname/value pair that can be seton components, services, etc.,and which provide a genericway of configuring the system.Typically, you shouldn't need touse a generic property like this,since almost all functionalityis exposed via dedicatedelements. However, it can beuseful in configuring obscureor overlooked options and inconfiguring transports from thegeneric endpoint elements.

properties 0..1 A map of Mule properties.

<custom-lifecycle-adapter-factory ...>

Attributes

Name Type Required Default Description

class class name no Animplementationof theLifecycleAdapterinterface.

Page 223: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 223

Child Elements

Name Cardinality Description

<binding ...>

A binding associates a Mule endpoint with an injected Java interface. This is like using Spring to inject abean, but instead of calling a method on the bean, a message is sent to an endpoint.

Attributes

Name Type Required Default Description

interface class name no The interfaceto be injected.A proxy will becreated thatimplements thisinterface bycalling out to theendpoint.

method no The method onthe interfacethat should beused. This canbe omitted if theinterface has asingle method.

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 1..* A placeholder for outboundendpoint elements. Outboundendpoints dispatch messages tothe underlying transport.

Interceptors

See Using Interceptors.

Entry Point Resolvers

See Entry Point Resolver Configuration Reference.

Page 224: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 224

Endpoint Configuration Reference

This page last changed on Feb 20, 2009 by jackie.wheeler.

Endpoint Configuration Reference

This page provides details on the elements you configure for endpoints. This information is pulled directlyfrom mule.xsd and is cached. If the information appears to be out of date, refresh the page. For moreinformation on endpoints, see Configuring Endpoints.

<inbound-endpoint ...>

An inbound endpoint receives messages via the associated transport. As with global endpoints, eachtransport implements its own inbound endpoint element.

Attributes

Name Type Required Default Description

name name (no spaces) no Identifies theendpoint in theregistry. There isno need to set the'name' attributeon inboundor outboundendpoints, only onglobal endpoints.

ref name (no spaces) no A reference to aglobal endpoint,which is usedas a templateto constructthis endpoint. Atemplate fixes theaddress (protocol,path, host, etc.),and may specifyinitial values forvarious properties,but furtherproperties can bedefined locally (aslong as they donot change theaddress in anyway).

address string no The genericaddress for thisendpoint. If thisattribute is used,the protocol mustbe specified aspart of the URI.Alternatively,most transportsprovide their own

Page 225: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 225

attributes forspecifying theaddress (path,host, etc.). Notethat the addressattribute cannotbe combined with'ref' or with thetransport-providedalternativeattributes.

synchronous boolean no If true, theresult from thecomponentprocessing theincoming messagewill be returned asa response.

responseTimeout integer no The timeoutfor a responseif making asynchronousendpoint call

encoding string no String encodingused formessages.

connector-ref name (no spaces) no The name ofthe connectorassociated withthis endpoint. Thismust be specifiedif more thanone connector isdefined for thistransport.

transformer-refs list of names no A list of thetransformers thatwill be applied(in order) to themessage before itis delivered to thecomponent.

responseTransformer-refs

list of names no A list of thetransformers thatwill be applied(in order) to thesynchronousresponse before itis returned via thetransport.

Page 226: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 226

Child Elements

Name Cardinality Description

abstract-transaction 0..1 A placeholder for transactionelements. Transactions allowa series of operations to begrouped together.

abstract-filter 0..1 A placeholder for filter elements,which control which messagesare handled.

abstract-security-filter 0..1 A placeholder for security filterelements, which control accessto the system.

abstract-retry-policy 0..1 A placeholder for a retry policyelement. Retry policies definehow Mule should retry a failedmessage send/dispatch/request.

abstract-multi-transaction 0..1 A placeholder for multi-transaction elements. Multi-transactions allow a seriesof operations to be groupedtogether spanning differenttransports, e.g. JMS and JDBC,but without the overhead ofXA. The trade-off is that XAreliability guarantees aren'tavailable, and services mustbe ready to handle duplicates.This is very similar to a 1.5 PCconcept. EE-only feature.

abstract-transformer 0..* A placeholder for transformerelements. Transformers convertmessage payloads.

transformers 0..1 A list of transformer elementsthat will be applied to themessage before it is deliveredto the component. Note thata list of transformers canalso be specified directly(without the 'transformers'element), but then it isnot possible to also specifyresponse transformers (usingthe 'response-transformers'element).

response-transformers 0..1 A list of transformer elementsthat will be applied to theresponse message returnedfrom the component.

property 0..* Sets a Mule property. This is aname/value pair that can be seton components, services, etc.,and which provide a generic

Page 227: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 227

way of configuring the system.Typically, you shouldn't need touse a generic property like this,since almost all functionalityis exposed via dedicatedelements. However, it can beuseful in configuring obscureor overlooked options and inconfiguring transports from thegeneric endpoint elements.

properties 0..1 A map of Mule properties.

<outbound-endpoint ...>

An outbound endpoint sends messages via the associated transport. As with global endpoints, eachtransport implements its own outbound endpoint element.

Attributes

Name Type Required Default Description

name name (no spaces) no Identifies theendpoint inthe registry.There is notneed to set the'name' attributeon inboundor outboundendpoints, only onglobal endpoints.

ref name (no spaces) no A reference to aglobal endpoint,which is usedas a templateto constructthis endpoint. Atemplate fixes theaddress (protocol,path, host, etc.),and may specifyinitial values forvarious properties,but furtherproperties can bedefined locally (aslong as they donot change theaddress in anyway).

address string no The genericaddress for thisendpoint. If thisattribute is used,the protocol mustbe specified aspart of the URI.Alternatively,

Page 228: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 228

most transportsprovide their ownattributes forspecifying theaddress (path,host, etc.). Notethat the addressattribute cannotbe combined with'ref' or with thetransport-providedalternativeattributes.

synchronous boolean no If true, theresult from thecomponentprocessing theincoming messagewill be returned asa response.

responseTimeout integer no The timeoutfor a responseif making asynchronousendpoint call

encoding string no String encodingused formessages.

connector-ref name (no spaces) no The name ofthe connectorassociated withthis endpoint. Thismust be specifiedif more thanone connector isdefined for thistransport.

transformer-refs list of names no A list of thetransformers thatwill be applied(in order) to themessage before itis delivered to thecomponent.

responseTransformer-refs

list of names no A list of thetransformers thatwill be applied(in order) to thesynchronousresponse before itis returned via thetransport.

Page 229: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 229

Child Elements

Name Cardinality Description

abstract-transaction 0..1 A placeholder for transactionelements. Transactions allowa series of operations to begrouped together.

abstract-filter 0..1 A placeholder for filter elements,which control which messagesare handled.

abstract-security-filter 0..1 A placeholder for security filterelements, which control accessto the system.

abstract-retry-policy 0..1 A placeholder for a retry policyelement. Retry policies definehow Mule should retry a failedmessage send/dispatch/request.

abstract-multi-transaction 0..1 A placeholder for multi-transaction elements. Multi-transactions allow a seriesof operations to be groupedtogether spanning differenttransports, e.g. JMS and JDBC,but without the overhead ofXA. The trade-off is that XAreliability guarantees aren'tavailable, and services mustbe ready to handle duplicates.This is very similar to a 1.5 PCconcept. EE-only feature.

abstract-transformer 0..* A placeholder for transformerelements. Transformers convertmessage payloads.

transformers 0..1 A list of transformer elementsthat will be applied to themessage before it is deliveredto the component. Note thata list of transformers canalso be specified directly(without the 'transformers'element), but then it isnot possible to also specifyresponse transformers (usingthe 'response-transformers'element).

response-transformers 0..1 A list of transformer elementsthat will be applied to theresponse message returnedfrom the component.

property 0..* Sets a Mule property. This is aname/value pair that can be seton components, services, etc.,and which provide a generic

Page 230: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 230

way of configuring the system.Typically, you shouldn't need touse a generic property like this,since almost all functionalityis exposed via dedicatedelements. However, it can beuseful in configuring obscureor overlooked options and inconfiguring transports from thegeneric endpoint elements.

properties 0..1 A map of Mule properties.

<endpoint ...>

A global endpoint, which acts as a template that can be used to construct an inbound or outboundendpoint elsewhere in the configuration by referencing the global endpoint name. Each transportimplements its own endpoint element, with a more friendly syntax, but this generic element can beused with any transport by supplying the correct address URI. For example, "vm://foo" describes a VMtransport endpoint.

Attributes

Name Type Required Default Description

name name (no spaces) no Identifies theendpoint so thatother elementscan reference it.This name canalso be referencedin the MuleClient.

ref name (no spaces) no A reference to aglobal endpoint,which is usedas a templateto constructthis endpoint. Atemplate fixes theaddress (protocol,path, host, etc.),and may specifyinitial values forvarious properties,but furtherproperties can bedefined locally (aslong as they donot change theaddress in anyway).

address string no The genericaddress for thisendpoint. If thisattribute is used,the protocol mustbe specified aspart of the URI.Alternatively,

Page 231: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 231

most transportsprovide their ownattributes forspecifying theaddress (path,host, etc.). Notethat the addressattribute cannotbe combined with'ref' or with thetransport-providedalternativeattributes.

synchronous boolean no If true, theresult from thecomponentprocessing theincoming messagewill be returned asa response.

responseTimeout integer no The timeoutfor a responseif making asynchronousendpoint call

encoding string no String encodingused formessages.

connector-ref name (no spaces) no The name ofthe connectorassociated withthis endpoint. Thismust be specifiedif more thanone connector isdefined for thistransport.

transformer-refs list of names no A list of thetransformers thatwill be applied(in order) to themessage before itis delivered to thecomponent.

responseTransformer-refs

list of names no A list of thetransformers thatwill be applied(in order) to thesynchronousresponse before itis returned via thetransport.

Page 232: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 232

Child Elements

Name Cardinality Description

abstract-transaction 0..1 A placeholder for transactionelements. Transactions allowa series of operations to begrouped together.

abstract-filter 0..1 A placeholder for filter elements,which control which messagesare handled.

abstract-security-filter 0..1 A placeholder for security filterelements, which control accessto the system.

abstract-retry-policy 0..1 A placeholder for a retry policyelement. Retry policies definehow Mule should retry a failedmessage send/dispatch/request.

abstract-multi-transaction 0..1 A placeholder for multi-transaction elements. Multi-transactions allow a seriesof operations to be groupedtogether spanning differenttransports, e.g. JMS and JDBC,but without the overhead ofXA. The trade-off is that XAreliability guarantees aren'tavailable, and services mustbe ready to handle duplicates.This is very similar to a 1.5 PCconcept. EE-only feature.

abstract-transformer 0..* A placeholder for transformerelements. Transformers convertmessage payloads.

transformers 0..1 A list of transformer elementsthat will be applied to themessage before it is deliveredto the component. Note thata list of transformers canalso be specified directly(without the 'transformers'element), but then it isnot possible to also specifyresponse transformers (usingthe 'response-transformers'element).

response-transformers 0..1 A list of transformer elementsthat will be applied to theresponse message returnedfrom the component.

property 0..* Sets a Mule property. This is aname/value pair that can be seton components, services, etc.,and which provide a generic

Page 233: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 233

way of configuring the system.Typically, you shouldn't need touse a generic property like this,since almost all functionalityis exposed via dedicatedelements. However, it can beuseful in configuring obscureor overlooked options and inconfiguring transports from thegeneric endpoint elements.

properties 0..1 A map of Mule properties.

Page 234: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 234

Exception Strategy Configuration Reference

This page last changed on Feb 20, 2009 by jackie.wheeler.

Exception Strategy Configuration Reference

This page provides details on the elements you configure for exception strategies. This information ispulled directly from mule.xsd and is cached. If the information appears to be out of date, refresh thepage. For more information on exception strategies, see Error Handling.

<default-service-exception-strategy ...>

Provide default exception handling for a service via an endpoint.

Attributes

Name Type Required Default Description

enableNotifications boolean no DetermineswhetherExceptionNotificationswill be fired fromthis strategy whenan exceptionoccurs.

Child Elements

Name Cardinality Description

commit-transaction 0..1 Defines when a currenttransaction gets committedbased on the name of theexception caught. You canset a comma-separated listof wildcard patterns that willbe matched against the fullyqualified classname of thecurrent exception. Patternsdefined for this element willleave the current transaction (ifany) untouched and allow it tobe committed.

rollback-transaction 0..1 Defines when a currenttransaction gets rolled backbased on the name of theexception caught. You canset a comma-separated listof wildcard patterns that willbe matched against the fullyqualified classname of thecurrent exception. Patternsdefined for this element will rollback the current transaction (ifany).

Page 235: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 235

abstract-outbound-endpoint 0..* A placeholder for outboundendpoint elements. Outboundendpoints dispatch messages tothe underlying transport.

<default-connector-exception-strategy ...>

Provide default exception handling for a connector via an endpoint.

Attributes

Name Type Required Default Description

enableNotifications boolean no DetermineswhetherExceptionNotificationswill be fired fromthis strategy whenan exceptionoccurs.

Child Elements

Name Cardinality Description

commit-transaction 0..1 Defines when a currenttransaction gets committedbased on the name of theexception caught. You canset a comma-separated listof wildcard patterns that willbe matched against the fullyqualified classname of thecurrent exception. Patternsdefined for this element willleave the current transaction (ifany) untouched and allow it tobe committed.

rollback-transaction 0..1 Defines when a currenttransaction gets rolled backbased on the name of theexception caught. You canset a comma-separated listof wildcard patterns that willbe matched against the fullyqualified classname of thecurrent exception. Patternsdefined for this element will rollback the current transaction (ifany).

abstract-outbound-endpoint 0..* A placeholder for outboundendpoint elements. Outboundendpoints dispatch messages tothe underlying transport.

Page 236: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 236

<custom-exception-strategy ...>

A user-defined exception strategy.

Attributes

Name Type Required Default Description

enableNotifications boolean no DetermineswhetherExceptionNotificationswill be fired fromthis strategy whenan exceptionoccurs.

class class name no A class thatimplements theExceptionListenerinterface. Inaddition, if an'outbound-endpoint' elementis specified,it is set as an"endpoint" beanproperty.

Child Elements

Name Cardinality Description

commit-transaction 0..1 Defines when a currenttransaction gets committedbased on the name of theexception caught. You canset a comma-separated listof wildcard patterns that willbe matched against the fullyqualified classname of thecurrent exception. Patternsdefined for this element willleave the current transaction (ifany) untouched and allow it tobe committed.

rollback-transaction 0..1 Defines when a currenttransaction gets rolled backbased on the name of theexception caught. You canset a comma-separated listof wildcard patterns that willbe matched against the fullyqualified classname of thecurrent exception. Patternsdefined for this element will rollback the current transaction (ifany).

Page 237: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 237

abstract-outbound-endpoint 0..* A placeholder for outboundendpoint elements. Outboundendpoints dispatch messages tothe underlying transport.

spring:property 0..*

Page 238: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 238

Filters Configuration Reference

This page last changed on Feb 20, 2009 by jackie.wheeler.

Filters Configuration Reference

[ Filter ] [ Not Filter ] [ And Filter ] [ Or Filter ] [ Wildcard Filter ] [ Expression Filter ] [ Regex Filter ] [Message Property Filter ] [ Exception Type Filter ] [ Payload Type Filter ] [ Custom Filter ] [ EncryptionSecurity Filter ] [ Is Xml Filter ] [ Jxpath Filter ] [ Jaxen Filter ] [ Xpath Filter ] [ Schema Validation Filter]

For more information on filters, see Using Filters.

Filter

A filter that is defined elsewhere (at the global level, or as a Spring bean).

Attributes of <filter...>

Name Type Required Default Description

name name (no spaces) no Identifies thefilter so thatother elementscan reference it.Required if thefilter is defined atthe global level.

not boolean no Inverts the filtercondition.

ref name (no spaces) no The name of thefilter to use.

Not Filter

Inverts the enclosed filter. For example, if the filter would normally return true for a specific message, itwill now return false, and vice versa.

Child Elements of <not-filter...>

Name Cardinality Description

abstract-filter 0..1 A placeholder for filter elements,which control which messagesare handled.

And Filter

Returns true only if all the enclosed filters return true.

Page 239: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 239

Child Elements of <and-filter...>

Name Cardinality Description

abstract-filter 2..* A placeholder for filter elements,which control which messagesare handled.

Or Filter

Returns true if any of the enclosed filters returns true.

Child Elements of <or-filter...>

Name Cardinality Description

abstract-filter 2..* A placeholder for filter elements,which control which messagesare handled.

Wildcard Filter

A filter that matches string messages against wildcards. It performs matches with "", for example,"jms.events." would catch "jms.events.customer" and "jms.events.receipts". This filter accepts acomma-separated list of patterns, so more than one filter pattern can be matched for a given argument:"jms.events., jms.actions." will match "jms.events.system" and "jms.actions" but not "jms.queue".

Expression Filter

A filter that can evaluate a range of expressions. It supports some base expression types such as header,payload (payload type), regex, and wildcard.

Attributes of <expression-filter...>

Name Type Required Default Description

name name (no spaces) no Identifies thefilter so thatother elementscan reference it.Required if thefilter is defined atthe global level.

not boolean no Inverts the filtercondition.

evaluator header/payload-type/exception-type/wildcard/regex/ognl/xpath/jxpath/groovy/bean/custom

no The expressionevaluatorto use. Theexpression filtersupports sometypes such asheader, payload,

Page 240: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 240

exception,wildcard, andregex, that arebuilt-in filtersnot registeredwith theExpressionEvaluatorManager.All others areregisteredwith theExpressionEvaluatorManager.Where XPath,bean, and ONGLare used, theexpression shouldbe a booleanexpression.

expression string no The expressionthat will beevaluated. Thisshould alwaysbe a booleanexpression. Thesyntax of theexpression willbe determined bythe expressionlanguage beingused.

customEvaluator name (no spaces) no Must be set ifthe evaluator isset to custom.The customevaluator mustbe registeredwith theExpressionEvaluatorManagerif it is to be usedhere.

nullReturnsTrue boolean no Whether the filtershould return trueif the specifiedexpression returnsnull.

Regex Filter

A filter that matches string messages against a regular expression. The Java regular expression engine(java.util.regex.Pattern) is used.

Attributes of <regex-filter...>

Name Type Required Default Description

name name (no spaces) no Identifies thefilter so thatother elementscan reference it.

Page 241: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 241

Required if thefilter is defined atthe global level.

not boolean no Inverts the filtercondition.

pattern string no The propertyname andoptionally a valueto use whenmatching. If theexpression is justa property name,the filter will checkthat the propertyexists. Users canalso use '=' and '!=' to determine aspecific value for aproperty.

Message Property Filter

A filter that matches properties on a message. This can be very useful, as the message propertiesrepresent all the meta information about the message from the underlying transport, so for a messagereceived over HTTP, you can check for HTTP headers and so forth. The pattern should be expressed as akey/value pair, such as "propertyName=value". If you want to compare more than one property, you canuse the logic filters for And, Or, and Not expressions. By default, the comparison is case sensitive, whichyou can override with the 'caseSensitive' property.

Attributes of <message-property-filter...>

Name Type Required Default Description

name name (no spaces) no Identifies thefilter so thatother elementscan reference it.Required if thefilter is defined atthe global level.

not boolean no Inverts the filtercondition.

pattern string no The propertyname andoptionally a valueto use whenmatching. If theexpression is justa property name,the filter will checkthat the propertyexists. Users canalso use '=' and '!=' to determine aspecific value for aproperty.

Page 242: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 242

caseSensitive boolean no true If false, thecomparisonignores case.

Exception Type Filter

A filter that matches the type of an exception.

Attributes of <exception-type-filter...>

Name Type Required Default Description

name name (no spaces) no Identifies thefilter so thatother elementscan reference it.Required if thefilter is defined atthe global level.

not boolean no Inverts the filtercondition.

expectedType class name no The expectedclass used in thecomparison.

Payload Type Filter

A filter that matches the type of the payload.

Attributes of <payload-type-filter...>

Name Type Required Default Description

name name (no spaces) no Identifies thefilter so thatother elementscan reference it.Required if thefilter is defined atthe global level.

not boolean no Inverts the filtercondition.

expectedType class name no The expectedclass used in thecomparison.

Custom Filter

A user-implemented filter.

Page 243: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 243

Attributes of <custom-filter...>

Name Type Required Default Description

name name (no spaces) no Identifies thefilter so thatother elementscan reference it.Required if thefilter is defined atthe global level.

not boolean no Inverts the filtercondition.

class class name no Animplementationof the Filterinterface.

Child Elements of <custom-filter...>

Name Cardinality Description

spring:property 0..*

Encryption Security Filter

A filter that provides password-based encyption.

Attributes of <encryption-security-filter...>

Name Type Required Default Description

strategy-ref name (no spaces) no The name ofthe encryptionstrategy to use.This should beconfigured usingthe 'password-encryption-strategy' element,inside a 'security-manager' elementat the top level.

Is Xml Filter

Accepts XML messages only. Alternatively, you can set the "not" attribute to filter out XML messages.

Jxpath Filter

Filters messages based on XPath expressions using JXPath.

Page 244: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 244

Attributes of <jxpath-filter...>

Name Type Required Default Description

lenient boolean no true Whether or noterrors are thrownif the XPathexpression doesn'texist.

expectedValue string no The expectedvalue of theXPath expressionevaluation. Ifthe expectedvalue matches theevaluation, thefilter returns true.

Child Elements of <jxpath-filter...>

Name Cardinality Description

namespace 0..* A namespace declaration,expressed as prefix and uriattributes. The prefix can thenbe used inside the expression.

context-property 0..* A property that will be madeavailable to the filter context.Expression Evaluators can beused to grab these propertiesfrom the message at runtime.

Jaxen Filter

The Jaxen filter allows you to route messages based on XPath expressions. The Jaxen filter is generallyfaster than the JXPath filter and should be considered the first choice when using an XPath filter.

Attributes of <jaxen-filter...>

Name Type Required Default Description

expectedValue string no The expectedvalue of theXPath expressionevaluation. Ifthe expectedvalue matches theevaluation, thefilter returns true.

Page 245: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 245

Child Elements of <jaxen-filter...>

Name Cardinality Description

namespace 0..* A namespace declaration,expressed as prefix and uriattributes. The prefix can thenbe used inside the expression.

context-property 0..* A property that wil be madeavailable to the filter context.Expression Evaluators can beused to grab these propertiesfrom the message at runtime.

Xpath Filter

The XPath filter uses the JAXP libraries to filter XPath expressions. Available as of Mule 2.2.

Attributes of <xpath-filter...>

Name Type Required Default Description

expectedValue string no The expectedvalue of theXPath expressionevaluation. Ifthe expectedvalue matches theevaluation, thefilter returns true.

Child Elements of <xpath-filter...>

Name Cardinality Description

namespace 0..* A namespace declaration,expressed as prefix and uriattributes. The prefix can thenbe used inside the expression.

Schema Validation Filter

The schema validation filter uses the JAXP libraries to validate your message against a schema. Availableas of Mule 2.2.

Attributes of <schema-validation-filter...>

Name Type Required Default Description

schemaLocations string no The path to theschema file.You can specify

Page 246: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 246

multiple schemalocations forvalidation.

schemaLanguage string no The schemalanguage touse. The defaultis "http://www.w3.org/2001/XMLSchema".

returnResult boolean no true Whether the filtershould cache theresult of the XML.If this is false, thefilter will be moreefficient, but itwon't allow youto read the XMLagain.

Page 247: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 247

Global Settings Configuration Reference

This page last changed on Feb 20, 2009 by jackie.wheeler.

Global Settings Configuration Reference

This page provides details on the global settings you configure at the root level of a Mule configuration.Some of this information is pulled directly from mule.xsd and is cached. If the information appears tobe out of date, refresh the page. For more information on configuration, see XML Configuration. Forinformation on threading profiles, see Tuning Performance.

<configuration ...>

Specifies defaults and general settings for the Mule instance.

Attributes

Name Type Required Default Description

defaultSynchronousEndpointsboolean no false If true, allrequests toendpoints will waitfor a response.

defaultResponseTimeout string no 10000 The default period(ms) to wait fora synchronousresponse.

defaultTransactionTimeout string no 30000 The defaulttimeout (ms)for transactions.This can alsobe configuredon transactions,in which casethe transactionconfiguration isused instead ofthis default.

Child Elements

Name Cardinality Description

default-threading-profile 0..1 The default threading profile,used by components and byendpoints for dispatching andreceiving if no more specificconfiguration is given.

default-dispatcher-threading-profile

0..1 The default dispatchingthreading profile, which modifiesthe default-threading-profilevalues and is used by endpointsfor dispatching messages.

Page 248: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 248

This can also be configured onconnectors, in which case theconnector configuration is usedinstead of this default.

default-receiver-threading-profile

0..1 The default receiving threadingprofile, which modifies thedefault-threading-profile valuesand is used by endpoints forreceiving messages. Thiscan also be configured onconnectors, in which case theconnector configuration is usedinstead of this default.

default-service-threading-profile 0..1 The default service threadingprofile, which modifies thedefault-threading-profileand is used by services forprocessing messages. This canalso be configured on modelsor services, in which case theseconfigurations will be usedinstead of this default.

abstract-retry-policy 0..1 The default retry policy, usedby connectors and endpoints.This can also be configured onconnectors, in which case theconnector configuration is usedinstead of this default.

A placeholder for a retry policyelement. Retry policies definehow Mule should retry a failedmessage send/dispatch/request.

Page 249: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 249

Inbound Router Configuration Reference

This page last changed on Feb 20, 2009 by jackie.wheeler.

Inbound Router Configuration Reference

This page provides details on the elements you configure for inbound routers. This information is pulleddirectly from mule.xsd and is cached. If the information appears to be out of date, refresh the page. Formore information on routers, see Using Message Routers.

<idempotent-receiver-router ...>

Ensures that only unique messages are received by a service by checking the unique ID of theincoming message. Note that the ID used can be generated from the message using an expressiondefined in the 'idExpression' attribute. By default, the expression used is '#[message:id]', whichmeans the underlying endpoint must support unique message IDs for this to work. Otherwise, aUniqueIdNotSupportedException is thrown.

Attributes

Name Type Required Default Description

idExpression string no Defines one ormore expressionsto use whenextracting the IDfrom the message.For example, itwould be possibleto combine toheaders as the IDof the messageto provideidempotency:'#[headers:foo,bar]'.Or, you couldcombine themessage IDwith a header:'#[message:id]-#[header:foo]'.If this propertyis not set,'#[message:id]'will be used bydefault.

Child Elements

Name Cardinality Description

abstract-filter 0..1 A placeholder for filter elements,which control which messagesare handled.

Page 250: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 250

abstract-object-store 0..1 A placeholder for an object storethat can be used by routers tomaintain state.

<idempotent-secure-hash-receiver-router ...>

Ensures that only unique messages are received by a service by calculating the hash of the messageitself using a message digest algorithm. This provides a value with an infinitesimally small chance of acollision. This can be used to filter message duplicates. Keep in mind that the hash is calculated overthe entire byte array representing the message, so any leading or trailing spaces or extraneous bytes(like padding) can produce different hash values for the same semantic message content. Care should betaken to ensure that messages do not contain extraneous bytes. This class is useful when the messagedoes not support unique identifiers.

Attributes

Name Type Required Default Description

messageDigestAlgorithm string no The securehashing algorithmto use. If not set,the default isSHA-256.

Child Elements

Name Cardinality Description

abstract-filter 0..1 A placeholder for filter elements,which control which messagesare handled.

abstract-object-store 0..1 A placeholder for an object storethat can be used by routers tomaintain state.

<wire-tap-router ...>

The WireTap inbound router allows you to route certain messages to a different endpoint as well as to thecomponent.

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

abstract-filter 0..1 A placeholder forfilter elements,which controlwhich messagesare handled.

Page 251: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 251

abstract-outbound-endpoint

1..1 A placeholder foroutbound endpointelements.Outboundendpoints dispatchmessages tothe underlyingtransport.

<forwarding-router ...>

Allows messages to be forwarded to the outbound routers without first being processed by a component.

Attributes

Name Type Required Default Description

transformFirst boolean no Specifies whethertransformationsare applied beforefiltering occurs.The default istrue.

Child Elements

Name Cardinality Description

abstract-filter 0..1 A placeholder for filter elements,which control which messagesare handled.

abstract-transformer 0..* A placeholder for transformerelements. Transformers convertmessage payloads.

<selective-consumer-router ...>

Applies one or more filters to the incoming message. If the filters match, the message is forwarded to thecomponent. Otherwise, the message is forwarded to the catch-all strategy on the router. If no catch-allstrategy is configured, the message is ignored and a warning is logged.

Attributes

Name Type Required Default Description

transformFirst boolean no Specifies whethertransformationsare applied beforefiltering occurs.The default istrue.

Page 252: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 252

Child Elements

Name Cardinality Description

abstract-filter 0..1 A placeholder for filter elements,which control which messagesare handled.

abstract-transformer 0..* A placeholder for transformerelements. Transformers convertmessage payloads.

<correlation-resequencer-router ...>

Holds back a group of messages and resequences them using each message's correlation sequenceproperty.

Attributes

Name Type Required Default Description

timeout integer no Defines a timeoutin Milliseconds towait for events tobe aggregated. Bydefault the routerwill throw anexeception if therouter is waitingfor a correlationgroup and timesout before allgroup enties arereceived.

failOnTimeout boolean no When false,incompleteaggregationgroups will beforwarded toa componenton timeout asa java.util.List.When true(default), aCorrelationTimeoutExceptionis thrown andRoutingNotification.CORRELATION_TIMEOUTis fired. Thecomponentdoesn't receiveany messages inthis case.

Page 253: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 253

Child Elements

Name Cardinality Description

abstract-filter 0..1 A placeholder for filter elements,which control which messagesare handled.

<message-chunking-aggregator-router ...>

Combines two or more messages into a single message by matching messages with a given CorrelationID. Correlation IDs are set on messages when they are dispatched by certain outbound routers, such asthe Recipient List and Message Splitter routers. These messages can be aggregated back together againusing this router.

Attributes

Name Type Required Default Description

timeout integer no Defines a timeoutin Milliseconds towait for events tobe aggregated. Bydefault the routerwill throw anexeception if therouter is waitingfor a correlationgroup and timesout before allgroup enties arereceived.

failOnTimeout boolean no When false,incompleteaggregationgroups will beforwarded toa componenton timeout asa java.util.List.When true(default), aCorrelationTimeoutExceptionis thrown andRoutingNotification.CORRELATION_TIMEOUTis fired. Thecomponentdoesn't receiveany messages inthis case.

Page 254: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 254

Child Elements

Name Cardinality Description

abstract-filter 0..1 A placeholder for filter elements,which control which messagesare handled.

abstract-message-info-mapping 0..1 Maps the attributes of thecurrent message to knownmessage elements in Mule,namely Message ID andCorrrelationID.

<custom-correlation-aggregator-router ...>

Configures a custom message aggregator. Mule provides an abstract implementation that has a templatemethod that performs the message aggregation. A common use of the aggregator router is to combinethe results of multiple requests such as "ask this set of vendors for the best price of X".

Attributes

Name Type Required Default Description

timeout integer no Defines a timeoutin Milliseconds towait for events tobe aggregated. Bydefault the routerwill throw anexeception if therouter is waitingfor a correlationgroup and timesout before allgroup enties arereceived.

failOnTimeout boolean no When false,incompleteaggregationgroups will beforwarded toa componenton timeout asa java.util.List.When true(default), aCorrelationTimeoutExceptionis thrown andRoutingNotification.CORRELATION_TIMEOUTis fired. Thecomponentdoesn't receiveany messages inthis case.

Page 255: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 255

class class name no Fully qualifiedclass name of thecustom correlationaggregator routerto be used.

Child Elements

Name Cardinality Description

abstract-filter 0..1 A placeholder for filter elements,which control which messagesare handled.

abstract-message-info-mapping 0..1 Maps the attributes of thecurrent message to knownmessage elements in Mule,namely Message ID andCorrrelationID.

<collection-aggregator-router ...>

Configures a Collection Response Router. This will return a MuleMessageCollection message type that willcontain all messages received for a each correlation group.

Attributes

Name Type Required Default Description

timeout integer no Defines a timeoutin Milliseconds towait for events tobe aggregated. Bydefault the routerwill throw anexeception if therouter is waitingfor a correlationgroup and timesout before allgroup enties arereceived.

failOnTimeout boolean no When false,incompleteaggregationgroups will beforwarded toa componenton timeout asa java.util.List.When true(default), aCorrelationTimeoutExceptionis thrown andRoutingNotification.CORRELATION_TIMEOUTis fired. The

Page 256: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 256

componentdoesn't receiveany messages inthis case.

Child Elements

Name Cardinality Description

abstract-filter 0..1 A placeholder for filter elements,which control which messagesare handled.

<custom-inbound-router ...>

Allows for custom inbound routers to be configured.

Attributes

Name Type Required Default Description

class class name no Animplementationof InboundRouter(fully qualifiedJava class name)

Child Elements

Name Cardinality Description

abstract-filter 0..1 A placeholder for filter elements,which control which messagesare handled.

spring:property 0..* Spring-style property elementsso that custom configuration canbe configured on the customrouter.

Page 257: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 257

Model Configuration Reference

This page last changed on Feb 20, 2009 by jackie.wheeler.

Model Configuration Reference

This page provides details on the elements you configure for models. Some of this information is pulleddirectly from mule.xsd and is cached. If the information appears to be out of date, refresh the page. Formore information on models, see Models.

<model ...>

The container for a set of services, providing basic settings and processing for all the services it contains.

Attributes

Name Type Required Default Description

name name no The name usedto identify thismodel.

inherit boolean no If true, this modelelement is anextension of aprevious modelelement with thesame name.

Child Elements

Name Cardinality Description

abstract-exception-strategy 0..1 A placeholder for an exceptionstrategy element. Exceptionstrategies define how Muleshould react to errors.

abstract-service 0..* A placeholder for a serviceelement. Services combinemessage routing with acomponent (typically a POJO).

abstract-entry-point-resolver-set 0..1 A placeholder for entry pointresolver set elements. Thesecombine a group of entry pointresolvers, trying them in turnuntil one succeeds.

abstract-entry-point-resolver 0..1 A placeholder for an entry pointresolver element. Entry pointresolvers define how payloadsare delivered to Java code bychoosing the method to call.

Page 258: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 258

abstract-queue-profile 0..1 A placeholder for a queueprofile, which controls howmessages are queued.

Queue Profile

Specifies the properties of an internal Mule queue. Internal queues are used to queue messages for eachcomponent managed by Mule.

Attributes of <queue-profile...>

Name Type Required Default Description

maxOutstandingMessagesinteger no Defines themaximum numberof messages thatcan be queued.

persistent boolean no false Whether Mulemessages arepersisted to astore. Primarily,this is used forpersisting queuedmessages todisk so that theinternal stateof the server ismirrored on diskin case the serverfails and needsto be restarted.Default is false.

Exception Strategy

See Exception Strategy Configuration Reference.

Service

See Service Configuration Reference.

Entry Point Resolver

See Entry Point Resolver Configuration Reference.

Page 259: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 259

Notifications Configuration Reference

This page last changed on Feb 20, 2009 by jackie.wheeler.

Notifications Configuration Reference

This page provides details on the elements you configure for notifications. Some of this information ispulled directly from mule.xsd and is cached. If the information appears to be out of date, refresh thepage. For more information on notifications, see Mule Server Notifications.

Notifications

Registers listeners for notifications and associates interfaces with particular events.

Attributes of <notifications...>

Name Type Required Default Description

dynamic boolean no If the notificationmanager isdynamic, listenerscan be registereddynamically atruntime via theMuleContext, andthe configurednotification canbe changed.Otherwise, someparts of Mule willcache notificationconfigurationfor efficiencyand will notgenerate eventsfor newly enablednotifications orlisteners. Thedefault value isfalse.

Child Elements of <notifications...>

Name Cardinality Description

notification 0..* Associates an event withan interface. Listeners thatimplement the interface willreceive instances of the event.

disable-notification 0..* Blocks the association ofan event with a particularinterface. This filters eventsafter the association with aparticular interface (and sotakes precedence).

Page 260: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 260

notification-listener 0..* Registers a bean as a listenerwith the notification system.Events are dispatched byreflection - the listener willreceive all events associatedwith any interfaces itimplements. The relationshipbetween interfaces and eventsis configured by the notificationand disable-notificationelements.

Notification

Associates an event with an interface. Listeners that implement the interface will receive instances of theevent.

Attributes of <notification...>

Name Type Required Default Description

event-class class name no The classassociated witha notificationevent that willbe delivered tothe interface.This can be usedinstead of the'event' attribute tospecify a customclass.

event notificationTypes no The notificationevent to deliver.

interface-class class name no The interface(class name) thatwill receive thenotification event.

interface notificationTypes no The interface thatwill receive thenotification event.

Disable Notification

Blocks the association of an event with a particular interface. This filters events after the association witha particular interface (and so takes precedence).

Attributes of <disable-notification...>

Name Type Required Default Description

event-class class name no The classassociated with

Page 261: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 261

an event thatwill no longerbe delivered toany interface.This can be usedinstead of the'event' attribute tospecify a customclass.

event notificationTypes no The event you nolonger want todeliver.

interface-class class name no The interface(class name) thatwill no longerreceive the event.

interface notificationTypes no The interface thatwill no longerreceive the event.

Notification Listener

Registers a bean as a listener with the notification system. Events are dispatched by reflection - thelistener will receive all events associated with any interfaces it implements. The relationship betweeninterfaces and events is configured by the notification and disable-notification elements.

Attributes of <notification-listener...>

Name Type Required Default Description

ref name (no spaces) no The bean thatwill receivenotifications.

subscription string no An optional stringthat is comparedwith the eventresource identifier.Only eventswith matchingidentifiers will besent. If no valueis given, all eventsare sent.

Notification Types

You can specify the following types of notifications using the event attribute of the <notification> and<disable-notification> element:"CONTEXT""MODEL""SERVICE""SECURITY""ENDPOINT-MESSAGE""COMPONENT-MESSAGE""MANAGEMENT""CONNECTION"

Page 262: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 262

"REGISTRY""CUSTOM""EXCEPTION""TRANSACTION""ROUTING"

Page 263: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 263

Outbound Router Configuration Reference

This page last changed on Feb 20, 2009 by jackie.wheeler.

Outbound Router Configuration Reference

This page provides details on the elements you configure for outbound routers. This information is pulleddirectly from the schema files and is cached. If the information appears to be out of date, refresh thepage. For more information on routers, see Using Message Routers.

<pass-through-router ...>

This router always matches and simply sends or dispatches message via the endpoint that is configured.

Attributes

Name Type Required Default Description

enableCorrelation ALWAYS/ NEVER /

IF_NOT_SET

no IF_NOT_SET Specifies whetherMule shouldgive outgoingmessages acorrelation ID. Thedefault behavior isto give messagesa correlation IDonly if they don'talready have one,so that existingcorrelation IDs aremaintained.

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 1..1 A placeholder for outboundendpoint elements. Outboundendpoints dispatch messages tothe underlying transport.

reply-to 0..1 Defines where the messageshould be routed after therecipient of the message towhich this service dispatcheshas finished with it.

abstract-transaction 0..1 Defines an overall transactionthat will be used for allendpoints on this router. Thisis only useful when you wantto define an outbound onlytransaction that will commit allof the transactions defined onthe outbound endpoints for thisrouter. Note that you must stilldefine a transaction on each of

Page 264: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 264

the endpoints that should takepart in the transaction. Thesetransactions should always beconfigured to JOIN the existingtransaction.

A placeholder for transactionelements. Transactions allowa series of operations to begrouped together.

abstract-message-info-mapping 0..1 The message info mapperused to extract key bits of themessage information, such asMessage ID or Correlation ID.these properties are used bysome routers and this mappinginformation tells Mule where toget the information from in thecurrent message.

Maps the attributes of thecurrent message to knownmessage elements in Mule,namely Message ID andCorrrelationID.

<filtering-router ...>

Uses filters to determine whether the message matches a particular criteria and if so will route themessage to the endpoint configured on the router.

Attributes

Name Type Required Default Description

transformer-refs list of names no A list of thetransformers thatwill be applied tothe message inorder before it isdelivered to thecomponent.

enableCorrelation ALWAYS/ NEVER /

IF_NOT_SET

no IF_NOT_SET Specifies whetherMule shouldgive outgoingmessages acorrelation ID. Thedefault behavior isto give messagesa correlation IDonly if they don'talready have one,so that existingcorrelation IDs aremaintained.

Page 265: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 265

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 1..1 A placeholder for outboundendpoint elements. Outboundendpoints dispatch messages tothe underlying transport.

abstract-filter 0..1 Filters the messages to beprocessed by this router.@Deprecated since 2.2.Configure the filter on theendpoint instead of the router.

A placeholder for filter elements,which control which messagesare handled.

abstract-transformer 0..* Filters are applied beforemessage transformations. Atransformer can be configuredhere to transform messagesbefore they are filtered.

A placeholder for transformerelements. Transformers convertmessage payloads.

reply-to 0..1 Defines where the messageshould be routed after therecipient of the message towhich this service dispatcheshas finished with it.

abstract-transaction 0..1 Defines an overall transactionthat will be used for allendpoints on this router. Thisis only useful when you wantto define an outbound onlytransaction that will commit allof the transactions defined onthe outbound endpoints for thisrouter. Note that you must stilldefine a transaction on each ofthe endpoints that should takepart in the transaction. Thesetransactions should always beconfigured to JOIN the existingtransaction.

A placeholder for transactionelements. Transactions allowa series of operations to begrouped together.

abstract-message-info-mapping 0..1 The message info mapperused to extract key bits of themessage information, such asMessage ID or Correlation ID.these properties are used bysome routers and this mapping

Page 266: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 266

information tells Mule where toget the information from in thecurrent message.

Maps the attributes of thecurrent message to knownmessage elements in Mule,namely Message ID andCorrrelationID.

<template-endpoint-router ...>

Allows endpoints to be altered at runtime based on properties set on the current message or fallbackvalues set on the endpoint properties. Templated values are expressed using square braces around aproperty name.

Attributes

Name Type Required Default Description

transformer-refs list of names no A list of thetransformers thatwill be applied tothe message inorder before it isdelivered to thecomponent.

enableCorrelation ALWAYS/ NEVER /

IF_NOT_SET

no IF_NOT_SET Specifies whetherMule shouldgive outgoingmessages acorrelation ID. Thedefault behavior isto give messagesa correlation IDonly if they don'talready have one,so that existingcorrelation IDs aremaintained.

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 1..1 A placeholder for outboundendpoint elements. Outboundendpoints dispatch messages tothe underlying transport.

abstract-filter 0..1 Filters the messages to beprocessed by this router.@Deprecated since 2.2.Configure the filter on theendpoint instead of the router.

Page 267: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 267

A placeholder for filter elements,which control which messagesare handled.

abstract-transformer 0..* Filters are applied beforemessage transformations. Atransformer can be configuredhere to transform messagesbefore they are filtered.

A placeholder for transformerelements. Transformers convertmessage payloads.

reply-to 0..1 Defines where the messageshould be routed after therecipient of the message towhich this service dispatcheshas finished with it.

abstract-transaction 0..1 Defines an overall transactionthat will be used for allendpoints on this router. Thisis only useful when you wantto define an outbound onlytransaction that will commit allof the transactions defined onthe outbound endpoints for thisrouter. Note that you must stilldefine a transaction on each ofthe endpoints that should takepart in the transaction. Thesetransactions should always beconfigured to JOIN the existingtransaction.

A placeholder for transactionelements. Transactions allowa series of operations to begrouped together.

abstract-message-info-mapping 0..1 The message info mapperused to extract key bits of themessage information, such asMessage ID or Correlation ID.these properties are used bysome routers and this mappinginformation tells Mule where toget the information from in thecurrent message.

Maps the attributes of thecurrent message to knownmessage elements in Mule,namely Message ID andCorrrelationID.

<chaining-router ...>

Sends the message through multiple endpoints using the result of the first invocation as the input for thenext.

Page 268: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 268

Attributes

Name Type Required Default Description

transformer-refs list of names no A list of thetransformers thatwill be applied tothe message inorder before it isdelivered to thecomponent.

enableCorrelation ALWAYS/ NEVER /

IF_NOT_SET

no IF_NOT_SET Specifies whetherMule shouldgive outgoingmessages acorrelation ID. Thedefault behavior isto give messagesa correlation IDonly if they don'talready have one,so that existingcorrelation IDs aremaintained.

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 1..* A placeholder for outboundendpoint elements. Outboundendpoints dispatch messages tothe underlying transport.

abstract-filter 0..1 Filters the messages to beprocessed by this router.@Deprecated since 2.2.Configure the filter on theendpoint instead of the router.

A placeholder for filter elements,which control which messagesare handled.

abstract-transformer 0..* Filters are applied beforemessage transformations. Atransformer can be configuredhere to transform messagesbefore they are filtered.

A placeholder for transformerelements. Transformers convertmessage payloads.

reply-to 0..1 Defines where the messageshould be routed after therecipient of the message towhich this service dispatcheshas finished with it.

Page 269: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 269

abstract-transaction 0..1 Defines an overall transactionthat will be used for allendpoints on this router. Thisis only useful when you wantto define an outbound onlytransaction that will commit allof the transactions defined onthe outbound endpoints for thisrouter. Note that you must stilldefine a transaction on each ofthe endpoints that should takepart in the transaction. Thesetransactions should always beconfigured to JOIN the existingtransaction.

A placeholder for transactionelements. Transactions allowa series of operations to begrouped together.

abstract-message-info-mapping 0..1 The message info mapperused to extract key bits of themessage information, such asMessage ID or Correlation ID.these properties are used bysome routers and this mappinginformation tells Mule where toget the information from in thecurrent message.

Maps the attributes of thecurrent message to knownmessage elements in Mule,namely Message ID andCorrrelationID.

<exception-based-router ...>

Sends a message over an endpoint by selecting the first endpoint that can connect to the transport.

Attributes

Name Type Required Default Description

transformer-refs list of names no A list of thetransformers thatwill be applied tothe message inorder before it isdelivered to thecomponent.

enableCorrelation ALWAYS/ NEVER /

IF_NOT_SET

no IF_NOT_SET Specifies whetherMule shouldgive outgoingmessages acorrelation ID. Thedefault behavior isto give messages

Page 270: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 270

a correlation IDonly if they don'talready have one,so that existingcorrelation IDs aremaintained.

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 1..* A placeholder for outboundendpoint elements. Outboundendpoints dispatch messages tothe underlying transport.

abstract-filter 0..1 Filters the messages to beprocessed by this router.@Deprecated since 2.2.Configure the filter on theendpoint instead of the router.

A placeholder for filter elements,which control which messagesare handled.

abstract-transformer 0..* Filters are applied beforemessage transformations. Atransformer can be configuredhere to transform messagesbefore they are filtered.

A placeholder for transformerelements. Transformers convertmessage payloads.

reply-to 0..1 Defines where the messageshould be routed after therecipient of the message towhich this service dispatcheshas finished with it.

abstract-transaction 0..1 Defines an overall transactionthat will be used for allendpoints on this router. Thisis only useful when you wantto define an outbound onlytransaction that will commit allof the transactions defined onthe outbound endpoints for thisrouter. Note that you must stilldefine a transaction on each ofthe endpoints that should takepart in the transaction. Thesetransactions should always beconfigured to JOIN the existingtransaction.

A placeholder for transactionelements. Transactions allowa series of operations to begrouped together.

Page 271: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 271

abstract-message-info-mapping 0..1 The message info mapperused to extract key bits of themessage information, such asMessage ID or Correlation ID.these properties are used bysome routers and this mappinginformation tells Mule where toget the information from in thecurrent message.

Maps the attributes of thecurrent message to knownmessage elements in Mule,namely Message ID andCorrrelationID.

<multicasting-router ...>

Sends the same message over multiple endpoints.

Attributes

Name Type Required Default Description

transformer-refs list of names no A list of thetransformers thatwill be applied tothe message inorder before it isdelivered to thecomponent.

enableCorrelation ALWAYS/ NEVER /

IF_NOT_SET

no IF_NOT_SET Specifies whetherMule shouldgive outgoingmessages acorrelation ID. Thedefault behavior isto give messagesa correlation IDonly if they don'talready have one,so that existingcorrelation IDs aremaintained.

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 1..* A placeholder for outboundendpoint elements. Outboundendpoints dispatch messages tothe underlying transport.

abstract-filter 0..1 Filters the messages to beprocessed by this router.@Deprecated since 2.2.

Page 272: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 272

Configure the filter on theendpoint instead of the router.

A placeholder for filter elements,which control which messagesare handled.

abstract-transformer 0..* Filters are applied beforemessage transformations. Atransformer can be configuredhere to transform messagesbefore they are filtered.

A placeholder for transformerelements. Transformers convertmessage payloads.

reply-to 0..1 Defines where the messageshould be routed after therecipient of the message towhich this service dispatcheshas finished with it.

abstract-transaction 0..1 Defines an overall transactionthat will be used for allendpoints on this router. Thisis only useful when you wantto define an outbound onlytransaction that will commit allof the transactions defined onthe outbound endpoints for thisrouter. Note that you must stilldefine a transaction on each ofthe endpoints that should takepart in the transaction. Thesetransactions should always beconfigured to JOIN the existingtransaction.

A placeholder for transactionelements. Transactions allowa series of operations to begrouped together.

abstract-message-info-mapping 0..1 The message info mapperused to extract key bits of themessage information, such asMessage ID or Correlation ID.these properties are used bysome routers and this mappinginformation tells Mule where toget the information from in thecurrent message.

Maps the attributes of thecurrent message to knownmessage elements in Mule,namely Message ID andCorrrelationID.

Page 273: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 273

<endpoint-selector-router ...>

Selects the outgoing endpoint based on an expression evaluator ("header:endpoint" by default). It willfirst try to match the endpoint by name and then by address. The endpoints to use can be set on therouter itself or be global endpoint definitions.

Attributes

Name Type Required Default Description

transformer-refs list of names no A list of thetransformers thatwill be applied tothe message inorder before it isdelivered to thecomponent.

enableCorrelation ALWAYS/ NEVER /

IF_NOT_SET

no IF_NOT_SET Specifies whetherMule shouldgive outgoingmessages acorrelation ID. Thedefault behavior isto give messagesa correlation IDonly if they don'talready have one,so that existingcorrelation IDs aremaintained.

default name (no spaces) no The name of thedefault endpointto use if theexpression returnsnull. This can beused as an 'else'condition to routemessages thatdon't contain theexpected routinginformation.

evaluator groovy / header/ headers /

headers-list /attachment /attachments /attachments-list / message /string / map-

payload /payload / mule/ xpath / jxpath

/ bean / ognl/ function/ custom

no The expressionevaluator touse. Expressionevaluators mustbe registeredwith theExpressionEvaluatorManagerbefore they canbe used. Using thecustom evaluatorallows you todefine your ownevaluator with the'custom-evaluator'attribute. Notethat someevaluators such as

Page 274: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 274

xpath, groovy, andbean are loadedfrom other Mulemodules (XMLand Scripting,respectively).These modulesmust be on yourclasspath beforethe evaluator canbe used.

expression string no The expressionto evaluate. Thesyntax of thisattribute changesdepending on theevaluator beingused.

custom-evaluator name (no spaces) no The name ofthe customevaluator to use.This attribute isonly used whenthe 'evaluator'attribute is setto "custom". Youcan plug in yourown expressionevaluators byregisteringthem with theExpressionEvaluatorManager.

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 1..* A placeholder for outboundendpoint elements. Outboundendpoints dispatch messages tothe underlying transport.

abstract-filter 0..1 Filters the messages to beprocessed by this router.@Deprecated since 2.2.Configure the filter on theendpoint instead of the router.

A placeholder for filter elements,which control which messagesare handled.

abstract-transformer 0..* Filters are applied beforemessage transformations. Atransformer can be configuredhere to transform messagesbefore they are filtered.

Page 275: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 275

A placeholder for transformerelements. Transformers convertmessage payloads.

reply-to 0..1 Defines where the messageshould be routed after therecipient of the message towhich this service dispatcheshas finished with it.

abstract-transaction 0..1 Defines an overall transactionthat will be used for allendpoints on this router. Thisis only useful when you wantto define an outbound onlytransaction that will commit allof the transactions defined onthe outbound endpoints for thisrouter. Note that you must stilldefine a transaction on each ofthe endpoints that should takepart in the transaction. Thesetransactions should always beconfigured to JOIN the existingtransaction.

A placeholder for transactionelements. Transactions allowa series of operations to begrouped together.

abstract-message-info-mapping 0..1 The message info mapperused to extract key bits of themessage information, such asMessage ID or Correlation ID.these properties are used bysome routers and this mappinginformation tells Mule where toget the information from in thecurrent message.

Maps the attributes of thecurrent message to knownmessage elements in Mule,namely Message ID andCorrrelationID.

<list-message-splitter-router ...>

The Filtering List Message Splitter accepts a list of objects that is split each object being routed todifferent endpoints.

Attributes

Name Type Required Default Description

transformer-refs list of names no A list of thetransformers thatwill be applied tothe message in

Page 276: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 276

order before it isdelivered to thecomponent.

enableCorrelation ALWAYS/ NEVER /

IF_NOT_SET

no IF_NOT_SET Specifies whetherMule shouldgive outgoingmessages acorrelation ID. Thedefault behavior isto give messagesa correlation IDonly if they don'talready have one,so that existingcorrelation IDs aremaintained.

deterministic boolean no If'disableRoundRobin'is false and thisoption is true (thedefault) then thefirst message partwill be routed tothe first endpoint,the second partto the secondendpoint, etc,with the nth partgoing to the (nmodulo numberof endpoints)endpoint. Iffalse then themessages willbe distributedequally amongstall endpoints.

disableRoundRobin boolean no If filters are beingused on endpointsthen round robinbehaviour isprobably notdesirable. This flagswitches roundrobin behaviouroff, it is on bydefault.

failIfNoMatch boolean no If'disableRoundRobin'is true, theremay be situationswhere the currentsplit messagedoes not matchany endpoints.this flag controlswhether anexception shouldbe thrown when

Page 277: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 277

a match is notfound.

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 1..* A placeholder for outboundendpoint elements. Outboundendpoints dispatch messages tothe underlying transport.

abstract-filter 0..1 Filters the messages to beprocessed by this router.@Deprecated since 2.2.Configure the filter on theendpoint instead of the router.

A placeholder for filter elements,which control which messagesare handled.

abstract-transformer 0..* Filters are applied beforemessage transformations. Atransformer can be configuredhere to transform messagesbefore they are filtered.

A placeholder for transformerelements. Transformers convertmessage payloads.

reply-to 0..1 Defines where the messageshould be routed after therecipient of the message towhich this service dispatcheshas finished with it.

abstract-transaction 0..1 Defines an overall transactionthat will be used for allendpoints on this router. Thisis only useful when you wantto define an outbound onlytransaction that will commit allof the transactions defined onthe outbound endpoints for thisrouter. Note that you must stilldefine a transaction on each ofthe endpoints that should takepart in the transaction. Thesetransactions should always beconfigured to JOIN the existingtransaction.

A placeholder for transactionelements. Transactions allowa series of operations to begrouped together.

abstract-message-info-mapping 0..1 The message info mapperused to extract key bits of themessage information, such as

Page 278: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 278

Message ID or Correlation ID.these properties are used bysome routers and this mappinginformation tells Mule where toget the information from in thecurrent message.

Maps the attributes of thecurrent message to knownmessage elements in Mule,namely Message ID andCorrrelationID.

<expression-splitter-router ...>

Splits the message based on an expression. The expression must return one or more message parts inorder to be effective.

Attributes

Name Type Required Default Description

transformer-refs list of names no A list of thetransformers thatwill be applied tothe message inorder before it isdelivered to thecomponent.

enableCorrelation ALWAYS/ NEVER /

IF_NOT_SET

no IF_NOT_SET Specifies whetherMule shouldgive outgoingmessages acorrelation ID. Thedefault behavior isto give messagesa correlation IDonly if they don'talready have one,so that existingcorrelation IDs aremaintained.

deterministic boolean no If'disableRoundRobin'is false and thisoption is true (thedefault) then thefirst message partwill be routed tothe first endpoint,the second partto the secondendpoint, etc,with the nth partgoing to the (nmodulo numberof endpoints)endpoint. Iffalse then the

Page 279: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 279

messages willbe distributedequally amongstall endpoints.

disableRoundRobin boolean no If filters are beingused on endpointsthen round robinbehaviour isprobably notdesirable. This flagswitches roundrobin behaviouroff, it is on bydefault.

failIfNoMatch boolean no If'disableRoundRobin'is true, theremay be situationswhere the currentsplit messagedoes not matchany endpoints.this flag controlswhether anexception shouldbe thrown whena match is notfound.

evaluator groovy / header/ headers /

headers-list /attachment /attachments /attachments-list / message /string / map-

payload /payload / mule/ xpath / jxpath

/ bean / ognl/ function/ custom

no The expressionevaluator touse. Expressionevaluators mustbe registeredwith theExpressionEvaluatorManagerbefore they canbe used. Using thecustom evaluatorallows you todefine your ownevaluator with the'custom-evaluator'attribute. Notethat someevaluators such asxpath, groovy, andbean are loadedfrom other Mulemodules (XMLand Scripting,respectively).These modulesmust be on yourclasspath beforethe evaluator canbe used.

expression string no The expressionto evaluate. Thesyntax of thisattribute changes

Page 280: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 280

depending on theevaluator beingused.

custom-evaluator name (no spaces) no The name ofthe customevaluator to use.This attribute isonly used whenthe 'evaluator'attribute is setto "custom". Youcan plug in yourown expressionevaluators byregisteringthem with theExpressionEvaluatorManager.

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 1..* A placeholder for outboundendpoint elements. Outboundendpoints dispatch messages tothe underlying transport.

abstract-filter 0..1 Filters the messages to beprocessed by this router.@Deprecated since 2.2.Configure the filter on theendpoint instead of the router.

A placeholder for filter elements,which control which messagesare handled.

abstract-transformer 0..* Filters are applied beforemessage transformations. Atransformer can be configuredhere to transform messagesbefore they are filtered.

A placeholder for transformerelements. Transformers convertmessage payloads.

reply-to 0..1 Defines where the messageshould be routed after therecipient of the message towhich this service dispatcheshas finished with it.

abstract-transaction 0..1 Defines an overall transactionthat will be used for allendpoints on this router. Thisis only useful when you wantto define an outbound onlytransaction that will commit allof the transactions defined onthe outbound endpoints for this

Page 281: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 281

router. Note that you must stilldefine a transaction on each ofthe endpoints that should takepart in the transaction. Thesetransactions should always beconfigured to JOIN the existingtransaction.

A placeholder for transactionelements. Transactions allowa series of operations to begrouped together.

abstract-message-info-mapping 0..1 The message info mapperused to extract key bits of themessage information, such asMessage ID or Correlation ID.these properties are used bysome routers and this mappinginformation tells Mule where toget the information from in thecurrent message.

Maps the attributes of thecurrent message to knownmessage elements in Mule,namely Message ID andCorrrelationID.

Filter Based Splitter

The filter-based splitter router will select the endpoint where you want to send part of a message byfiltering parts using the endpoint filters.

Attributes of <filter-based-splitter...>

Name Type Required Default Description

splitExpression string no The XPathexpression used tosplit the message.

externalSchemaLocationstring no The locationof a schemathat should beused to validatethe currentmessage. This isnot required if themessage containsthe location of theschema.

validateSchema boolean no Whether to enableschema validationwhen processingthe XML message.Note that this canhave a seriousperformancehit on high-

Page 282: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 282

throughputsystems.

failIfNoMatch boolean no Whether thisrouter shouldfail if none ofthe endpointfilters match thepayload. Thedefault is true.

Round Robin Splitter

The round robin message splitter will split a DOM4J document into nodes based on the splitExpressionproperty. It will then send these document fragments to the list of specified endpoints in a round-robin fashion. Optionally, you can specify a namespaces property map that contain prefix/namespacemappings.

Attributes of <round-robin-splitter...>

Name Type Required Default Description

splitExpression string no The XPathexpression used tosplit the message.

externalSchemaLocationstring no The locationof a schemathat should beused to validatethe currentmessage. This isnot required if themessage containsthe location of theschema.

validateSchema boolean no Whether to enableschema validationwhen processingthe XML message.Note that this canhave a seriousperformancehit on high-throughputsystems.

deterministic boolean no If there is noendpoint filteringand this attributeis true (thedefault), the firstmessage partis routed to thefirst endpoint, thesecond part routesto the secondendpoint, and soon with the nthpart going to the

Page 283: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 283

(n modulo numberof endpoints)endpoint. If false,the messages willbe distributedequally among allendpoints.

<message-chunking-router ...>

Allows you to split a single message into a number of fixed-length messages that will all be routed to thesame endpoint.

Attributes

Name Type Required Default Description

transformer-refs list of names no A list of thetransformers thatwill be applied tothe message inorder before it isdelivered to thecomponent.

enableCorrelation ALWAYS/ NEVER /

IF_NOT_SET

no IF_NOT_SET Specifies whetherMule shouldgive outgoingmessages acorrelation ID. Thedefault behavior isto give messagesa correlation IDonly if they don'talready have one,so that existingcorrelation IDs aremaintained.

messageSize integer no The messagechunk size (inbytes) that thecurrent messagewill be splitinto. Note thatthis is mutuallyexclusive to the'numberOfMessages'property.

numberOfMessages integer no The number ofmessage peices tobreak the currentmessage into. Thisproperty is lessuseful than the'message' sizeproperty since,usually messagesare constrictedby size. Note that

Page 284: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 284

this is mutuallyexclusive to the'messageSize'property.

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 1..* A placeholder for outboundendpoint elements. Outboundendpoints dispatch messages tothe underlying transport.

abstract-filter 0..1 Filters the messages to beprocessed by this router.@Deprecated since 2.2.Configure the filter on theendpoint instead of the router.

A placeholder for filter elements,which control which messagesare handled.

abstract-transformer 0..* Filters are applied beforemessage transformations. Atransformer can be configuredhere to transform messagesbefore they are filtered.

A placeholder for transformerelements. Transformers convertmessage payloads.

reply-to 0..1 Defines where the messageshould be routed after therecipient of the message towhich this service dispatcheshas finished with it.

abstract-transaction 0..1 Defines an overall transactionthat will be used for allendpoints on this router. Thisis only useful when you wantto define an outbound onlytransaction that will commit allof the transactions defined onthe outbound endpoints for thisrouter. Note that you must stilldefine a transaction on each ofthe endpoints that should takepart in the transaction. Thesetransactions should always beconfigured to JOIN the existingtransaction.

A placeholder for transactionelements. Transactions allowa series of operations to begrouped together.

Page 285: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 285

abstract-message-info-mapping 0..1 The message info mapperused to extract key bits of themessage information, such asMessage ID or Correlation ID.these properties are used bysome routers and this mappinginformation tells Mule where toget the information from in thecurrent message.

Maps the attributes of thecurrent message to knownmessage elements in Mule,namely Message ID andCorrrelationID.

<static-recipient-list-router ...>

Sends the same message to multiple endpoints over the same endpoint, or implements routing-slipbehavior where the next destination for the message is determined from message properties or thepayload. It uses a static list of recipient endpoints.

Attributes

Name Type Required Default Description

recipientsProperty string no Defines a propertyname on thecurrent messagewhere a list ofendpoint names(or URIs) canbe obtained.This propertycan return a{{java.util.List}}of values ora delimited{{java.lang.String}}.If the'recipientsProperty'returns astring then the'recipientsDelimiter'property is usedto split the string.If the entries inthe String or Listdefine endpointnames, these willbe looked up atruntime. If theentries defineendpoint URIsthese endpointswill be created atruntime.

recipientsDelimiter string no The delimiter touse when splitting

Page 286: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 286

a String list ofrecipients. thedefault is ','. Thisproperty is onlyused with the'recipientsProperty'.

synchronous boolean no This flag controlswhether themessage willbe sent tothe recipientssynchronously.Unlike otherrouters threcipient listrouter doesn'thave pre-configuredendpoints so thesynchronicityof the endpointcannot behonoured.

transformer-refs list of names no A list of thetransformers thatwill be applied tothe message inorder before it isdelivered to thecomponent.

enableCorrelation ALWAYS/ NEVER /

IF_NOT_SET

no IF_NOT_SET Specifies whetherMule shouldgive outgoingmessages acorrelation ID. Thedefault behavior isto give messagesa correlation IDonly if they don'talready have one,so that existingcorrelation IDs aremaintained.

Child Elements

Name Cardinality Description

recipients 0..1 Static list of recipients that theoutgoing message is sent to.The default delimiter is ','.

abstract-filter 0..1 Filters the messages to beprocessed by this router.@Deprecated since 2.2.Configure the filter on theendpoint instead of the router.

Page 287: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 287

A placeholder for filter elements,which control which messagesare handled.

abstract-transformer 0..* Filters are applied beforemessage transformations. Atransformer can be configuredhere to transform messagesbefore they are filtered.

A placeholder for transformerelements. Transformers convertmessage payloads.

reply-to 0..1 Defines where the messageshould be routed after therecipient of the message towhich this service dispatcheshas finished with it.

abstract-transaction 0..1 Defines an overall transactionthat will be used for allendpoints on this router. Thisis only useful when you wantto define an outbound onlytransaction that will commit allof the transactions defined onthe outbound endpoints for thisrouter. Note that you must stilldefine a transaction on each ofthe endpoints that should takepart in the transaction. Thesetransactions should always beconfigured to JOIN the existingtransaction.

A placeholder for transactionelements. Transactions allowa series of operations to begrouped together.

abstract-message-info-mapping 0..1 The message info mapperused to extract key bits of themessage information, such asMessage ID or Correlation ID.these properties are used bysome routers and this mappinginformation tells Mule where toget the information from in thecurrent message.

Maps the attributes of thecurrent message to knownmessage elements in Mule,namely Message ID andCorrrelationID.

<expression-recipient-list-router ...>

Sends the same message to multiple endpoints over the same endpoint, or implements routing-slipbehavior where the next destination for the message is determined from message properties or thepayload. The recipients can be extracted from the message using an expression, or you can specify astatic list of recipient endpoints. (As of version 2.1)

Page 288: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 288

Attributes

Name Type Required Default Description

synchronous boolean no This flag controlswhether themessage willbe sent tothe recipientssynchronously.Unlike otherrouters threcipient listrouter doesn'thave pre-configuredendpoints so thesynchronicityof the endpointcannot behonoured.

transformer-refs list of names no A list of thetransformers thatwill be applied tothe message inorder before it isdelivered to thecomponent.

enableCorrelation ALWAYS/ NEVER /

IF_NOT_SET

no IF_NOT_SET Specifies whetherMule shouldgive outgoingmessages acorrelation ID. Thedefault behavior isto give messagesa correlation IDonly if they don'talready have one,so that existingcorrelation IDs aremaintained.

evaluator groovy / header/ headers /

headers-list /attachment /attachments /attachments-list / message /string / map-

payload /payload / mule/ xpath / jxpath

/ bean / ognl/ function/ custom

no The expressionevaluator touse. Expressionevaluators mustbe registeredwith theExpressionEvaluatorManagerbefore they canbe used. Using thecustom evaluatorallows you todefine your ownevaluator with the'custom-evaluator'attribute. Notethat someevaluators such asxpath, groovy, and

Page 289: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 289

bean are loadedfrom other Mulemodules (XMLand Scripting,respectively).These modulesmust be on yourclasspath beforethe evaluator canbe used.

expression string no The expressionto evaluate. Thesyntax of thisattribute changesdepending on theevaluator beingused.

custom-evaluator name (no spaces) no The name ofthe customevaluator to use.This attribute isonly used whenthe 'evaluator'attribute is setto "custom". Youcan plug in yourown expressionevaluators byregisteringthem with theExpressionEvaluatorManager.

Child Elements

Name Cardinality Description

recipients 0..1 A static list of endpoint namesor URIs that will be usedas recipients of the currentmessage. If the expressionon this router returns a list ofendpoint names, the endpointshere will be checked as well asany global endpoints.

abstract-filter 0..1 Filters the messages to beprocessed by this router.@Deprecated since 2.2.Configure the filter on theendpoint instead of the router.

A placeholder for filter elements,which control which messagesare handled.

abstract-transformer 0..* Filters are applied beforemessage transformations. Atransformer can be configuredhere to transform messagesbefore they are filtered.

Page 290: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 290

A placeholder for transformerelements. Transformers convertmessage payloads.

reply-to 0..1 Defines where the messageshould be routed after therecipient of the message towhich this service dispatcheshas finished with it.

abstract-transaction 0..1 Defines an overall transactionthat will be used for allendpoints on this router. Thisis only useful when you wantto define an outbound onlytransaction that will commit allof the transactions defined onthe outbound endpoints for thisrouter. Note that you must stilldefine a transaction on each ofthe endpoints that should takepart in the transaction. Thesetransactions should always beconfigured to JOIN the existingtransaction.

A placeholder for transactionelements. Transactions allowa series of operations to begrouped together.

abstract-message-info-mapping 0..1 The message info mapperused to extract key bits of themessage information, such asMessage ID or Correlation ID.these properties are used bysome routers and this mappinginformation tells Mule where toget the information from in thecurrent message.

Maps the attributes of thecurrent message to knownmessage elements in Mule,namely Message ID andCorrrelationID.

<custom-outbound-router ...>

Allows you to configure a custom outbound router by specifying the custom router class and by usingSpring properties.

Attributes

Name Type Required Default Description

class class name no Animplementation ofOutboundRouter

Page 291: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 291

(fully qualifiedJava class name)

transformer-refs list of names no A list of thetransformers thatwill be applied tothe message inorder before it isdelivered to thecomponent.

enableCorrelation ALWAYS/ NEVER /

IF_NOT_SET

no IF_NOT_SET Specifies whetherMule shouldgive outgoingmessages acorrelation ID. Thedefault behavior isto give messagesa correlation IDonly if they don'talready have one,so that existingcorrelation IDs aremaintained.

Child Elements

Name Cardinality Description

abstract-outbound-endpoint 0..* A placeholder for outboundendpoint elements. Outboundendpoints dispatch messages tothe underlying transport.

spring:property 0..* Spring-style property elementsso that custom configuration canbe configured on the customrouter.

abstract-filter 0..1 Filters the messages to beprocessed by this router.@Deprecated since 2.2.Configure the filter on theendpoint instead of the router.

A placeholder for filter elements,which control which messagesare handled.

abstract-transformer 0..* Filters are applied beforemessage transformations. Atransformer can be configuredhere to transform messagesbefore they are filtered.

A placeholder for transformerelements. Transformers convertmessage payloads.

reply-to 0..1 Defines where the messageshould be routed after therecipient of the message to

Page 292: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 292

which this service dispatcheshas finished with it.

abstract-transaction 0..1 Defines an overall transactionthat will be used for allendpoints on this router. Thisis only useful when you wantto define an outbound onlytransaction that will commit allof the transactions defined onthe outbound endpoints for thisrouter. Note that you must stilldefine a transaction on each ofthe endpoints that should takepart in the transaction. Thesetransactions should always beconfigured to JOIN the existingtransaction.

A placeholder for transactionelements. Transactions allowa series of operations to begrouped together.

abstract-message-info-mapping 0..1 The message info mapperused to extract key bits of themessage information, such asMessage ID or Correlation ID.these properties are used bysome routers and this mappinginformation tells Mule where toget the information from in thecurrent message.

Maps the attributes of thecurrent message to knownmessage elements in Mule,namely Message ID andCorrrelationID.

Page 293: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 293

Properties Configuration Reference

This page last changed on Feb 20, 2009 by jackie.wheeler.

Properties Configuration Reference

This page provides detailed reference information for property elements in Mule. The information below ispulled directly from the source code, so it reflects the latest data since you loaded the page. If somethingappears to be out of date, you can refresh the page to reload the information.

Global Property

A global property is a named string. It can be inserted in most attribute values using standard (ant-style)Spring placeholders.

Attributes of <global-property...>

Name Type Required Default Description

name name (no spaces) no The name of theproperty. This isused inside Springplaceholders.

value string no The value ofthe property.This replaceseach occurenceof a Springplaceholder.

Property

Sets a Mule property. This is a name/value pair that can be set on components, services, etc., and whichprovide a generic way of configuring the system. Typically, you shouldn't need to use a generic propertylike this, since almost all functionality is exposed via dedicated elements. However, it can be usefulin configuring obscure or overlooked options and in configuring transports from the generic endpointelements.

Attributes of <property...>

Name Type Required Default Description

key string no

value string no

value-ref name (no spaces) no

Properties

A map of Mule properties.

Page 294: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 294

Jndi Provider Property

Direct setting of a JNDI property.

Attributes of <jndi-provider-property...>

Name Type Required Default Description

key string no

value string no

value-ref name (no spaces) no

Jndi Provider Properties

Direct setting of JNDI properties (allows access to the full Spring map entry).

Page 295: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 295

Service Configuration Reference

This page last changed on Feb 20, 2009 by jackie.wheeler.

Service Configuration Reference

This page provides details on the elements you configure for services. This information is pulled directlyfrom mule.xsd and is cached. If the information appears to be out of date, refresh the page. For moreinformation on services, see Configuring the Service.

<service ...>

Describes how to receive messages, deliver them to a component, and handle the results (if any).

Attributes

Name Type Required Default Description

name name no The name usedto identify thisservice.

initialState started /stopped/ paused

no started The initialstate of theservice. Usually aservice is startedautomatically("started"), butthis attribute canbe used to disableinitial startup("stopped") orstart the servicein a paused state("paused").

queueTimeout integer no The timeout usedwhen takingmessages fromthe service queue.

Child Elements

Name Cardinality Description

description 0..1 This can hold any kind ofdocumentation related to theservice. It is intended to be"human readable" only and isnot used by the system.

inbound 0..1 The elements within 'inbound'describe how a service receivesmessages.

Page 296: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 296

abstract-component 0..1 The service component thatis invoked when incomingmessages are received. If thiselement is not present, theservice simply bridges theinbound and outbound using apass-through component.

A placeholder for a componentelement. A component isinvoked when inbound messagesare received by the service.

outbound 0..1 The elements within 'outbound'describe how a service sends ordispatches messages.

async-reply 0..1 The elements within'async-reply' describe howasynchronous replies arehandled.

abstract-exception-strategy 0..1 A placeholder for an exceptionstrategy element. Exceptionstrategies define how Muleshould react to errors.

abstract-service-threading-profile

0..1 A placeholder for the servicethreading profile element.Threading profiles define howthread pools are used by aservice.

abstract-queue-profile 0..1 A placeholder for a queueprofile, which controls howmessages are queued.

<custom-service ...>

A user-implemented service (typically used only in testing).

Attributes

Name Type Required Default Description

name name no The name usedto identify thisservice.

initialState started /stopped/ paused

no started The initialstate of theservice. Usually aservice is startedautomatically("started"), butthis attribute canbe used to disableinitial startup("stopped") orstart the service

Page 297: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 297

in a paused state("paused").

class class name no The class to usefor the service.

Child Elements

Name Cardinality Description

description 0..1 This can hold any kind ofdocumentation related to theservice. It is intended to be"human readable" only and isnot used by the system.

inbound 0..1 The elements within 'inbound'describe how a service receivesmessages.

abstract-component 0..1 The service component thatis invoked when incomingmessages are received. If thiselement is not present, theservice simply bridges theinbound and outbound using apass-through component.

A placeholder for a componentelement. A component isinvoked when inbound messagesare received by the service.

outbound 0..1 The elements within 'outbound'describe how a service sends ordispatches messages.

async-reply 0..1 The elements within'async-reply' describe howasynchronous replies arehandled.

abstract-exception-strategy 0..1 A placeholder for an exceptionstrategy element. Exceptionstrategies define how Muleshould react to errors.

<description ...>

Holds any kind of documentation that accompanies this configuration file. It is intended to be "humanreadable" only and is not used by the system.

Page 298: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 298

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

<description ...>

This can hold any kind of documentation related to the service. It is intended to be "human readable"only and is not used by the system.

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

<inbound ...>

The elements within 'inbound' describe how a service receives messages.

Attributes

Name Type Required Default Description

matchAll boolean no true If true, the inputmessage willbe passed to allinbound routers.Otherwise, onlythe first matchingrouter is used.

Child Elements

Name Cardinality Description

abstract-inbound-endpoint 0..* A placeholder for inboundendpoint elements. Inboundendpoints receive messagesfrom the underlying transport.The message payload is thendelivered to the component forprocessing.

abstract-inbound-router 0..* A placeholder for inbound routerelements, which control howincoming messages are handled.

Page 299: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 299

abstract-catch-all-strategy 0..1 A placeholder for catch-allstrategy elements.

<outbound ...>

The elements within 'outbound' describe how a service sends or dispatches messages.

Attributes

Name Type Required Default Description

matchAll boolean no false If true, the outputmessage will besent to all routers.Otherwise, onlythe first matchingrouter is used.

Child Elements

Name Cardinality Description

abstract-outbound-router 1..* A placeholder for outboundrouter elements, which controlhow outgoing messages aredelivered to the outboundendpoints.

abstract-catch-all-strategy 0..1 A placeholder for catch-allstrategy elements.

<async-reply ...>

The elements within 'async-reply' describe how asynchronous replies are handled.

Attributes

Name Type Required Default Description

timeout integer no The timeout (ms)to wait for a reply.

failOnTimeout boolean no If the routertimes out beforeall expectedevents have beenreceived, specifieswhether anexception shouldbe thrown (true)or the currentevents shouldbe returned forprocessing (false).

Page 300: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 300

The default isfalse.

Child Elements

Name Cardinality Description

abstract-inbound-endpoint 1..* A placeholder for inboundendpoint elements. Inboundendpoints receive messagesfrom the underlying transport.The message payload is thendelivered to the component forprocessing.

abstract-async-reply-router 0..1 A placeholder for an async replyrouter element. Asynchronousreplies are handled via thisrouter.

<queue-profile ...>

Specifies the properties of an internal Mule queue. Internal queues are used to queue messages for eachcomponent managed by Mule.

Attributes

Name Type Required Default Description

maxOutstandingMessages integer no Defines themaximum numberof messages thatcan be queued.

persistent boolean no false Whether Mulemessages arepersisted to astore. Primarily,this is used forpersisting queuedmessages todisk so that theinternal stateof the server ismirrored on diskin case the serverfails and needsto be restarted.Default is false.

Page 301: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 301

Child Elements

Name Cardinality Description

Exception Strategy

See Exception Strategy Configuration Reference.

Catch All Strategy

See Catch All Strategy Configuration Reference.

Component

See Component Configuration Reference.

Page 302: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 302

Transactions Configuration Reference

This page last changed on Feb 20, 2009 by jackie.wheeler.

Transactions Configuration Reference

This page provides reference information on the elements you configure for transactions. For moreinformation on transactions, see Transaction Management.

Abstract Transaction

A placeholder for transaction elements. Transactions allow a series of operations to be grouped together.

Attributes of <abstract-transaction...>

Name Type Required Default Description

action NONE/ALWAYS_BEGIN/BEGIN_OR_JOIN/ALWAYS_JOIN/JOIN_IF_POSSIBLE

no The type of actionthe transactionshould take, oneof the following:NONE - Neverparticipate ina transaction.ALWAYS_BEGIN- Always start anew transactionwhen receivinga message. Anexception willbe thrown ifa transactionalready exists.BEGIN_OR_JOIN- If a transactionis already inprogress whena message isreceived, jointhe transactionif possible.Otherwise, start anew transaction.ALWAYS_JOIN -Always expects atransaction to bein progress whena message isreceived. If thereis no transaction,an exceptionis thrown.JOIN_IF_POSSIBLE- Join the currenttransaction ifone is available.Otherwise, notransaction iscreated.

Page 303: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 303

timeout integer no Timeout for thetransaction (ms).

Custom Transaction

A user-defined or otherwise unsupported third-party transactions.

Attributes of <custom-transaction...>

Name Type Required Default Description

action NONE/ALWAYS_BEGIN/BEGIN_OR_JOIN/ALWAYS_JOIN/JOIN_IF_POSSIBLE

no The type of actionthe transactionshould take, oneof the following:NONE - Neverparticipate ina transaction.ALWAYS_BEGIN- Always start anew transactionwhen receivinga message. Anexception willbe thrown ifa transactionalready exists.BEGIN_OR_JOIN- If a transactionis already inprogress whena message isreceived, jointhe transactionif possible.Otherwise, start anew transaction.ALWAYS_JOIN -Always expects atransaction to bein progress whena message isreceived. If thereis no transaction,an exceptionis thrown.JOIN_IF_POSSIBLE- Join the currenttransaction ifone is available.Otherwise, notransaction iscreated.

timeout integer no Timeout for thetransaction (ms).

factory-class class name no A class thatimplements theTransactionFactory

Page 304: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 304

interface that willbe instantiatedand used togenerate atransaction. Thisattribute andthe 'factory-ref' attributeare mutuallyexclusive; oneof the two isrequired.

factory-ref name (no spaces) no A bean thatimplements theTransactionFactoryinterface thatwill be usedto generate atransaction. Thisattribute andthe 'factory-class' attributeare mutuallyexclusive; oneof the two isrequired.

Xa Transaction

An XA transaction.

Websphere Transaction Manager

The WebSphere transaction manager.

Attributes of <websphere-transaction-manager...>

Name Type Required Default Description

name name (no spaces) no transactionManager An optional namefor the transactionmanager. Thedefault value is"transactionManager".

Jboss Transaction Manager

The JBoss transaction manager.

Attributes of <jboss-transaction-manager...>

Name Type Required Default Description

name name (no spaces) no transactionManager An optional namefor the transactionmanager. The

Page 305: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 305

default value is"transactionManager".

Weblogic Transaction Manager

The WebLogic transaction manager.

Child Elements of <weblogic-transaction-manager...>

Name Cardinality Description

environment 0..1 The JNDI environment.

Jrun Transaction Manager

The JRun transaction manager.

Attributes of <jrun-transaction-manager...>

Name Type Required Default Description

name name (no spaces) no transactionManager An optional namefor the transactionmanager. Thedefault value is"transactionManager".

Resin Transaction Manager

The Resin transaction manager.

Attributes of <resin-transaction-manager...>

Name Type Required Default Description

name name (no spaces) no transactionManager An optional namefor the transactionmanager. Thedefault value is"transactionManager".

Jndi Transaction Manager

Retrieves a named transaction manager factory from JNDI.

Attributes of <jndi-transaction-manager...>

Name Type Required Default Description

jndiName string no The name ofthe manager

Page 306: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 306

factory to retrieve(such as java:/TransactionManager).

Custom Transaction Manager

A user-implemented transaction manager.

Attributes of <custom-transaction-manager...>

Name Type Required Default Description

class class name no The class toinstantiateto create atransactionmanager.

Child Elements of <custom-transaction-manager...>

Name Cardinality Description

environment 0..1 The JNDI environment.

spring:property 0..*

Page 307: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 307

Configuring a Mule Instance

This page last changed on Feb 24, 2009 by jackie.wheeler.

Configuring a Mule Instance

A Mule configuration file can become an elaborate tree of elements, however, the basic things toconfigure at the top level are:

• Connectors - Non-default configuration of any transports used• Endpoints - Global definition of endpoints is encouraged to clearly describe where your integration

channels are• Transformers - Transformers may be defined globally and later referenced from your services• Filters - Filters may be defined globally and later referenced from your services• Models - One or more models that logically group together your services• Services - One or more services that wrap your components and configure routers, endpoints,

transformers, and filters specifically for that service

Following is an example of a simple Mule configuration file:

<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.2" xsi:schemaLocation=" http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/vm/2.2 http://www.mulesource.org/schema/mule/vm/2.2/mule-vm.xsd">

<vm:connector name="vmConnector" queueEvents="true" queueTimeout="5000"/>

<vm:endpoint name="CustomerRequests" path="customer.requests"/> <vm:endpoint name="CustomerResponses" path="customer.responses"/>

<custom-transformer name="ThisToThat" class="com.acme.transformer.ThisToThat"/>

<model name="main"> <service name="myBasicService"> <inbound> <inbound-endpoint ref="CustomerRequests"/> </inbound> <component class="com.acme.service.BasicService"/> <outbound> <outbound-pass-through-router> <outbound-endpoint ref="CustomerResponses" transformer-refs="ThisToThat"/> </outbound-pass-through-router> </outbound> </service>

Page 308: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 308

</model></mule>

Advanced Configuration

Other, more advanced things you may configure at this level:

• Agents - Agents are typically used for cross-cutting concerns such as logging or management• Notifications - Be notified upon certain lifecycle events• Security Manager - Authenticates requests based on one or more security providers• Transaction Management - Mule transactions are configured on inbound endpoints, where an

endpoint can be configured to start a new transaction or join an existing one.• Global Configuration Options - Miscellaneous global settings• Global Properties - Placeholder values

Page 309: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 309

Configuring Endpoints

This page last changed on Mar 19, 2009 by jackie.wheeler.

Configuring Endpoints

[ Basic Configuration ] [ Endpoint Usage ] [ Global Endpoints ]

Endpoints are used to connect services. An endpoint is a specific channel on which a service can sendmessages and from which another service can receive messages. For example, a purchasing componentmay receive an order request over HTTP. Once the order has been processed by the component, a JMSmessage may be sent over a topic to notify an auditing system, and a response can be sent back overHTTP.

This page describes how to configure an endpoint. For details on the various attributes and elements youcan configure on an endpoint, see Endpoint Configuration Reference.

Basic Configuration

In its most basic form, an endpoint consists of a transport and a transport-specific channel/destination/resource used to identify the channel and location where two services can exchange information. Forexample:

<inbound-endpoint address="udp://localhost:65432"/><jetty:inbound-endpoint address="http://localhost:60211/mycomponent1" synchronous="true" /> <outbound-endpoint address="smtp://user:[email protected]"/><inbound-endpoint address="jms://test.queue"/>

Traditionally, endpoints in Mule have been specified as a URI such as the examples above. This form isstill supported, and indeed may prove to be more practical depending on your application. However, as ofMule 2.0, the recommended way to specify endpoints is via transport-specific namespaces, as shown inthe following examples.

<file:inbound-endpoint path="./.mule/in" comparator="org.mule.transport.file.comparator.OlderFirstComparator" reverseOrder="true"/><ssl:endpoint name="clientEndpoint" host="localhost" port="60198" synchronous="true"/><jetty:endpoint name="serverEndpoint" host="localhost" port="60203" path="services/Foo" synchronous="false" /> <imaps:endpoint name="global1s" host="localhost" password="secret" port="123" user="bob"/><rmi:endpoint name="BadType" host="localhost" port="1099" object="MatchingUMO" method="reverseString"/><quartz:endpoint name="qEP6" repeatCount="10" repeatInterval="1000" jobName="job"/><jms:inbound-endpoint queue="test.queue"/>

Properties

Properties on endpoints can be used to customize behavior. Any properties set on the endpoint canbe used to overload default properties on the associated transport's connector. For example, an SMTPoutbound endpoint might set the fromAddress property to workflow1 to override a default connectorvalue of sysadmin. Any standard properties for an endpoint will be available as attributes in the XMLschema if transport-specific endpoints are used. It is also possible to specify a non-standard property. Forexample:

<!-- Standard properties --><quartz:endpoint name="qEP6" repeatCount="10" repeatInterval="1000" jobName="job"/>

Page 310: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 310

<!-- Non-standard properties --><quartz:endpoint name="qEP7" jobName="job2"> <property key="actionOnTimeout" value="self-destruct"/> <property key="precision" value="2.5"/></quartz:endpoint>

Connector

In many cases, the connector associated with an endpoint can simply be assumed based on the transportand created implicitly. However, if more than one connector of the same transport exists, or if non-default settings are used for the connector, you must refer to the connector from the endpoint using theconnector-ref attribute.

<inbound-endpoint address="tcp://localhost:65432" connector-ref="tcpConnector1"/><tcp:inbound-endpoint host="localhost" port="65433" connector-ref="tcpConnector2"/>

Filter

An endpoint can contain a filter to selectively ignore certain messages. The filter can be transport-specificsuch as a JMS selector or file filter or can be a general-purpose filter such as JXPath. Filtering is notsupported by all transports, and setting a filter on an endpoint using some transports will result in anUnsupportedOperationException. For more information, see Using Filters.

<jms:endpoint queue="in.queue"> <jms:selector expression="JMSPriority > 5"/></jms:endpoint>

<vm:endpoint name="fruitBowlEndpoint" path="fruitBowlPublishQ"> <message-property-filter pattern="foo=bar"/></vm:endpoint>

Messaging Style

By default, endpoints are asynchronous. To set an endpoint to synchronous, you set sychronous="true".This setting is not required by HTTP/S, SSL, TCP, and Servlet endpoints, which are synchronous bydefault.

For more information on configuring messaging styles on an endpoint, see Mule Messaging Styles.

Transaction

A transaction can begin or commit when an event is received or sent via an endpoint. The endpoint mustbe synchronous, and transaction support depends largely on the particular transport being used. Formore information see Transaction Management.

<jms:inbound-endpoint queue="in"> <jms:transaction action="BEGIN_OR_JOIN"/></jms:inbound-endpoint>

Page 311: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 311

Endpoint Usage

Endpoints can be used in the following places:

• Inbound Routers• Outbound Routers• Services• Catch-all Strategies• Exception Strategies

Inbound Routers

See Using Message Routers.

<service name="Receiver"> <inbound> <vm:inbound-endpoint path="inbound.channel"/> <wire-tap-router> <vm:outbound-endpoint path="tapped.channel"/> </wire-tap-router> </inbound> <component class="com.acme.SomeService"/></service>

Outbound Routers

See Using Message Routers.

<service name="MessageChunker"> <inbound> <jms:inbound-endpoint queue="big.messages"/> </inbound> <outbound> <message-chunking-router messageSize="10"> <jms:outbound-endpoint queue="small.chunks"/> </message-chunking-router> </outbound></service>

<service name="LenderGatewayService"> <inbound> <inbound-endpoint ref="LenderGateway" /> </inbound> <outbound> <chaining-router> <outbound-endpoint ref="LenderService" /> <outbound-endpoint ref="BankingGateway" transformer-refs="SetLendersAsRecipients ObjectToJMSMessage" /> </chaining-router> </outbound></service>

Services

As a shortcut, endpoints can be configured directly on the service without a router in some cases.

Page 312: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 312

<service name="Echo"> <inbound> <!-- Inbound router is implicit --> <stdio:inbound-endpoint system="IN"/> </inbound> <echo-component/> <outbound> <!-- Outbound router is explicit --> <outbound-pass-through-router> <stdio:outbound-endpoint system="OUT"/> </outbound-pass-through-router> </outbound></service>

Catch-all Strategies

A single "catch-all" endpoint can be configured for certain types of routers. See Using Message Routers.

<service name="dataService"> <inbound> <inbound-endpoint ref="dataIn"> <payload-type-filter expectedType="java.lang.String"/> </inbound-endpoint> <forwarding-catch-all-strategy> <jms:outbound-endpoint queue="error.queue"/> </forwarding-catch-all-strategy> </inbound> ...cut...</service>

Exception Strategies

A single error endpoint can be configured on an exception strategy. See Error Handling.

<service name="dataService"> <inbound> ...cut... </inbound> <component class="com.acme.DataProcessor"/> <outbound> ...cut... </outbound> <default-service-exception-strategy> <jms:outbound-endpoint queue="error.queue"/> </default-service-exception-strategy></service>

Global Endpoints

Global endpoints, while not required, are a recommended best practice for having a nicely organizedconfiguration file. A global endpoint can be thought of as a template for shared endpoint configuration.Global endpoints can be used as they are defined globally, or they can be extended by adding moreconfiguration attributes or elements.

Page 313: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 313

To reference a global endpoint, use the usual <inbound-endpoint> and <outbound-endpoint> elements,and specify the global endpoint name using the ref attribute.

<file:endpoint name="fileReader" reverseOrder="true" comparator="org.mule.transport.file.comparator.OlderFirstComparator"/>...cut...

<model> <service name="Priority1"> <file:inbound-endpoint ref="fileReader" path="/var/prio1"/> ...cut... </service>

<service name="Priority2"> <file:inbound-endpoint ref="fileReader" path="/var/prio2"/> ...cut... </service></model>

In the above example, the "fileReader" endpoint is used as a template for the inbound endpoints. Theproperties reverseOrder and comparator only need to be declared once, and the property path changesfor each inbound endpoint.

Page 314: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 314

Mule Endpoint URIs

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

Mule Endpoint URIs

Although URI-based endpoints are still supported in Mule 2.0, transport-specific endpointsare generally recommended instead.

Mule Endpoint URIs are any valid URI and describe how to connect to the underlying transport. Mostconnectors in Mule can be created from an endpoint URI except where not enough connection informationcan be expressed clearly in a URI, such as JMS connection properties. Endpoint URIs are set on MuleEndpoints, which manage other connection instance information such as filters and transactions.

Mule Endpoint URIs usually appear in one of the following forms, although other providerimplementations can introduce their own schemes.

scheme://host[:port]//[address][?params]

The scheme must always be set. The host and port are set for endpoints that use unwrapped socketbased communications such as the TCP, UDP, HTTP, or multicast.

udp://localhost:65432

scheme://[username][:password]@host[:port][?params]

The user name and password are used to log in to the remote server specified by the host and portparameters. The POP3 and SMTP connectors use this format or URI.

pop3://ross:[email protected]

smtp://ross:[email protected]

scheme://address[?params]

Here we only define a protocol and an address. This tells Mule to get a connector that handles thespecified scheme, or create one if needed, and to create a new endpoint using the specified address.

vm://my.queue

URI Parameters

There are two types of parameters you can set on the URI:

1. Known Mule parameters that control the way the endpoint is configured, such as transformers forthe endpoint.

2. Properties to be set on the connector or to be associated with the transport. This allows you toset properties on a connector used by this endpoint. Additionally, all properties will be associatedwith the transport, so you can mix connector and transport properties. For more information, seeConfiguring Endpoints.

Known Parameters

Property Description

connector The name of an existing connector to use for thisendpoint URI

Page 315: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 315

transformers Defines a comma-separated list of transformers toconfigure on the endpoint

address Explicitly sets the endpoint address to thespecified value and ignores all other info in theURI.

For example:

file:///C:/temp?transformers=FileToString,XmlToDom

jms://jmsEndpoint/topic:my.topic?connector=WMQConnector

Other Parameters

Any other parameters set on the URI will be set on the connector if a connector is created and also set onthe endpoint itself as properties.

Endpoint Encoding

When using XML configuration, certain character entities defined in the W3C SGML specification needto be escaped to their SGML code. The most relevant are listed here. Don't forget to remove the spacebefore the ';'.

For characters such as > < " % #, the notation will be resolved and cause the constructor for the URI tothrow an exception. To use one of these characters, you can specify %HEXNUMBER

Text code Numerical code What it looks like Description, extras

%22 #34 " quotation mark =APL quote, U+0022ISONEW

&amp ; #38 & ampersand, U+0026ISOnum

%3C #60 < less-than sign, U+003CISOnum

%3E #62 > greater-than sign, U+003E ISOnum

%25 #37 % percentage sign, U+0023 ISOnum

%23 #35 # hash sign, U+0025ISOnum

Additionally, for connectors such as Axis, FTP, and the Email connectors, if your login credentials include@, you must escape it using %40. For example, instead of these URIs:

axis:http://wsuser@username:password@localhost/services/services/Version?method=getVersionftp://username:password@ftpserversmtp://'[email protected]':'123456'@mailserver?address=QA

You must use these:

axis:http://wsuser%40username:password%40localhost/services/services/Version?method=getVersionftp://username:password%40ftpserversmtp://'sender%40mydomain.com':'123456'%40mailserver?address=QA

Page 316: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 316

Using Filters

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

Using Filters

[ Standard Filters ] [ Transport and Module Filters ] [ Creating Custom Filters ]

Filters specify conditions that must be met for a message to be routed to a service. There are severalstandard filters that come with Mule that you can use, or you can create your own filters.

You can create a global filter and then reference it from your services. Global filters require the "name"attribute, whereas filters configured on endpoints or routers do not.

<!-- Globally defined filter with name attribute --><payload-type-filter name="payloadFilter" expectedType="java.lang.String">

<model> <service> <inbound> <tcp:inbound-endpoint host="locahost" port="1234"> <!-- Here we reference the filter defined globally using it for this endpoint --> <filter ref="payloadFilter"/> </tcp:inbound-endpoint> </inbound> <echo-component/> <service></model>

For reference to the configuration of each filter, see Filters Configuration Reference.

Standard Filters

Mule includes the following standard filters that you can apply to your routers:

• Payload Type Filter• Expression Filter• ° Using JXPath Expressions

° Using OGNL Expressions• RegEx Filter• Wildcard Filter• Exception Type Filter• Message Property Filter• Logic Filters• ° And Filter

° Or Filter° Not Filter

Payload Type Filter

Checks the class type of the payload object inside a message.

<payload-type-filter expectedType="java.lang.String">

Page 317: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 317

Expression Filter

Evaluates a range of expressions. Use the evaluator attribute to specify the expression evaluator touse, one of the following: header, payload-type, exception-type, wildcard, regex, ognl, xpath, jxpath,bean, groovy, or custom. Use the expression attribute to set the actual expression. If the expressiontype is xpath, bean, or ognl, the expression should be a boolean. If the expression type is custom, setthe customEvaluator attribute to the name of the custom evaluator, which must be registered with theExpressionEvaluatorManager (see Creating Custom Filters). For more information on using expressionevaluators, see Using Expression Evaluators.

Optionally, set the nullReturnsTrue attribute to true if you want to return true whenever theexpression is null.

Using JXPath Expressions

JXPath is an XPath interpreter that can apply XPath expressions to XML DOM objects or any other objectgraph. For more information about JXPath, see the JXpath user guide, JXPath tutorial, or XPath tutorial.

<expression-filter evaluator="jxpath" expression="(msg/header/resultcode)='success'">

You can also use the JXPath filter from the XML Module, which supports some additional properties.

Using OGNL Expressions

OGNL is a simple yet very powerful expression language for plain Java objects. Similar to JXPath, itworks on object graphs, and thus the corresponding filter enables simple and efficient content routing forpayloads. For example:

<expression-filter evaluator="ognl" expression="[MULE:0].equals(42)"/>

or more simply:

<ognl-filter expression="[MULE:0].equals(42)"/>

This filter would block any messages whose payloads are not arrays or lists and do not contain the value42 as the first element.

RegEx Filter

Applies a regular expression pattern to the message payload. The filter applies toString() to thepayload, so you might also want to apply a PayloadTypeFilter to the message using an AndFilter to makesure the payload is a String.

<regex-filter pattern="the quick brown (.*)"/>

Wildcard Filter

Applies a wildcard pattern to the message payload. The filter applies toString() to the payload, so youmight also want to apply a PayloadTypeFilter to the message using an AndFilter to make sure the payloadis a String.

Page 318: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 318

For the string "the quick brown fox jumped over the lazy dog", the following patterns would match:

• *x jumped over the lazy dog• the quick*• *fox*

<wildcard-filter pattern="the quick brown *"/>

Exception Type Filter

A filter that matches an exception type.

<exception-type-filter expectedType="java.lang.RuntimeException"/>

Message Property Filter

This filter allows you add logic to your routers based on the value of one or more properties of amessage. This filter can be very powerful because the message properties are exposed, allowing you toreference any transport-specific or user-defined property. For example, you can match one or more HTTPheaders for an HTTP event, match properties in JMS and email messages, and more.

By default, the comparison is case sensitive. You can set the caseSensitive attribute to override thisbehavior.

<message-property-filter pattern="Content-Type=text/xml" caseSensitive="false"/>

The expression is always a key value pair. If you want to use more complex expressions, you can use thelogic filters. The following example shows two filters :

<and-filter> <message-property-filter pattern="JMSCorrelationID=1234567890"/> <message-property-filter pattern="JMSReplyTo=null"/></and-filter>

Logic Filters

There are three logic filters that can be used with other filters: And, Or, and Not. Logic filters can benested so that more complex logic can be expressed.

And Filter

An And filter combines two filters and only accepts the message if it matches the criteria of both filters.

<and-filter> <payload-type-filter expectedType="java.lang.String"/> <regex-filter pattern="the quick brown (.*)"/>

Page 319: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 319

</and-filter>

Or Filter

The Or filter considers two filters and accepts the message if it matches the criteria of either one of thefilters.

<or-filter> <payload-type-filter expectedType="java.lang.String"/> <payload-type-filter expectedType="java.lang.StringBuffer"/></or-filter>

Not Filter

A Not filter accepts the message if it does not match the criteria in the filter.

<not-filter> <payload-type-filter expectedType="java.lang.String"/></not-filter>

Transport and Module Filters

Several Mule transports and modules provide their own filters. For example, the XML Module includes afilter to determine if a message is XML. For more information, see Available Transports and Using MuleModules. Also, there are filters on MuleForge that have been contributed by the community.

Creating Custom Filters

The standard filters handle most filtering requirements, but you can also create your own filter. To createa filter, implement the Filter interface , which has a single method:

public boolean accept(MuleMessage message);

This method returns true if the message matches the criteria that the filter imposes. Otherwise, it returnsfalse.

You can then use this filter with the <custom-filter...> element, using the class attribute to specifythe custom filter class you created and specifying any necessary properties using the <spring:property>child element. For example:

<outbound> <filtering-router> <cxf:outbound-endpoint address="http://localhost:65071/services/EnterOrder?method=create" synchronous="true"/> <custom-filter class="org.mule.transport.http.filters.HttpRequestWildcardFilter"> <spring:property name="pattern" value="/services/EnterOrder?wsdl"/> </custom-filter> </filtering-router>

Page 320: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 320

</outbound>

Page 321: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 321

Configuring a Transport

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

Configuring a Transport

You can configure a transport in the following ways:

• Define a connector configuration using the <connector> element in the Mule XML configuration file.• Set transport properties on endpoints to customize the transport behavior for a single endpoint

instance.• Use an endpoint URI that defines the scheme and connection information for the transport, such

as tcp://localhost:12345. See Mule Endpoint URIs for more information. The URI consists of theprotocol followed by transport-specific information, and then zero or more parameters to set asproperties on the connector.

This page describes the common properties for all transports. The actual configuration parameters foreach transport type are described separately for each transport. To see the details of a specific transport,see Available Transports.

Common Connector Attributes and Properties

Attribute Description Required

name The identifying name of theconnector

Yes

createMultipleTransactedReceivers Whether to create multipleconcurrent receivers for thisconnector. This property isused by transports that supporttransactions, specificallyreceivers that extend theTransactedPollingMessageReceiver,and provides better throughput.

No

numberOfConcurrentTransactedReceiversIfcreateMultipleTransactedReceiversis set to true, the number ofconcurrent receivers that will belaunched.

No

dynamicNotification Whether to enable dynamicnotification.

No

Property Description Default Required

abstract-exception-strategy

The exception strategyto use when errorsoccur in the connector.

The default exceptionstrategy set on theMule Configuration.

No

receiver-threading-profile

The threadingproperties andWorkManager to usewhen receiving eventsfrom the connector.

The default receiverthreading profile set onthe Mule Configuration

Yes

Page 322: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 322

dispatcher-threading-profile

The threadingproperties andWorkManager to usewhen dispatchingevents from theconnector.

The default dispatcherthreading profile set onthe Mule Configuration.

Yes

connection-strategy The object responsiblefor controlling howconnection failures andretries are handled.The connection strategycan attempt to makea connection basedon frequency, retryattempts, Jmx, or someother trigger. NOTE:this feature is not yetavailable for 2.0.

org.mule.transport.SingleAttemptConnectionStrategy

Yes

service-overrides A map of serviceconfiguration valuesthat can be used tooverride the defaultconfiguration for thistransport.

No

Retry Policies

Retry policies are used to configure how a connector behaves when its connection fails. For completeinformation, see Configuring Retry Policies.

Creating Your Own Transport

For information on creating a custom transport for Mule, see Creating Transports.

Detailed Configuration Information

• Threading profiles° Receiver threading profile° Dispatcher threading profile

• Service overrides

Receiver Threading Profile

The threading profile to use when a connector receives messages.

Attributes of <receiver-threading-profile...>

Name Type Required Default Description

maxThreadsActive integer no The maximumnumber of threadsthat will be used.

Page 323: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 323

maxThreadsIdle integer no The maximumnumber of idle orinactive threadsthat can be in thepool before theyare destroyed.

threadTTL integer no Determines howlong an inactivethread is kept inthe pool beforebeing discarded.

poolExhaustedAction WAIT/DISCARD/DISCARD_OLDEST/ABORT/RUN

no When themaximum poolsize or queue sizeis bounded, thisvalue determineshow to handleincoming tasks.Possible valuesare: WAIT(wait until athread becomesavailable; don'tuse this valueif the minimumnumber of threadsis zero, in whichcase a threadmay neverbecome available),DISCARD(throw away thecurrent requestand return),DISCARD_OLDEST(throw away theoldest requestand return),ABORT (throw aRuntimeException),and RUN (thedefault; thethread making theexecute requestruns the taskitself, which helpsguard againstlockup).

threadWaitTimeout integer no How long to waitin millisecondswhen the poolexhaustedaction is WAIT.If the value isnegative, it willwait indefinitely.

doThreading boolean no true Whether threadingshould be used(default is true).

Page 324: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 324

maxBufferSize integer no Determines howmany requestsare queued whenthe pool is atmaximum usagecapacity and thepool exhaustedaction is WAIT.The buffer is usedas an overflow.

Dispatcher Threading Profile

The threading profile to use when a connector dispatches messages.

Attributes of <dispatcher-threading-profile...>

Name Type Required Default Description

maxThreadsActive integer no The maximumnumber of threadsthat will be used.

maxThreadsIdle integer no The maximumnumber of idle orinactive threadsthat can be in thepool before theyare destroyed.

threadTTL integer no Determines howlong an inactivethread is kept inthe pool beforebeing discarded.

poolExhaustedAction WAIT/DISCARD/DISCARD_OLDEST/ABORT/RUN

no When themaximum poolsize or queue sizeis bounded, thisvalue determineshow to handleincoming tasks.Possible valuesare: WAIT(wait until athread becomesavailable; don'tuse this valueif the minimumnumber of threadsis zero, in whichcase a threadmay neverbecome available),DISCARD(throw away thecurrent requestand return),DISCARD_OLDEST

Page 325: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 325

(throw away theoldest requestand return),ABORT (throw aRuntimeException),and RUN (thedefault; thethread making theexecute requestruns the taskitself, which helpsguard againstlockup).

threadWaitTimeout integer no How long to waitin millisecondswhen the poolexhaustedaction is WAIT.If the value isnegative, it willwait indefinitely.

doThreading boolean no true Whether threadingshould be used(default is true).

maxBufferSize integer no Determines howmany requestsare queued whenthe pool is atmaximum usagecapacity and thepool exhaustedaction is WAIT.The buffer is usedas an overflow.

Service Overrides

Service overrides allow the connector to be further configured/customized by allowing parts ofthe transport implementation to be overridden, for example, the message receiver or dispatcherimplementation, or the message adaptor that is used.

Attributes of <service-overrides...>

Name Type Required Default Description

messageReceiver name (no spaces) no

transactedMessageReceivername (no spaces) no

xaTransactedMessageReceivername (no spaces) no

dispatcherFactory name (no spaces) no

inboundTransformer name (no spaces) no

outboundTransformername (no spaces) no

Page 326: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 326

responseTransformer name (no spaces) no

endpointBuilder name (no spaces) no

messageAdapter name (no spaces) no

streamMessageAdaptername (no spaces) no

serviceFinder name (no spaces) no

sessionHandler name (no spaces) no

Page 327: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 327

Configuring Retry Policies

This page last changed on Mar 24, 2009 by jwheeler.

Configuring Retry Policies

[ Configuring Retry Policies with the Retry Schema ] [ Retry Simple Policy ] [ Retry Forever Policy ] [Retry Custom Policy ] [ Retry Connect Notifier ] [ Retry Custom Notifier ] [ Creating a Custom Retry Policy] [ Configuring Retry Policies with the Spring Schema ]

Retry policies configure how a connector behaves when its connection fails. Different policies can be usedto control how a reconnection is made based on type of exception, number and/or frequency of retryattempts, notifications, and more.

For example, assume you are using the FTP transport and have a polling receiver set to poll every 1000ms, and the connection is down. The polling receiver will try to connect (and fail) once every 1000 ms,using up resources and filling up your log files. It will continue to fail indefinitely until you manually stopthe process. Additionally, it leaves the system in an unstable state, because the connector is theoretically"connected" even though it's constantly failing. With a retry policy, you can better control the behaviorwhen a connection fails, such as setting the connector to retry the connection once every 15 minutes andto give up after 30 attempts. You can also send an automatic notification to your IT administrator whenthe retry policy goes into effect. You can even define a policy that only retries during business hours,which is useful if you server is frequently shut down for maintenance at night, for example.

When using the FTP transport, and you are using synchronous inbound and outbound endpoints, allinbound messages would fail if the connection went down and you weren't using retry policies. With retrypolicies, you will lose the first message that fails, since FTP is not transactional, but once a retry policygoes into effect, no further messages will be accepted by the inbound endpoint until the connection is re-established.

Retry policies are available for the JDBC, JMS, and FTP transports only.

If you are using the Enterprise Edition of Mule, there are several standard retry policies available that youcan configure using the Retry schema. If you are using the Community Edition of Mule, you must createyour own policies and configure them using standard Spring syntax rather than the Retry schema.

Configuring Retry Policies with the Retry Schema

This section describes the retry policies you can configure directly in your XML by including the mule-ee.xsd schema. You import the schema as follows:

<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ee="http://www.mulesource.org/schema/mule/ee/core/2.2" xsi:schemaLocation=" http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/ee/core/2.2 http://www.mulesource.org/schema/mule/ee/core/2.2/mule-ee.xsd">

Retry Simple Policy

A retry policy that allows the user to configure how many times a retry should be attempted and howlong to wait between retries.

Page 328: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 328

Attributes of <retry-simple-policy...>

Name Type Required Default Description

asynchronous boolean no false Whether the retrypolicy should runin a separate,non-blockingthread

frequency long no 2000 How often (in ms)to retry

count integer no 2 How many retryattempts to make

For example:

<jms:activemq-connector name="AMQConnector" brokerURL="tcp://localhost:61616" specification="1.1" durable="true" clientId="C1" numberOfConcurrentTransactedReceivers="1" maxRedelivery="-1" persistentDelivery="true"> <ee:retry-simple-policy count="5" frequency="1000"/></jms:activemq-connector>

Retry Forever Policy

A retry policy that retries an infinite number of times at the specified frequency.

Attributes of <retry-forever-policy...>

Name Type Required Default Description

asynchronous boolean no false Whether the retrypolicy should runin a separate,non-blockingthread

frequency long no 2000 How often (in ms)to retry

For example (most of the connector information is truncated as ...):

<jms:activemq-connector name="AMQConnector" ...> <ee:retry-forever-policy frequency="5000"/></jms:activemq-connector>

Retry Custom Policy

A user-defined retry policy.

Page 329: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 329

Attributes of <retry-custom-policy...>

Name Type Required Default Description

asynchronous boolean no false Whether the retrypolicy should runin a separate,non-blockingthread

class class name no A class thatimplements theRetryPolicyTemplateinterface.

Child Elements of <retry-custom-policy...>

Name Cardinality Description

spring:property 0..*

For example:

<jms:activemq-connector name="AMQConnector" ...> <ee:retry-custom-policy class="org.mule.retry.test.TestRetryPolicyTemplate"> <spring:property name="fooBar" value="true"/> <spring:property name="revolutions" value="500"/> </ee:retry-custom-policy></jms:activemq-connector>

Asynchronous Retry

By default, a retry policy will block until it is able to connect/reconnect. Enabling asynchronous retrymeans the application does not need to wait for all endpoints to connect before it can start up, and if aconnection is lost, the reconnection will happen in a separate thread from the application thread. Notethat such behavior may or may not be desirable depending on your application. Asynchronous retry isavailable as of version 2.2.

Any retry policy can be made asynchronous by simply setting the attribute asynchronous="true". Forexample:

<jms:activemq-connector name="AMQConnector" ...> <ee:retry-simple-policy frequency="3000" asynchronous="true" /></jms:activemq-connector>

Transactions

If transactions are properly configured, any messages being routed by Mule at the time a retry policygoes into effect will not be dropped. Instead, the transaction will roll back and only commit once thetransport finally reconnects successfully via the retry policy.

Page 330: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 330

Retry Notifiers

A retry notifier is called upon each retry attempt and is also configurable.

Retry Connect Notifier

Fires a ConnectionNotification upon each retry attempt.

For example:

<jms:activemq-connector name="AMQConnector" ...> <ee:retry-simple-policy> <ee:retry-connect-notifier/> </ee:retry-simple-policy></jms:activemq-connector>

Retry Custom Notifier

A user-defined retry notifier.

Attributes of <retry-custom-notifier...>

Name Type Required Default Description

class class name no A class thatimplements theRetryNotifierinterface.

Child Elements of <retry-custom-notifier...>

Name Cardinality Description

spring:property 0..*

For example:

<jms:activemq-connector name="AMQConnector" ...> <ee:retry-simple-policy> <ee:retry-custom-notifier class="org.mule.retry.test.TestRetryNotifier"> <spring:property name="color" value="red"/> </ee:retry-custom-notifier> </ee:retry-simple-policy></jms:activemq-connector>

Configuring Separate Connectors for Inbound and Outbound

The retry policy for a connector is used for both inbound and outbound connections. If you requirea different behavior for inbound and outbound connections, you can achieve this by configuring two

Page 331: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 331

connectors with the different policies and reference them from the inbound and outbound endpoints,respectively.

Default Retry Policy

The default retry policy is used for any connector that does not have retry explicitly configured. You canset the default policy using the <configuration> element:

<configuration> <ee:retry-simple-policy count="3"/></configuration>

Creating a Custom Retry Policy

To create a custom retry policy, you implement the interface RetryPolicy , where the methodPolicyStatus applyPolicy(Throwable cause) takes some action based on the type of exceptionand returns PolicyStatus to indicate whether the policy has been exhausted or should continue to retry.You also create a RetryPolicyTemplate , which is what you actually configure on the connector. Thetemplate should generally inherit from AbstractPolicyTemplate and have the method RetryPolicycreateRetryInstance() return an instance of your custom RetryPolicy. At runtime, a new instanceof the RetryPolicy will be created each time the policy goes into effect, thereby resetting any stateinformation it may contain, such as counters.

For example:

package com.acme.retry;

public class AstronomicalRetryPolicyTemplate extends AbstractPolicyTemplate{ int totalPlanets; public RetryPolicy createRetryInstance() { return new AstronomicalRetryPolicy(totalPlanets); }

protected static class AstronomicalRetryPolicy implements RetryPolicy { int totalPlanets; public AstronomicalRetryPolicy(int totalPlanets) { this.totalPlanets = totalPlanets; }

public PolicyStatus applyPolicy(Throwable cause) { if (AstronomyUtils.getPlanetsAligned() == totalPlanets) { return PolicyStatus.policyExhausted(cause); } else { Thread.sleep(5000); return PolicyStatus.policyOk(); } } } public int getTotalPlanets() { return totalPlanets; } public void setTotalPlanets(int totalPlanets) { this.totalPlanets = totalPlanets; }

Page 332: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 332

}

Configuring Retry Policies with the Spring Schema

Because the retry schema is available in Mule Enterprise Edition only, Mule Community users must usestandard Spring syntax for configuring a custom retry policy. For example:

<jms:activemq-connector name="AMQConnector" ...> <spring:property name="retryPolicyTemplate"> <spring:bean class="com.acme.retry.AstronomicalRetryPolicyTemplate"> <spring:property name="totalPlanets" value="8"/> </spring:bean> </spring:property></jms:activemq-connector>

Page 333: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 333

Configuring Logging

This page last changed on Nov 11, 2008 by jackie.wheeler.

Configuring Logging

[ Troubleshooting Logging ] [ Controlling Logging from JMX ]

For logging, Mule uses slf4j, which is a logging facade that discovers and uses a logging strategy from theclasspath, such as Log4J or the JDK Logger. By default, Mule includes Log4J, which is configured with afile called log4j.properties.

The Mule server has a log4j.properties in its conf directory, which you can customize when runningthe server in standalone mode. Additionally, all the examples included with Mule have log4j.propertiesfiles in their conf directories.

Troubleshooting Logging

I don't see any logging output

A log4j.properties file must be at the root of your classpath. If you don't have a log4j.propertiesfile, you can get a simple one here. For more information about configuring Log4J, see their website.

I reconfigured Log4J, but nothing happened

This happens because there is another log4j.properties file on your classpath that is getting picked upbefore your modified one. To find out which configuration file Log4J is using, you must add the followingJVM parameter to the Mule startup script (or container startup script if you are embedding Mule):

-Dlog4j.debug=true

This parameter will write the Log4J startup information, including the location of the configuration filebeing used, to stdout. You must remove that configuration file before your modified configuration willwork.

I don't want to use Log4J

You can remove Log4J by deleting log4j-xx.jar from your Mule classpath. You will then need to checkthat the logging system you are using is supported by slf4j and put the necessary JAR (unless usingJDK1.4 Logger) and configuration files on the Mule classpath.

Controlling Logging from JMX

You can expose a manager's logging configuration over JMX by configuring a Log4J Jmx agent in yourMule configuration file. See JMX Management for more information.

Page 334: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 334

Configuring Queues

This page last changed on Nov 06, 2008 by jackie.wheeler.

Configuring Queues

[ SEDA Service Queues ] [ Transport Queues ] [ Queue Configuration ] [ Queue Profile ]

Mule uses queues to enable asynchronous message processing. This page describes the places whereMule uses queues and how to configure them. Note that you can use Mule HQ to monitor your queuesand see historically how many messages they have contained. For more information, see Using Mule HQ.

SEDA Service Queues

When requests come in to a SEDA service (the default model type), they are stored on a queue untilthreads from the component thread pool can pick them up and process them. The queue profile specifieshow this queue behaves. Typically, you do not need to configure the queue profile for performance, as theendpoints or the component, and not the queue, are the usual bottleneck. However, you might want tospecify the maximum queue size, or specify that you want to enable persistence on the queue (disabledby default) to store a copy of all messages processed by the component.

When a SEDA service is stopped either by calling stop() on the service or by shutting down Mule,all messages still in the queue are processed before the service completes the stop phase if a non-persistent queue is being used. If a persistent queue is being used, Mule will complete the processing ofany messages that are currently being processed but will not take any new messages from the queueonce the service has been requested to stop. Once the service or Mule is restarted, any messages in thepersistent queue will be processed.

Note: If a SEDA service is paused when stop() is called, and a non-persistent queue is being used, allmessages pending processing in the queue will be lost.

By using persistent SEDA queues and using transports that support persistence for any message channelsthat Mule uses internally, you can easily achieve graceful shutdown. Although message loss shouldn'toccur if you design your system using these guidelines, if messages are absolutely critical, you should beusing synchronous endpoints with transactions.

Transport Queues

Transports may also uses queues internally to enable asynchronous message delivery. Often this isinherent in the transport implementation, such as with JMS, whereas the Mule VM Transport allows you toenable or disable queuing and to configure the queue.

Queue Configuration

You configure the queue profile using the <queue-profile> element on the model and/or services,where services inherit the queue configuration from the model but override it if a <queue-profile> isconfigured explicitly on a service.

Queue Profile

Specifies the properties of an internal Mule queue. Internal queues are used to queue messages for eachcomponent managed by Mule.

Attributes of <queue-profile...>

Name Type Required Default Description

Page 335: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 335

maxOutstandingMessagesinteger no Defines themaximum numberof messages thatcan be queued.

persistent boolean no false Whether Mulemessages arepersisted to astore. Primarily,this is used forpersisting queuedmessages todisk so that theinternal stateof the server ismirrored on diskin case the serverfails and needsto be restarted.Default is false.

Persistence Strategies

By default, Mule use two persistence strategies:

• MemoryPersistenceStrategy : a volatile in-memory persistence strategy• FilePersistenceStrategy : uses a file store to persist messages to disk and maintains messages even

if Mule is restarted.

You specify the persistence strategy to use by setting the persistent attribute of the queue-profile.If set to true, the FilePersistenceStrategy is used, and if false, the MemoryPersistenceStrategy isused.

Currently, you cannot configure alternative persistence strategies as part of the typed Mule XMLconfiguration. However, if you need to change them, such as to persist to a database instead of disk, youcan override the defaults in mule-default-config.xml by redefining the _muleQueueManager bean inyour own configuration file. Custom persistence strategies must implement QueuePersistenceStrategy .

Page 336: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 336

Configuring Security

This page last changed on Mar 24, 2009 by jwheeler.

Configuring Security

Mule allows you to authenticate requests via endpoints using transport-specific or generic authenticationmethods. It also allows you to control method-level authorization on your service components. TheSecurity Manager is responsible for authenticating requests based on one or more security providers. Allsecurity is pluggable via the Mule security API , so you can easily plug in custom implementations.

Acegi

Acegi provides a number of authentication and authorization providers such as JAAS, LDAP, CAS (YaleCentral Authentication service), and DAO. The following topics will help you get started securing yourservices using Acegi:

• Configuring the Acegi Security Manager• Component Authorization Using Acegi• Setting up LDAP Provider for Acegi

Spring Security 2.0

(Available as of Mule 2.2) Spring Security is the next version of Acegi and provides a number ofauthentication and authorization providers such as JAAS, LDAP, CAS (Yale Central Authentication service),and DAO. The following topics will help you get started securing your services using Spring Security:

• Configuring the Spring Security Manager• Component Authorization Using Spring Security• Setting up LDAP Provider for Spring Security

Other Security Integration

Mule also supports the following security technologies:

• Encryption Strategies - Secure your messages by encrypting them.• PGP Security - Secure your messages by encrypting them with PGP.• Enabling WS-Security - Secure your CXF SOAP endpoints with WS-Security.• Jaas Security

Page 337: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 337

Component Authorization Using Acegi

This page last changed on Mar 24, 2009 by jwheeler.

Component Authorization Using Acegi

[ Securing Service Components ] [ Setting Security Properties on the Security Provider ]

This page describes how you can configure method-level authorization on your components so that userswith different roles can only invoke certain service methods.

Securing Service Components

To secure MethodInvocations, developers must add a properly configured MethodSecurityInterceptorinto the application context. The beans requiring security are chained into the interceptor. This chainingis accomplished using Spring's ProxyFactoryBean or BeanNameAutoProxyCreator. Alternatively,Acegi security provides a MethodDefinitionSourceAdvisor, which you can use with Spring'sDefaultAdvisorAutoProxyCreator to automatically chain the security interceptor in front of any beansdefined against the MethodSecurityInterceptor.

In addition to the daoAuthenticationProvider and inMemoryDaoImpl beans (see Configuring Security),the following beans must be configured:

• MethodSecurityInterceptor• AuthenticationManager• AccessDecisionManager• AutoProxyCreator• RoleVoter

The MethodSecurityInterceptor

The MethodSecurityInterceptor is configured with a reference to an:

• AuthenticationManager• AccessDecisionManager

Following is a security interceptor for intercepting calls made to the methods of a component that has aninterface myComponentIfc, which defines two methods: delete and writeSomething. Roles are set onthese methods as seen below in the property objectDefinitionSource.

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mule="http://www.mulesource.org/schema/mule/core/2.2" xmlns:acegi="http://www.mulesource.org/schema/mule/acegi/2.2" ...cut... <bean id="myComponentSecurity" class="org.acegisecurity.intercept.method.aopalliance.MethodSecurityInterceptor"> <property name="authenticationManager" ref="authenticationManager"/> <property name="accessDecisionManager" ref="accessDecisionManager"/> <property name="objectDefinitionSource"> <value> com.foo.myComponentIfc.delete=ROLE_ADMIN com.foo.myComponentIfc.writeSomething=ROLE_ANONYMOUS </value> </property> </bean>

Page 338: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 338

The AuthenticationManager

An AuthenticationManager is responsible for passing requests through a chain ofAuthenticationProvider objects.

<bean id="authenticationManager" class='org.acegisecurity.providers.ProviderManager'> <property name= "providers"> <list> <ref local="daoAuthenticationProvider"/> </list> </property></bean>

The AccessDecisionManager

This bean specifies that a user can access the protected methods if they have any one of the rolesspecified in the objectDefinitionSource.

<bean id="accessDecisionManager" class='org.acegisecurity.vote.AffirmativeBased'> <property name="decisionVoters"> <list> <ref bean="roleVoter"/> </list> </property></bean>

The AutoProxyCreator

This bean defines a proxy for the protected bean. When an application asks Spring for a myComponentbean, 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 configurationmust contain the property proxyTargetClass set to true. Otherwise, the method passed toMethodSecurityInterceptor.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 casesensitive on comparisons as well as the ROLE_ prefix.

Page 339: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 339

• 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 withROLE.

• If there is no exact match of any ConfigAttribute starting with ROLE_, the RoleVoter will vote todeny access.

• If no ConfigAttribute begins with ROLE_, the voter will abstain.

<bean id="roleVoter" class="org.acegisecurity.vote.RoleVoter"/>

Setting Security Properties on the Security Provider

You can add any additional properties to the security provider in the securityProperties map. Forexample, this map can be used to change Acegi's default security strategy into one of the following:

• MODE_THREADLOCAL, which allows the authentication to be set on the current thread (this is thedefault 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

Securing Components in Asynchronous Systems

The use of Acegi's security strategies is particularly useful when using an asynchronous system, since wehave to add a property on the security provider for the authentication to be set on more than one thread.

In this case, we would use MODE_GLOBAL as seen in the example below.

<acegi:security-manager> <acegi:delegate-security-provider name="memory-dao" delegate-ref="daoAuthenticationProvider"> <acegi:security-property name="securityMode" value="MODE_GLOBAL"/> </acegi:delegate-security-provider></acegi:security-manager>

Page 340: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 340

Component Authorization Using Spring Security

This page last changed on Mar 24, 2009 by dandiep.

Component Authorization Using SpringSecurity

[ Securing Service Components ] [ Setting Security Properties on the Security Provider ]

This page describes how you can configure method-level authorization using Spring Security on yourcomponents so that users with different roles can only invoke certain service methods. Spring Security isavailable as of Mule 2.2.

Securing Service Components

To secure MethodInvocations, you must add a properly configured MethodSecurityInterceptor intothe application context. The beans requiring security are chained into the interceptor. This chainingis accomplished using Spring's ProxyFactoryBean or BeanNameAutoProxyCreator. Alternatively,Spring Security provides a MethodDefinitionSourceAdvisor, which you can use with Spring'sDefaultAdvisorAutoProxyCreator to automatically chain the security interceptor in front of any beansdefined against the MethodSecurityInterceptor.

In addition to the daoAuthenticationProvider and inMemoryDaoImpl beans (see Configuring Security},the following beans must be configured:

• MethodSecurityInterceptor• AuthenticationManager• AccessDecisionManager• AutoProxyCreator• RoleVoter

The MethodSecurityInterceptor

The MethodSecurityInterceptor is configured with a reference to the following:

• AuthenticationManager• AccessDecisionManager

Following is a security interceptor for intercepting calls made to the methods of a component that has aninterface myComponentIfc, which defines two methods: delete and writeSomething. Roles are set onthese methods as seen below in the property objectDefinitionSource.

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mule="http://www.mulesource.org/schema/mule/core/2.2" xmlns:mule-ss="http://www.mulesource.org/schema/mule/spring-security/2.2" ...cut... <bean id="myComponentSecurity" class="org.springframework.security.intercept.method.aopalliance.MethodSecurityInterceptor"> <property name="authenticationManager" ref="authenticationManager"/> <property name="accessDecisionManager" ref="accessDecisionManager"/> <property name="objectDefinitionSource"> <value> com.foo.myComponentIfc.delete=ROLE_ADMIN com.foo.myComponentIfc.writeSomething=ROLE_ANONYMOUS </value> </property>

Page 341: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 341

</bean>

The AuthenticationManager

This bean is responsible for passing requests through a chain of AuthenticationProvider objects.

<bean id="authenticationManager" class="org.springframework.security.providers.ProviderManager"> <property name= "providers"> <list> <ref local="daoAuthenticationProvider"/> </list> </property></bean>

The AccessDecisionManager

This bean specifies that a user can access the protected methods if they have any one of the rolesspecified in the objectDefinitionSource.

<bean id="accessDecisionManager" class='org.springframework.security.vote.AffirmativeBased'> <property name="decisionVoters"> <list> <ref bean="roleVoter"/> </list> </property></bean>

The AutoProxyCreator

This bean defines a proxy for the protected bean. When an application asks Spring for a myComponentbean, 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 configurationmust contain the property proxyTargetClass set to true. Otherwise, the method passed toMethodSecurityInterceptor.invoke is the proxy's caller, not the proxy's target.

Page 342: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 342

The RoleVoter

The RoleVoter class will vote if any ConfigAttribute begins with ROLE_. The RoleVoter is casesensitive on comparisons as well as the ROLE_ prefix.

• It will vote to grant access if there is a GrantedAuthority, which returns a String representation(via the getAuthority() method) exactly equal to one or more ConfigAttribute objects startingwith ROLE.

• If there is no exact match of any ConfigAttribute starting with ROLE_, the RoleVoter will vote todeny access.

• If no ConfigAttribute begins with ROLE_, the voter will abstain.

<bean id="roleVoter" class="org.springframework.security.vote.RoleVoter"/>

Setting Security Properties on the Security Provider

You can add any additional properties to the security provider in the securityProperties map. Forexample, this map can be used to change Spring Security's default security strategy into one of thefollowing:

• MODE_THREADLOCAL: allows the authentication to be set on the current thread (this is the defaultstrategy used by Spring Security)

• MODE_INHERITABLETHREADLOCAL: allows authentication to be inherited from the parent thread• MODE_GLOBAL: allows the authentication to be set on all threads

Securing Components in Asynchronous Systems

The use of Spring Securitysecurity strategies is particularly useful for asynchronous systems, since wehave to add a property on the security provider for the authentication to be set on more than one thread.In this case, we would use MODE_GLOBAL as shown in the following example:

<mule-ss:security-manager> <mule-ss:delegate-security-provider name="memory-dao" delegate-ref="authenticationManager"> <mule-ss::security-property name="securityMode" value="MODE_GLOBAL"/> </mule-ss::delegate-security-provider></mule-ss:security-manager>

Page 343: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 343

Configuring the Acegi Security Manager

This page last changed on Dec 16, 2008 by jackie.wheeler.

Configuring the Acegi Security Manager

The Mule Acegi security manager implementation delegates to Acegi to provide authorization andauthentication functions. You can use any of the Acegi security providers such as JAAS, LDAP, CAS (YaleCentral Authenication service), and DAO.

Example Configuration

The following example illustrates how to configure a single security provider on Mule, in this case anin-memory DAO. Here we have a static DAO security provider that allows user credentials to be set inmemory with two users: ross and anon.

<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:acegi="http://www.mulesource.org/schema/mule/acegi/2.2" ...cut...

<spring:bean id="inMemoryDaoImpl" class="org.acegisecurity.userdetails.memory.InMemoryDaoImpl"> <spring:property name="userMap"> <spring:value> ross=ross,ROLE_ADMIN anon=anon,ROLE_ANONYMOUS </spring:value> </spring:property> </spring:bean>

<spring:bean id="daoAuthenticationProvider" class="org.acegisecurity.providers.dao.DaoAuthenticationProvider"> <spring:property name="userDetailsService" ref="inMemoryDaoImpl"/> </spring:bean>

<acegi:security-manager> <acegi:delegate-security-provider name="memory-dao" delegate-ref="daoAuthenticationProvider"/> </acegi:security-manager> ...cut...</mule>

Security Filters

Security filters can be configured on an object to either authenticate inbound requests or attachcredentials to outbound requests. For example, to configure an HTTP basic authorization filter on an HTTPendpoint, you would use the following endpoint security filter:

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

When a request is received, the authentication header will be read from the request and authenticatedagainst all security providers on the Security Manager. If you only want to validate on certain ones, youcan supply a comma-separated list of security provider names.

Page 344: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 344

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

Page 345: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 345

Configuring the Spring Security Manager

This page last changed on Feb 20, 2009 by jackie.wheeler.

Configuring the Spring Security Manager

[ Example ] [ Security Filters ]

As of Mule 2.2, you can use Spring Security 2.0 as a Security Manager inside of Mule. You can use any ofthe library's security providers such as JAAS, LDAP, CAS (Yale Central Authenication service), and DAO.

Example

The following example illustrates how to configure a single security provider on Mule, in this case anin-memory database of users. To configure the provider, we set up a <user-service> element and the<authentication-manager> to which Mule delegates.

<?xml version="1.0" encoding="UTF-8"?><mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:http="http://www.mulesource.org/schema/mule/http/2.2" xmlns:mule-ss="http://www.mulesource.org/schema/mule/spring-security/2.2" xmlns:ss="http://www.springframework.org/schema/security" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/http/2.2 http://www.mulesource.org/schema/mule/http/2.2/mule-http.xsd http://www.mulesource.org/schema/mule/spring-security/2.2http://www.mulesource.org/schema/mule/spring-security/2.2/mule-spring-security.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.xsd">

<mule-ss:security-manager> <mule-ss:delegate-security-provider name="memory-provider" delegate-ref="authenticationManager" /> </mule-ss:security-manager>

<spring:beans> <ss:authentication-manager alias="authenticationManager" />

<ss:authentication-provider> <ss:user-service id="userService"> <ss:user name="ross" password="ross" authorities="ROLE_ADMIN" /> <ss:user name="anon" password="anon" authorities="ROLE_ANON" /> </ss:user-service> </ss:authentication-provider> </spring:beans> ...cut...</mule>

Security Filters

Security filters can be configured on an object to either authenticate inbound requests or attachcredentials to outbound requests. For example, to configure an HTTP basic authorization filter on an HTTPendpoint, you would use the following endpoint security filter:

Page 346: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 346

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

When a request is received, the authentication header will be read from the request and authenticatedagainst all security providers on the Security Manager. If you only want to validate on certain ones, youcan supply a comma-separated list of security provider names.

<inbound-endpoint address="http://localhost:4567"> <mule-ss:http-security-filter realm="mule-realm" securityProviders="default,another"/></inbound-endpoint>

Page 347: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 347

Encryption Strategies

This page last changed on Dec 16, 2008 by jackie.wheeler.

Encryption Strategies

The Security Manager can be configured with one or more encryption strategies that can then beused by encryption transformers, security filters, or secure transports such as SSL or HTTPS. Theseencryption strategies can greatly simplify configuration for secure messaging as they can be sharedacross components.

Following is an example of a password-based encryption strategy (PBE) that provides password-basedencryption using JCE. Users must specify a password and optionally a salt and iteration count as well. Thedefault algorithm is PBEWithMD5AndDES, but users can specify any valid algorithm supported by JCE.

<security-manager> <password-encryption-strategy name="PBE" password="mule"/></security-manager>

This strategy can then be referenced by other components in the system such as filters or transformers.

<decrypt-transformer name="EncryptedToByteArray" strategy-ref="PBE"/>

<service name="Svc1"> <inbound> <inbound-endpoint address="vm://test"> <encryption-security-filter strategy-ref="PBE"/> </inbound-endpoint> </inbound> ...cut...

<service name="Svc2"> ...cut... <outbound> <pass-through-router> <outbound-endpoint address="vm://output" transformer-refs="EncryptedToByteArray"/> </pass-through-router> </outbound>

Page 348: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 348

Setting up LDAP Provider for Acegi

This page last changed on Dec 16, 2008 by jackie.wheeler.

Setting Up an LDAP Provider for Acegi

[ Declaring the Beans ] [ Configuring the Mule Security Provider ] [ Configuring theMethodSecurityInterceptor ]

This page describes how you can configure an Acegi LDAP provider, which can be:

• Used by Mule as its security provider via AcegiProviderAdapter• Used by Acegi/Spring to perform Component Authorization

For information on configuring an in-memory DAO provider, see Configuring Security.

Declaring the Beans

You must set up two beans in Spring, an InitialDirContextFactory and an LdapAuthenticationProvider.The InitialDirContextFactory is the access point for obtaining an LDAP context where theLdapAuthenticationProvider provides integration with the LDAP server. For example:

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mule="http://www.mulesource.org/schema/mule/core/2.2" xmlns:acegi="http://www.mulesource.org/schema/mule/acegi/2.2" ...cut...

<bean id="initialDirContextFactory" class="org.acegisecurity.ldap.DefaultInitialDirContextFactory"> <constructor-arg value="ldap://localhost:389/dc=com,dc=foobar" /> <property name="managerDn"> <value>cn=root,dc=com,dc=foobar</value> </property> <property name="managerPassword"> <value>secret</value> </property> </bean>

<bean id="authenticationProvider" class="org.acegisecurity.providers.ldap.LdapAuthenticationProvider"> <constructor-arg> <bean class="org.acegisecurity.providers.ldap.authenticator.BindAuthenticator"> <constructor-arg> <ref local="initialDirContextFactory" /> </constructor-arg> <property name="userDnPatterns"> <list> <value>uid={0},ou=people</value> </list> </property> </bean> </constructor-arg> <constructor-arg> <bean class="org.acegisecurity.providers.ldap.populator.DefaultLdapAuthoritiesPopulator"> <constructor-arg> <ref local="initialDirContextFactory" /> </constructor-arg> <constructor-arg> <value>ou=groups</value> </constructor-arg> <property name="groupRoleAttribute"> <value>cn</value> </property>

Page 349: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 349

<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>

Configuring the Mule Security Provider

The AcegiProviderAdapter delegates to an AuthenticationProvider such as theLdapAuthenticationProvider.

<acegi:security-manager> <acegi:delegate-security-provider name="acegi-ldap" delegate-ref="authenticationProvider"/></acegi:security-manager>

With the above configuration, you can achieve endpoint-level security and other security features in Mulethat require one or more security providers.

Configuring the MethodSecurityInterceptor

The configuration for component authorization is similar to the one described in Component AuthorizationUsing Acegi. A key point of configuration is ObjectDefinitionSource:

<property name="objectDefinitionSource" value="org.mule.api.lifecycle.Callable.onCall=ROLE_MANAGERS"/>

The roles are looked up by the DefaultLdapAuthoritiesPopulator, which you configured in theprevious section. By default, a role is prefixed with ROLE_ and its value is extracted (and converted touppercase) from the LDAP attribute defined by the groupRoleAttribute.

Page 350: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 350

Setting up LDAP Provider for Spring Security

This page last changed on Mar 24, 2009 by dandiep.

Setting Up an LDAP Provider for SpringSecurity

[ Declaring the Beans ] [ Configuring the Mule Security Provider ] [ Configuring theMethodSecurityInterceptor ]

This page describes how you can configure a Spring Security LDAP provider, which can be used by Mule2.2 or later as follows:

• As its security provider via SpringProviderAdapter• To perform component authorization

For information on configuring an in-memory provider, see Configuring Security.

Declaring the Beans

You must set up two beans in Spring, an InitialDirContextFactory and an LdapAuthenticationProvider.The InitialDirContextFactory is the access point for obtaining an LDAP context where theLdapAuthenticationProvider provides integration with the LDAP server. For example:

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mule="http://www.mulesource.org/schema/mule/core/2.2" xmlns:mule-ss="http://www.mulesource.org/schema/mule/spring-security/2.2" ...cut...

<bean id="initialDirContextFactory" class="org.springframework.security.ldap.DefaultInitialDirContextFactory"> <constructor-arg value="ldap://localhost:389/dc=com,dc=foobar" /> <property name="managerDn"> <value>cn=root,dc=com,dc=foobar</value> </property> <property name="managerPassword"> <value>secret</value> </property> </bean>

<bean id="authenticationProvider" class="org.springframework.security.providers.ldap.LdapAuthenticationProvider"> <constructor-arg> <bean class="org.springframework.security.providers.ldap.authenticator.BindAuthenticator"> <constructor-arg ref="initialDirContextFactory" /> <property name="userDnPatterns"> <list> <value>uid={0},ou=people</value> </list> </property> </bean> </constructor-arg> <constructor-arg> <bean class="org.springframework.security.providers.ldap.populator.DefaultLdapAuthoritiesPopulator"> <constructor-arg ref="initialDirContextFactory"/> <constructor-arg value="ou=groups"/> <property name="groupRoleAttribute" value="ou"/> </bean>

Page 351: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 351

</constructor-arg> </bean>

Configuring the Mule Security Provider

The SpringSecurityProviderAdapter delegates to an AuthenticationProvider such as theLdapAuthenticationProvider.

<mule-ss:security-manager> <mule-ss:delegate-security-provider name="spring-security-ldap" delegate-ref="authenticationManager"/></mule-ss:security-manager>

With the above configuration, you can achieve endpoint-level security and other security features in Mulethat require one or more security providers.

Configuring the MethodSecurityInterceptor

The configuration for component authorization is similar to the one described in Component AuthorizationUsing Spring Security. A key point of configuration is ObjectDefinitionSource:

<property name="objectDefinitionSource" value="org.mule.api.lifecycle.Callable.onCall=ROLE_MANAGERS"/>

The roles are looked up by the DefaultLdapAuthoritiesPopulator, which you configured in theprevious section. By default, a role is prefixed with ROLE_, and its value is extracted and converted touppercase from the LDAP attribute defined by the groupRoleAttribute.

Page 352: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 352

Upgrading from Acegi to Spring Security

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

Upgrading from Acegi to Spring Security

[ Adding the Namespaces ] [ Updating the Acegi Package Names ] [ Using an AuthenticationManager ] [Simplifying the Configuration ]

Spring Security is version 2.0 of the Acegi Security framework. Upgrading your Mule application to useSpring Security instead of Acegi involves the following steps:

1. Adding the necessary namespaces to your Mule configuration2. Updating the Acegi package names3. Updating your Mule configuration to use an AuthenticationManager4. Simplification using new Spring Security elements

Adding the Namespaces

Your Mule configuration file should have the following namespaces declared.

<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:mule-ss="http://www.mulesource.org/schema/mule/spring-security/2.2" xmlns:ss="http://www.springframework.org/schema/security" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/spring-security/2.2 http://www.mulesource.org/schema/mule/spring-security/2.2/mule-spring-security.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.xsd">...</mule>

The mule-ss namespace is for the Mule Spring Security extensions. The ss namespace is for the SpringSecurity schema elements that are not Mule specific and allows you to use the less verbose XML that ispart of Spring Security 2.0.

Updating the Acegi Package Names

Except for the changed package names, the Spring Security API has remained compatible with Acegi. Forexample, assume you configured a DaoAuthenticationProvider like this one:

<bean class="org.acegisecurity.providers.dao.DaoAuthenticationProvider"> <property name="userDetailsService" ref="userService"/></bean>

To use Spring Security, you simply change the acegisecurity package to springframework.security:

<bean class="org.springframework.security.providers.dao.DaoAuthenticationProvider">

Page 353: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 353

<property name="userDetailsService" ref="userService"/></bean>

Repeat this step for all your Acegi bean definitions.

Using an AuthenticationManager

The only major difference between Mule integration with Acegi and Spring Security is that the latteruses the AuthenticationManager to provider authentication functions, while the former tied in at theAcegi AuthenticationProvider level. With the Acegi provider, the authentication flow followed thisprogression:

AcegiProviderAdapter (Mule) -> AuthenticationProvider (Acegi)

With the new Spring Security adapter, it follows this progression:

SpringProviderAdapter (Mule) -> AuthenticationManager (Spring Security) -> AuthenticationProvider (Spring Security)

This allows the authentication manager to try multiple authentication providers to authenticate yourmessages.

Configuration of this approach requires a little more XML. For example, consider this originalconfiguration:

<mule ...> <acegi:security-manager> <acegi:delegate-security-provider name="memory-dao" delegate-ref="daoAuthenticationProvider"/> </acegi:security-manager> <spring:bean id="inMemoryDaoImpl" class="org.acegisecurity.userdetails.memory.InMemoryDaoImpl"> <spring:property name="userMap"> <spring:value> ross=ross,ROLE_ADMIN anon=anon,ROLE_ANONYMOUS </spring:value> </spring:property> </spring:bean>

<spring:bean id="daoAuthenticationProvider" class="org.acegisecurity.providers.dao.DaoAuthenticationProvider"> <spring:property name="userDetailsService" ref="inMemoryDaoImpl"/> </spring:bean> </mule>

To upgrade this configuration, you add an AuthenticationManager. This would result in the following:

<mule ...> <mule-ss:security-manager> <mule-ss:delegate-security-provider name="memory-dao" delegate-ref="authenticationManager"/> </mule-ss:security-manager>

Page 354: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 354

<spring:bean id="inMemoryDaoImpl" class="org.springframework.security.userdetails.memory.InMemoryDaoImpl"> <spring:property name="userMap"> <spring:value> ross=ross,ROLE_ADMIN anon=anon,ROLE_ANONYMOUS </spring:value> </spring:property> </spring:bean>

<spring:bean id="daoAuthenticationProvider" class="org.springframework.security.providers.dao.DaoAuthenticationProvider"> <spring:property name="userDetailsService" ref="inMemoryDaoImpl"/> </spring:bean>

<spring:bean id="authenticationManager" class="org.springframework.security.providers.ProviderManager"> <spring:property name="providers"> <spring:list> <spring:ref bean="daoAuthenticationProvider"/> </spring:list> </spring:property> </spring:bean></mule>

Simplifying the Configuration

Spring Security 2.0 includes new XML syntax that can simplify configurations, especially in simple cases.For example, the previous example has an in-memory user database, a DAO authentication provider, andan authentication manager. This can be simplified to:

<mule ...> <mule-ss:security-manager> <mule-ss:delegate-security-provider name="memory-dao" delegate-ref="authenticationManager" /> </mule-ss:security-manager>

<spring:beans> <ss:authentication-manager alias="authenticationManager" />

<ss:authentication-provider> <ss:user-service id="userService"> <ss:user name="ross" password="ross" authorities="ROLE_ADMIN" /> <ss:user name="anon" password="anon" authorities="ROLE_ANON" /> </ss:user-service> </ss:authentication-provider> </spring:beans></mule>

The <authentication-manager> element defines the name of our AuthenticationManager bean.We then create a single AuthenticationProvider with the <authentication-provider and <user-service> elements. This <user-service> is the same as our InMemoryDaoImpl above.

For more information on how to configure Acegi, see the following Spring documentation:

• Spring Security Documentation• Spring Security Javadoc• Spring Security XML Schema reference

Page 355: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 355

Controlling the Infrastructure with Mule Galaxy

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

Controlling the Infrastructure with Mule Galaxy

Mule Galaxy helps you get control over your infrastructure by providing the following features:

• Governance: provides a centralized control point for policy management and compliance, ensuringthat your SOA adheres to your firm's policies.

• Registry: automatically detects and displays dependencies among services and manages servicelifecycles.

• Repository: stores and manages artifacts (including Mule configuration files, web servicesframeworks, and any other artifact), providing version management and collaborative comments,and allows you to publish the artifacts in a web browser using the Atom Publishing Protocol.

Mule Galaxy can be deployed either alongside Mule or as a standalone component in an enterprise's SOAinfrastructure. Mule Galaxy is available with Mule Enterprise Edition.

For complete information on Mule Galaxy, see the Mule Galaxy site.

Page 356: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 356

Creating a Custom XML Namespace

This page last changed on Mar 25, 2009 by jwheeler.

Creating a Custom XML Namespace

XML schema definitions are used for each module to define the objects and properties that the modulemakes available to Mule. These configuration elements are introduced using a namespace for eachmodule and associating the namespace with the schema. This page describes how configuration ishandled in Mule and what steps are required when writing a new module or transport in Mule.

Advantages of Using Namespaces

The use of namespaces provides the following advantages:

• Class names are removed from XML so that implementation details are hidden.• All objects introduced by the module are self-contained by a namespace.• The schema provides a domain-specific language (DSL) for the module where all objects and

properties are described in the schema with type validation.• The schema can provide additional validation for types, value ranges, and required properties.

Using Module Schemas

Schemas are located in each package's main/resources/META-INF directory. The core schema is in themule-core package, the TCP schema is in the tcp package, and so on.

The Mule schema can be used directly or embedded inside Spring. In addition, Spring beans can becreated directly inside the Mule schema (just use <spring:bean .../>) and elements from othernamespaces can be placed in <other>...</other>.

Mule Namespace

The default namespace for Mule xml configuration files is mule:

<?xml version="1.0" encoding="UTF-8"?><mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.mulesource.org/schema/mule/core/2.2 META-INF/mule.xsd"> <!-- Mule config here --> <spring:bean ...you can also embed Spring bean definitions directly.../>

<spring:beans> <!-- and you can have nested spring definitions --> </spring:beans></mule>

Note here we have a spring namespace declared so we can embed spring beans directly inside your Muleconfiguration file.

Page 357: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 357

More on Mixing Mule and Spring

The Mule schema includes the ability to use Spring elements at certain points by including<spring:bean> inside <mule>. These elements are handled explicitly by Mule code, which delegates theirprocessing to Spring.

Be careful when using Spring elements in your own schema, and check that they behave as expected.The <bean> and <beans> elements are all forwarded to Spring for processing. In addition, the predefinedmule:mapType can be used and, when associated with the ChildMapDefinitionParser, will automaticallyconstruct a map using Spring's <entry> elements (this is the only way that <entry> can be useddirectly inside Mule elements). For examples, see the use of mapType in the Mule schema. Similarbehavior with ChildPropertiesDefinitionParser should also be possible (but ChildMapEntry andChildListEntryDefinitionParsers are unrelated to Spring).

Other namespaces can be introduced via <spring:beans> or by adding a dedicated element in a module(see the Scripting module's <lang> element).

Documentation

You add documentation to the schema using the <xsd:annotation> and <xsd:documentation> tags:

<xsd:element name="my-element" type="myType"> <xsd:annotation> <xsd:documentation>This element does this</xsd:documentation> </xsd:annotation></xsd:element><xsd:complexType name="myType"> <xsd:annotation> <xsd:documentation>This type does that</xsd:documentation> </xsd:annotation></xsd:complexType>

While documentation can be added in various places within the schema, tools that use this informationfollow certain conventions (see below). As a consequence, embedded documentation should:

• Be placed in the element, attribute, or associated type• Avoid duplicating information in element and type• Avoid reference elements (<xsd:element ref="..."/>)• Make documentation at each level correct and distinct (do not rely on inheritance, but try to avoid

duplication)

IntelliJ Idea

Idea will show documentation defined for an element or attribute, or for the associated type if those aremissing. The information is displayed when the user presses Ctrl-J. For more information see this postabout how to work with Mule schemas in IntelliJ.

Eclipse

The Web Tools Platform (WTP) XML editor shows documentation defined for an element or attribute, orfor the associated type if those are missing. The information is displayed when you press F2 when anelement or attribute is selected or has the cursor on it. The same information is also shown when usingthe context-sensitive auto-completion functionality by pressing the "CTRL-." key combination.

The WTP XML editor will display "inherited" documentation but does not show documentation associatedwith referenced global elements.

Page 358: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 358

Writing Configuration Handlers

When writing a new Mule transport of module, you will need to write a schema definition and the codenecessary to parse the XML, but most of the work is done for you. The following section will walk throughthe process of:

• Defining the XML Schema: Describes all the objects that your module exposes, such astransformers, components, filters, routers, agents, etc.

• Writing the Namespace Handler: Responsible for configuring the XML parsers for each of theelements that your schema defines.

• Writing a Definition Parser for each of the elements (objects) defined in the schema• Testing your Namespace Handler

Defining the Schema

If you are not familiar with XML schema, you may want to take an introductory course here. However,Mule defines most of what you need out of the box, so it's fairly straightforward to jump in and write yourown. Following are a few key concepts:

• Complex Types are defined for each object in the module. Complex types define the elements andattributes that make up the type. For example, a connectorType would define shared attributes forall connectors and define any nested elements such as <service-overrides>.

<xsd:complexType name="connectorType" mixed="true"> <xsd:choice minOccurs="0" maxOccurs="unbounded"> <xsd:element name="receiver-threading-profile" type="threadingProfileType" minOccurs="0" maxOccurs="1"/> <xsd:element name="dispatcher-threading-profile" type="threadingProfileType" minOccurs="0" maxOccurs="1"/> <xsd:group ref="exceptionStrategies" minOccurs="0" maxOccurs="1"/> <xsd:element name="service-overrides" type="serviceOverridesType" minOccurs="0" maxOccurs="1"/> </xsd:choice>

<xsd:attribute name="name" type="xsd:string" use="required"/> <xsd:attribute name="createDispatcherPerRequest" type="xsd:boolean"/> <xsd:attribute name="createMultipleTransactedReceivers" type="xsd:boolean"/></xsd:complexType>

Note that complex types can be extended (much like inheritance), so new complex types canbe built upon existing ones. Mule provides a number of base complex types out of the box forconnectors, agents, transformers, and routers. If you write one of these, your schema shouldextend the corresponding complex type. Using TCP as an example, here is an excerpt from wherewe define the noProtocolTcpConnectorType:

<xsd:import namespace="http://www.mulesource.org/schema/mule/core/2.2"/>

<xsd:complexType name="noProtocolTcpConnectorType"> <xsd:complexContent> <xsd:extension base="mule:connectorType"> <xsd:attribute name="sendBufferSize" type="mule:substitutableInt"> <xsd:annotation> <xsd:documentation> The size of the buffer (in bytes) used when sending data, set on the socket itself. </xsd:documentation> </xsd:annotation> </xsd:attribute> <xsd:attribute name="receiveBufferSize" type="mule:substitutableInt"> <xsd:annotation> <xsd:documentation>

Page 359: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 359

The size of the buffer (in bytes) used when receiving data, set on the socket itself. </xsd:documentation> </xsd:annotation> </xsd:attribute> ... <xsd:attribute name="validateConnections" type="mule:substitutableBoolean"> <xsd:annotation> <xsd:documentation> This "blips" the socket, opening and closing it to validate the connection when first accessed. </xsd:documentation> </xsd:annotation> </xsd:attribute> </xsd:extension> </xsd:complexContent></xsd:complexType>

This complex type extends the mule:connectorType type. Notice that we need to import the Mulecore schema since that is where the connectorType is defined.

Schema Types

Note that the types we use for int, boolean, and all numeric types are custom typescalled substitutableInt or substitutableBoolean. These types allow for int valuesand boolean values but also allow developers to use property placeholders, suchas ${tcp.keepAlive} as a valid value for the property. These placeholders will bereplaced at run-time by real values defined in property files.

Element definitions describe what elements are available in the schema. An element has a type, whichshould be declared as a Complex Type. For example:

<xsd:element name="connector" type="tcpConnectorType"/>

This makes the connector element available within the tcp namespace.

The schema should be called mule-<short module name>.xsd and stored in the META-INF of the moduleor transport.

Versioning

In Mule, the version of the schema is maintained in the schema URI. This means that the namespace andthe targetNamespace implicitly contain the schema version. Schema URIs use the following convention:

http://www.mulesource.org/schema/mule/core/2.2

The first part of the URI http://www.mulesource.org/schema/mule/ is the same for each schema. It isthen followed by the module's short name, followed by the version of the schema.

Schema Mapping

To stop the XML parser from loading Mule schemas from the Internet, you add a mapping file that mapsthe remote schema location to a local classpath location. This mapping is done in a simple properties filecalled spring.schemas located in the META-INF directory for the module/transport.

http\://www.mulesource.org/schema/mule/tcp/2.2/mule-tcp.xsd=META-INF/mule-tcp.xsd

Page 360: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 360

Namespace Handler

The namespace handler is responsible for registering definition parsers, so that when an element in theconfiguration is found, it knows which parser to use to create the corresponding object.

A namespace handler is a single class that is directly associated with a namespace URI. To make thisassociation, there needs to be a file called spring.handlers in the root of the META-INF directory of themodule or transport. The file contains the following:

http\://www.mulesource.org/schema/mule/tcp/2.2=org.mule.transport.tcp.config.TcpNamespaceHandler

The TcpNamespaceHandler code is very simple because there is a base support class provided:

public class TcpNamespaceHandler extends NamespaceHandlerSupport{ public void init() { registerBeanDefinitionParser("connector", new OrphanDefinitionParser(TcpConnector.class, true)); }}

Here, there should be one or more registrations binding an element name with a definition parser.

Definition Parsers

The definition parser is where the actual object reference is created. It includes some Spring-specificclasses and terminology, so it's worth reading this introduction.

Mule already includes a number of useful definition parsers that can be used for mostsituations or extended to suit your needs. You can also create a custom definitionparser. The following table describes the existing parsers. To see how they are used, seeorg.mule.config.spring.handlers.MuleNamespaceHandler .

Parser Description

org.mule.config.spring.parsers.generic.OrphanDefinitionParserContructs a single, standalone bean from anelement. It is not injected into any other object.This parser can be configured to automaticallyset the class of the object, the init and destroymethods, and whether this object is a singleton.

org.mule.config.spring.parsers.generic.ChildDefinitionParserCreates a definition parser that will constructa single child element and inject it into theparent object (the enclosing XML element). Theparser will set all attributes defined in the XMLas bean properties and will process any nestedelements as bean properties too, except thecorrect definition parser for the element will belooked up automatically. If the class is read froman attribute (when class is null), it is checkedagainst the constraint. It must be a subclass ofthe constraint.

org.mule.config.spring.parsers.generic.ParentDefinitionParserProcesses child property elements in XML butsets the properties on the parent object. This isuseful when an object has lots of properties and

Page 361: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 361

it's more readable to break those properties intogroups that can be represented as a sub-elementin XML.

org.mule.config.spring.parsers.collection.ChildMapEntryDefinitionParserAllows a series of key value pair elements to beset on an object as a Map. There is no need todefine a surrounding 'map' element to containthe map entries. This is useful for key value pairmappings.

org.mule.config.spring.parsers.AbstractChildBeanDefinitionParserThis definition parser introduces the notionof hierarchical processing to nested XMLelements. Definition parsers that extendthis class are always child beans that getset on the parent definition parser. A singlemethod getPropertyName must be overridento specify the name of the property to seton the parent bean with this bean. Notethat the property name can be dynamicallyresolved depending on the parent element. Thisimplementation also supports collections andMaps. If the bean class for this element is set toMapEntryDefinitionParser.KeyValuePair, it isassumed that a Map is being processed and anychild elements will be added to the parent Map.

org.mule.config.spring.parsers.AbstractMuleSingleBeanDefinitionParserThis parser extends the Spring providedAbstractBeanDefinitionParser to provideadditional features for consistently customizingbean representations for Mule bean definitionparsers. Most custom bean definition parsersin Mule will use this base class. The followingenhancements are made:

• Attribute mappings can be registered tocontrol how an attribute name in Mule XMLmaps to the bean name in the object beingcreated.

• Value mappings can be used to map keyvalue pairs from selection lists in the XMLschema to property values on the bean beingcreated. These are a comma-separated listof key=value pairs.

• Provides an automatic way of setting theinit-method and destroy-method for thisobject. This will then automatically wire thebean into the lifecycle of the applicationcontext.

• The singleton property provides a fixedway to make sure the bean is always asingleton or not.

Naming Conventions

The number and variety of definition parsers is growing rapidly. To make them more manageable, pleaseuse the following conventions.

• Group by function. Abstract bases live in org.mule.config.spring.parsers. Under that we havegeneric, specific, and collection, which should be self-explanatory. Inside those you may wantto add further grouping (e.g., specific.security).

• Use consistent names for the relationship of the object being created with the surrounding context:° Child objects are injected into parents (the enclosing DOM element)° Grandchild are like child, but recurse up the DOM tree more than one generation° Orphan objects stand alone

Page 362: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 362

° Named objects are injected into a target identified by name rather than DOM location.° Parent definition parsers are something like facades, providing an alternative interface to the

parent.

Testing

Testing the namespace handler is pretty simple. You configure the object in Mule XML, start the server,and check that the values have been set correctly. For example:

public class TcpNamespaceHandlerTestCase extends FunctionalTestCase{ protected String getConfigResources() { return "tcp-namespace-config.xml"; }

public void testConfig() throws Exception { TcpConnector c = (TcpConnector)managementContext.getRegistry().lookupConnector("tcpConnector"); assertNotNull(c); assertEquals(1024, c.getReceiveBufferSize()); assertEquals(2048, c.getSendBufferSize()); assertEquals(50, c.getReceiveBacklog()); assertEquals(3000, c.getReceiveTimeout()); assertTrue(c.isKeepAlive()); assertTrue(c.isConnected()); assertTrue(c.isStarted());

}}

Extending Existing Handlers

Instead of creating a new handler, you can extend an existing transport and add new properties andelements. For example, the SSL transport extends the TCP transport.

<?xml version="1.0" encoding="UTF-8" standalone="no"?><xsd:schema xmlns="http://www.mulesource.org/schema/mule/ssl/2.2" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:mule="http://www.mulesource.org/schema/mule/core/2.2" xmlns:tcp="http://www.mulesource.org/schema/mule/tcp/2.2" targetNamespace="http://www.mulesource.org/schema/mule/ssl/2.2" elementFormDefault="qualified" attributeFormDefault="unqualified">

<xsd:import namespace="http://www.w3.org/XML/1998/namespace"/> <xsd:import namespace="http://www.mulesource.org/schema/mule/core/2.2" schemaLocation="http://www.mulesource.org/schema/mule/core/2.2/mule.xsd" /> <xsd:import namespace="http://www.mulesource.org/schema/mule/tcp/2.2" schemaLocation="http://www.mulesource.org/schema/mule/tcp/2.2/mule-tcp.xsd"/>

<xsd:element name="connector" substitutionGroup="mule:abstract-connector"> <xsd:annotation> <xsd:documentation> Connect Mule to an SSL socket, to send or receive data via the network. </xsd:documentation> </xsd:annotation> <xsd:complexType> <xsd:complexContent> <xsd:extension base="tcp:tcpConnectorType">

Page 363: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 363

<xsd:sequence> <xsd:element minOccurs="0" maxOccurs="1" name="client" type="mule:tlsClientKeyStoreType"/> <xsd:element minOccurs="0" maxOccurs="1" name="key-store" type="mule:tlsKeyStoreType"/> <xsd:element minOccurs="0" maxOccurs="1" name="server" type="mule:tlsServerTrustStoreType"/> <xsd:element minOccurs="0" maxOccurs="1" name="protocol-handler" type="mule:tlsProtocolHandler"/> </xsd:sequence> </xsd:extension> </xsd:complexContent> </xsd:complexType> </xsd:element>

Simple Recipe

The following recipe is sufficient for a simple transport (like UDP). The ordering helps guarantee completecoverage.

1. Write a test case for the connector.a. Use IDE's auto completion to test each public getter (as a first approximation to the public API

- tidy by hand).b. Set the test value to something other than the default.

2. Write the XML configuration for the connector (test/resources/foo-connector-test.xml) usingthe properties from the test (make sure the import section is correct).

3. Write the schema definition (tweaking until the XML connector config shows no errors) (META-INF/mule-foo.xsd).

4. Write the namespace handler (and any needed definition parsers) (src/main/java/org/mule/providers/foo/config/FooNamespaceHandler)

5. Set the Spring handler mapping (META-INF/spring.handlers).6. Set the local schema mapping (META-INF/spring.schemas).7. Make sure the test runs.8. Check properties against the documentation and make consistent (but note that things like

connection strategy parameters are handled by an embedded element that is itself inherited fromthe connectorType) and then re-run the test.

Resources

• A useful set of PDF slides that give an overview of the new approach in Spring and (slides29 on) given an introductory example. The Mule code is more complex, but follows the samestructure: org.mule.config.spring.handlers.MuleNamespaceHandler is the namespace handler;org.mule.config.spring.parsers.AbstractMuleBeanDefinitionParser and subclasses are thebean definition parsers.

• A couple of blog posts (1, 2) that give a developer's-eye overview.• Useful papers on mutable/extensible containers 1, 2

Page 364: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 364

Creating Custom Routers

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

Creating Custom Routers

Typically, you implement custom routing with filters, but occasionally you may need to implement acustomer router.

Custom Outbound Routers

Outbound routers control how a message gets routed to a list of endpoints. For example, sometimes amessage gets routed based on simple rules or business logic, whereas in other cases you may multicast amessage to every router.

The easiest way to write an outbound router is to extend theorg.mule.routing.outbound.AbstractOutboundRouter class:

import org.mule.routing.outbound.AbstractOutboundRouter;

public class CustomOutboundRouter extends AbstractOutboundRouter {....}

There are two methods you must implement that control how messages will be routed through thesystem. First, you must implement the isMatch method. This determines if a message should beprocessed by the router.

For example, to route only messages that have a payload containing the string "hello":

public boolean isMatch(MuleMessage message) throws RoutingException{ return "hello".equals(message.getPayloadAsString());}

The second method you must implement is the route method. Each outbound router has a list ofendpoints that are associated with it. The route method contains the logic to control how the event ispropagated to the endpoints.

For example, if there were two endpoints you want to route to based on a condition, you would use thismethod to select the endpoint:

MuleMessage route(MuleMessage message, MuleSession session, boolean synchronous) throws MessagingException { OutboundEndpoint ep = null; if (isConditionMet(message)) { ep = getEndpoints().get(0); } else { ep = getEndpoints().get(1); }....

Once you've selected an endpoint, you must then dispatch or send the message to it based on whether ornot the message is synchronous:

Page 365: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 365

try { if (synchronous) { return send(session, message, ep); } else { dispatch(session, message, ep); return null; } } catch (MuleException e) { throw new CouldNotRouteOutboundMessageException(message, ep, e); } return result;}

If the request is synchronous, you must use the send method to send the inbound messagessynchronously to the endpoint. The result from this is then returned. If the request is asynchronous, it issent using the dispatch method, and no response message is returned.

Custom Inbound Routers

Inbound routers control whether a message is consumed by an inbound endpoint. Typically, you do nothave to create custom routers, as the existing ones provide a high degree of customization using existingor custom filters.

If a new inbound router class is needed, it will typically extend theorg.mule.routing.inbound.SelectiveConsumerrouter. This class uses the Mule filter APIs to determine if a message should be consumed and can beconfigured using the existing filters.

The other responsibility of inbound routers is to control how a message is processed by a service. It canchoose to:

• Consume the message and start a new message.• Aggregate several messages.• Forward an incoming message to an outbound transport and skip the service invocation.• Pass on the original message.

For more information, examine the source code for the available inbound routers.

Page 366: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 366

Creating Transports

This page last changed on Feb 09, 2009 by jackie.wheeler.

Creating Transports

[ Overview ] [ Transport Interfaces ] [ Implementation ] [ Connectors ] [ Message Receivers ] [ MessageDispatchers ] [ Message Requesters ] [ Service Descriptors ] [ Coding Standards ] [ Package Structure ]

Transports are used to implement message channels and provide connectivity to an underlying datasource or message channel in a consistent way. Mule provides transports for many different protocols,including File, FTP, HTTP, JMS, JDBC, Quartz, and many more. For a complete list, see AvailableTransports. There are also community-created transports on MuleForge. If you need to send messages ona protocol other than those provided, you can create a new transport.

Overview

When creating a new transport, you must implement a set of Mule interfaces in the org.mule.transportpackage, and then extend the provided abstract classes. For a quick start, you can use the Maventransport archetype as a code template for your transports. If you want to update an existing transport,use the Module Archetype instead.

Mule transports can be one of the following types:

1. inbound-only: Components can only subscribe to events. They cannot dispatch events.2. outbound-only: Components can only dispatch events. They cannot subscribe to events.3. inbound-outbound: Components can subscribe and dispatch events

Transport Interfaces

A transport consists of a set of interface implementations that expose the features for the underlyingtransport. Cannot resolve external resource into attachment.

Interface Role

Connector Used to manage Receivers, Dispatchers andRequesters and to store any configurationinformation.

Message Receiver Implements the server part of the transport.For example, a TcpMessageReceiver creates aserver socket to receive incoming requests. AMessageReceiver instance is created when thistransport is used for inbound communication.

Message Dispatcher Implements the client part of the transport. Forexample, a TcpMessageDispatcher opens a socketto send requests. A MessageDispatcher instanceis created when this transport for outboundcommunication.

Message Requester Is also used to receive incoming messages like theMessageReceiver but rather than subscribing toinbound events or polling a resource or messagechannel messages are only received on "request".Inbound endpoints on services always use aMessageReceiver rather than a MessageRequesterbut they can be used elsewhere programatically to

Page 367: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 367

request a single message from a message channelor resource.

Message Adapter Is contained within the message and acts as abridge between the underlying message type usedby this transport and a MuleMessage. Forexample, the JMS message adapter exposesMule methods such as getPayload() to provideaccess to the payload of the JMS message, andall headers and user properties are accessible asmessage properties.

Transformers Transformers are used to convert databetween the transport-specific data formatand another format, such as from an HTTPresponse to a string. The dispatcher must callMuleEvent.transformMessage() to transform themessage.

Endpoints The means of configuring the use of messagechannels or resource as part of serviceconfiguration. The endpoint defines whichtransport to use and includes settings like the hostor queue name, the filter to use, and transactioninfo. Defining an endpoint on a service will causeMule to create the necessary transport connectorfor the protocol being used.

When writing a transport, you must implement the following interfaces that define the contract betweenMule and the underlying technology.

org.mule.api.transport.Connector

The connector is used by Mule to register listeners and create message dispatchers for the transport.Configuration parameters that should be shared by all Message Receivers, Dispatchers and Requestersare stored on the connector. Usually, only one connector instance is needed for multiple inbound andoutbound endpoints as multiple Message Receivers, Dispatchers and Requesters can be associated witha connector. However, where the underlying transport API has the notion of a connection such as theJMS or JDBC API, there should be a one-to-one mapping between the Mule connector and the underlyingconnection.

org.mule.api.transport.MessageReceiver

The Message Receiver is used to receive incoming data from the underlying transport and package itas an event. The Message Receiver is essentially the server implementation of the transport (where theMessage Dispatcher is a client implementation). For example, the HTTP Message Receiver is an HTTPserver implementation that accepts HTTP requests. An implementation of this class is needed if thetransport supports inbound communication.

org.mule.api.transport.MessageDispatcher

The Message Dispatcher is used to send messages, which is akin to making client calls with theunderlying technology. For example, the CXF Message Dispatcher will make a web service call. Animplementation of this class is needed if the transport supports outbound communication. The MessageDispatcher must call MuleEvent.transformMessage() to invoke any necessary transformers beforedispatching it.

org.mule.api.transport.MessageRequester

The Message Requester is used to request messages from a message channel or resource rather thansubscribing to inbound events or polling a resource for messages. This is often used programatically butis not used for inbound endpoints configured on services. An implementation of this class is needed if thetransport supports the requesting of messages from a message channel.

Page 368: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 368

org.mule.api.transport.MessageDispatcherFactory

This is a factory class used to create MessageDispatcher instances. An implementation of this class isneeded if the transport supports outbound communication.

org.mule.api.transport.MessageAdapter

The message adapter is used to provide a consistent way of reading messages in Mule. The messageadapter provides methods for reading the payload of the message and reading message properties. Theseproperties may be message headers, custom properties, or other meta information about the message.

Implementation

Mule provides abstract implementations for all of the above interfaces. These implementations handle allthe Mule specifics, leaving a few abstract methods where custom transport code should be implemented.Therefore, writing a custom transport is as easy as writing/embedding client and or server code specificto the underlying technology. The following sections describes the implementations available to you.

For a quick start, use the Maven Transport Archetype.

Connectors

The org.mule.transport.AbstractConnector implements all the default functionality required for Muleconnectors, such as threading configuration and receiver/dispatcher management. For details about thestandard connector properties, see Configuring a Transport.

You can set further properties on the connector that act as defaults. For example, you can set endpointproperties that are used by default unless you override them when configuring a specific endpoint.

Sometimes the connector is responsible for managing a connection resource of the transport where theunderlying technology has the notion of a connection, such as in JMS or JDBC. These types of connectorswill have a one-to-one mapping between a Mule connector and the underlying connection. Therefore, ifyou want to have two or more physical JMS connections in a single Mule instance, a new connector shouldbe created for each connection.

For other transports, there will be only one connector of a particular protocol in a Mule instance thatmanages all endpoint connections. One such example would be socket-based transports such as TCPwhere each receiver manages its own ServerSocket and the connector manages multiple receivers.

Methods to Implement

Method Name Description Required

doInitialise() Is called once all bean propertieshave been set on the connectorand can be used to validate andinitialize the connector's state.

No

doStart() If there is a single serverinstance or connectionassociated with the connector(such as AxisServer or a JMS orJDBC Connection), this methodshould put the resource in astarted state.

No

doConnect() Makes a connection to theunderlying resource if this isnot handled at the receiver/dispatcher level.

No

Page 369: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 369

doDisconnect() Close any connection made indoConnect().

No

doStop() Should put any associatedresources into a stopped state.Mule automatically calls thestop() method.

No

doDispose() Should clean up any openresources associated with theconnector.

No

Message Receivers

Message Receivers will behave a bit differently for each transport, but Mule provides some standardimplementations that can be used for polling resources and managing transactions for the resource.Usually there are two types of Message Receivers: Polling and Listener-based.

• A Polling Receiver polls a resource such as the file system, database, and streams.• A Listener-based receiver registers itself as a listener to a transport. Examples would be JMS

(javax.message.MessageListener) and Pop3 (javax.mail.MessageCountListener). These base typesmay be transacted.

The abstract implementations provided by Mule are described below.

Abstract Message Receiver

The AbstractMessageReceiver provides methods for routing events. When extending this class, you shouldset up the necessary code to register the object as a listener to the transport. This will usually be a caseof implementing a listener interface and registering itself.

Methods to Implement

Method name Description Required

doConnect() Should make a connection tothe underlying transport, suchas to connect to a socket orregister a SOAP service. Whenthere is no connection to bemade, this method should beused to check that resourcesare available. For example, theFileMessageReceiver checks thatthe directories it will be usingare available and readable.The MessageReceiver shouldremain in a 'stopped' stateeven after the doConnect()method is called. This meansthat a connection has beenmade but no events will bereceived until the start() methodis called. Calling start() onthe MessageReceiver will calldoConnect() if the receiverhasn't connected.

Yes

doDisconnect() Disconnects and tidies upany resources allocated using

Yes

Page 370: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 370

the doConnect() method.This method should returnthe MessageReceiver in adisconnected state so that it canbe connected again using thedoConnect() method.

doStart() Should perform any actionsnecessary to enable the receiverto start receiving events. This isdifferent from the doConnect()method, which actually makes aconnection to the transport butleaves the MessageReceiver in astopped state. For polling-basedMessageReceivers, the doStart()method simply starts the pollingthread. For the Axis messagereceiver, the start method onthe SOAPService is called.The action performed dependson the transport being used.Typically, a custom transportdoesn't need to override thismethod.

No

doStop() Should perform any actionsnecessary to stop the receiverfrom receiving events.

No

doDispose() Is called when the connector isbeing disposed and should cleanup any resources. The doStop()and doDisconnect() methodswill be called implicitly when thismethod is called.

No

Polling Message Receiver

Some transports poll a resource periodically waiting for new data to arrive. The polling message receiver,which is based on AbstractPollingMessageReceiver , implements the code necessary to set up and destroya listening thread and provides a single method poll() that is invoked repeatedly at a given frequency.Setting up and destroying the listening thread should occur in the doStart() and doStop() methodsrespectively.

Methods to Implement

Method name Description Required

poll() Is executed repeatedly at aconfigured frequency. Thismethod should execute the logicnecessary to read the data andreturn it. The data returnedwill be the payload of the newmessage. Returning null willcause no event to be fired.

Yes

Page 371: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 371

Transacted Polling Message Receiver

The TransactedPollingMessageReceiver can be used by transaction-enabled transports to manage pollingand transactions for incoming requests. This receiver uses a transaction template to execute requests intransactions, and the transactions themselves are created according to the endpoint configuration for thereceiver. Derived implementations of this class must be thread safe, as several threads can be started atonce for an improved throughput.

Methods to Implement

You implement the following methods for the transacted polling message receiver in addition to those inthe standard Message Receiver:

Method name Description Required

getMessages() Returns a list of objects thatrepresent individual messagepayloads. The payload can beany type of object and will bysent to Mule services wrapped ina MuleEvent object.

Yes

processMessage(Object) is called for each objectin the list returned fromgetMessages(). Each objectprocessed is managed in its owntransaction.

Yes

Thread Management

It's common for receivers to spawn a thread per request. All receiver threads are allocated using theWorkManager on the receiver. The WorkManager is responsible for executing units of work in a thread. Ithas a thread pool that allows threads to be reused and ensures that only a prescribed number of threadswill be spawned.

The WorkManager is an implementation of org.mule.api.context.WorkManager , which is really just awrapper of javax.resource.spi.work.WorkManager with some extra lifecycle methods. There is agetWorkManager() method on the AbstractMessageReceiver that you can use to get a reference to theWorkManager for the receiver. Work items (such as the code to execute in a separate thread) mustimplement javax.resource.spi.work.Work. This interface extends java.lang.Runnable and thus has arun() method that will be invoked by the WorkManager.

When scheduling work with the WorkManager, you should call scheduleWork(...) on the WorkManagerrather than startWork(...).

Message Dispatchers

Whereas a message receiver is equivalent to a server for the transport in that it serves client requests,a message dispatcher is the client implementation of the transport. Message dispatchers are responsiblefor making client requests over the transport, such as writing to a socket or invoking a web service. TheAbstractMessageDispatcher provides a good base implementation, leaving three methods for the customMessageDispatcher to implement.

Methods to Implement

Method Name Description Required

Page 372: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 372

doSend(MuleEvent) Sends the message payloadover the transport. If there isa response from the transport,it should be returned from thismethod. The sendEvent methodis called when the endpoint isrunning synchronously, and anyresponse returned will ultimatelybe passed back to the caller.This method is executed in thesame thread as the requestthread.

Yes

doDispatch(MuleEvent) Invoked when the endpointis asynchronous and shouldinvoke the transport but notreturn any result. If a resultis returned, it should beignored, and if they underlyingtransport does have a notion ofasynchronous processing, thatshould be invoked. This methodis executed in a different threadfrom the request thread.

Yes

doConnect() Makes a connection to theunderlying transport, suchas connecting to a socket orregistering a SOAP service.When there is no connection tobe made, this method shouldbe used to check that resourcesare available. For example,the FileMessageDispatcherchecks that the directoriesit will be using areavailable and readable. TheMessageDispatcher shouldremain in a 'stopped' state evenafter the doConnect() method iscalled.

Yes

doDisconnect() Disconnects and tidies up anyresources that were allocatedby the doConnect() method.This method should return theMessageDispatcher into adisconnected state so that it canbe connected again using thedoConnect() method

Yes

doDispose() Called when the Dispatcher isbeing disposed and should cleanup any open resources.

No

Message Requesters

As with message receivers and dispatchers the implementation of a message requester for a transport,if it even applies, will vary greatly. The abstract AbstractMessageRequester provides a base from whichto extend and implement your own Message Requester and implemented methods for routing events.Although requesters can implement doConnect} and {{doDisconnect methods given the nature of arequester this can also be done as part of the doRequest implementation, it really depending on the

Page 373: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 373

underlying transport and if you need to maintain a connection open all the time or not to be able to makearbitrary requests.

Method Name Description Required

doRequest(long) Used to make arbitrary requeststo a transport resource. If thetimeout is 0, the method shouldblock until a message on theendpoint is received.

doConnect() Should make a connection to theunderlying transport if required,such as to connect to a socket..

No

doDisconnect() Disconnects and tidies upany resources allocated usingthe doConnect() method.This method should returnthe MessageReceiver in adisconnected state so that it canbe connected again using thedoConnect() method.

No

doInitialise() Called when the Requesteris being initialized after allproperties have been set. Anyrequired initialization can bedone here.

No

doStart() Called when the Requester isstarted. Any transport specificimplementation that is requiredwhen the requestor is startedshould be implemented here.

No

doStop() Called when the Requester isstopped. Any transport specificimplementation that is requiredwhen the requestor is stoppedshould be implemented here.

No

doDispose() Called when the Requester isbeing disposed and should cleanup any open resources.

No

Threads and Dispatcher Caching

Custom transports do not need to worry about dispatcher threading. Unless threading is turned off,the Dispatcher methods listed above will be executed in their own thread. This is managed by theAbstractMessageDispatcher.

When a request is made for a dispatcher, it is looked up from a dispatcher cache on theAbstractConnector. The cache is keyed by the endpoint being dispatched to. If a Dispatcher is notfound, one is created using the MessageDispatcherFactory and then stored in the cache for later.

Message Adapters

Message adapters are usually simple objects that provide a uniform way of accessing a message payloadand associated metadata from a format used by the underlying transport. Almost all messaging protocolshave the notion of message payload and header properties, which means that a message adapter justneeds to allow access to the header properties using standard Map notation. For example:

Page 374: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 374

//JMS message IDString id = (String)message.getProperty("JMSMssageID");

//HTTP content lengthint contentLength = message.getIntProperty("Content-Length");

Note that the property names use the same name that is used by the underlying transport; Content-Length is a standard HTTP header name, and JMSMessageID is the equivalent bean property name on thejavax.jms.Message interface.

A message adapter should extend org.mule.transport.AbstractMessageAdapter , which implements muchof the mundane methods needed by the org.mule.api.transport.MessageAdapter interface.

Methods to Implement

Method Name Description Required

getPayload() Returns the message payload 'asis'.

Yes

getUniqueId() This ID is used by variousrouters when correlatingmessages. The superclasssupplies a unique value bydefault, but this method canbe overridden to provide an IDrecognized by the underlyingtransport.

No

Service Descriptors

Each transport has a service descriptor that describes what classes are used to construct the transport.For complete information, see Transport Service Descriptors.

Coding Standards

Following are coding standards to use when creating transports.

Package Structure

All Mule transports have a similar package structure. They follow the convention of:

org.mule.transport.<protocol>

Where protocol is the protocol identifier of the transport such as 'tcp' or 'soap'. Any transformers andfilters for the transport are stored in either a 'transformers' or 'filters' package under the main package.Note that if a transport has more than one implementation for a given protocol, such as the Axis and CXFimplementations of the SOAP protocol, the package name should be the protocol, such as soap instead ofaxis or cxf.

Page 375: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 375

Internationalization

Any exceptions messages used in your transport implementation should be stored in a resource bundleso that they can be internationalized . The message bundle is a standard Java properties file and must belocated at:

META-INF/services/org/mule/i18n/<protocol>-messages.properties

Page 376: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 376

Transport Archetype

This page last changed on Feb 24, 2009 by jackie.wheeler.

Transport Archetype

[ Configuring Maven ] [ Using the Archetype ] [ The Questions Explained ] [ Example Console Output ] [Command Line Options ]

Mule provides Maven archetypes that you can use as code templates for your Mule projects. Thesetemplates include a set of implementation notes and "todo" pointers that help you get started quickly.The Mule transport archetype will help you generate a tailored boilerplate transport project in seconds.For more information on Maven, see Using Maven.

If you want to update an existing transport instead of creating a new one, such as adding new schemanamespaces and registry bootstrapping to the transport, use the Module Archetype instead.

Follow the instructions below to create template files for a new transport, including all the necessary Javaboilerplate and detailed implementation instructions in comments.

Configuring Maven

Add the following to the file settings.xml (usually in your Maven conf or $HOME/.m2 directory) so thatMaven will allow you to execute Mule plug-ins.

<settings> <pluginGroups> <pluginGroup>org.mule.tools</pluginGroup> </pluginGroups> ...</settings>

Using the Archetype

First, open a command shell and change to the directory where you want to create your project.

> cd yourDir

Next, you execute the archetype and generate the code. If this is your first time running this command,Maven will download the archetype for you.

> mvn mule-transport-archetype:create -DtransportId=xxx -DmuleVersion=2.2.0

As of Mule 2.2, the parameter -DtransportId can be replaced with -DartifactId, which isin line with the other Mule archetypes.

At minimum, you pass in two system parameters:

• artifactId: The short name for the project (such as 'tcp'). This must be a single word in lowercase with no spaces, periods, hyphens, etc. For transports this is usually the short protocol name ofthe underlying transport being connected.

• muleVersion: The version of the Mule project archetype you want to use. This will also be thedefault Mule version used for the generated artifact.

The plug-in will ask various questions (described below) and then generate the files. You can also usethis plug-in without user prompts by entering all the arguments at the command line. For a full list ofarguments that can be passed in, see the Command Line Options.

Page 377: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 377

After you have answered all the questions, the archetype creates a directory using the transport nameyou specified. The directory includes a POM file for building with Maven, a Mule configuration file (src\main\resources\mule-config.xml) that includes the namespaces for the transports and modules youspecified and has placeholder elements for creating your first service, and a package.html file under src\main\java using the package path you specified. Lastly, it creates some template files under src\testto help you get started creating a unit test for the transport. A new MULE-README.txt file will be createdin the root of your project explaining what files were created.

The Questions Explained

The plug-in prompts you to answer several questions about the transport you are writing. These mayvary according to the options you select. An example of the output is shown below.

Provide a description of what the transport does:

You should provide an accurate description of the transport with any high-level details of what you can orcannot do with it. This text will be used where a description of the transport is required.

Which version of Mule is this transport targeted at?

The version of Mule you want to use for your transport. By default this will default to the version passedin on the command line.

Will this project be hosted on MuleForge?

If the transport is going to be hosted on MuleForge, additional information will be added to your projectfor linking to its issue tracker, web site, build server and deployment information.

Will this transport have a custom schema for configuring the transport in Xml?

All new transports targeted for Mule 2.x should define an XML schema that defines how the transportis configured. If you do not use this option, users will have to use generic configuration to use yourtransport.

Can the transport receive inbound requests?

Can this transport receive inbound events? For example, the File transport allows you to listen for fileswritten to a directory. JMS allows you to listen for events being written to a topic or queue.

Does the Message Receiver need to poll the underlying resource?

To receive a message, some transports must do polling. For example, the File transport mustpoll a directory to know something has been written there, whereas JMS provides a callback(MessageListener) to deliver the message. This question is asked only if the transport can receiveinbound requests.

If this transport will have a default inbound transformer, enter the name of the transformer?

If the protocol of the application being connected to has its own message type, you can define adefault inbound transformer that will be invoked by default when defining endpoints that use thistransport. You enter the name of the transformer class (without package name) to generate, such asJmsMessageToObject.

Can the transport dispatch outbound requests?

Asks whether messages can be written to this transport. With the File transport, you can write file data toa directory, and with JMS you can write to a queue or topic.

Page 378: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 378

If this transport will have a default outbound transformer, enter the name of thetransformer?

If the protocol of the application being connected to has its own message type, you can define a defaultoutbound transformer that will be invoked by default when defining outbound endpoints that use thistransport. You enter the name of the transformer class (without package name) to generate, such asObjectToJmsMessage.

Does the transport need a custom MessageAdapter?

This is usually only required if the underlying transport has an API that has amessage object i.e. JMSMessage or HttpServletRequest.

Can the transport request individual messages from the underlying resource?

If the transport can request messages from a message channel or resource rather than subscribing toinbound events or polling a resource, answer yes to this question. This will generate a MessageRequesterclass.

Does this transport support transactions?

If the underlying resource for this transport is transactional, you can have Mule generate a transactionwrapper that will allow users to enable transactions on endpoints defined using this transport.

Does this transport use a non-JTA transaction manager?

Not all technologies (such as JavaSpaces) support the standard JTA transaction manager. Mule can stillwork with different non-JTA transaction managers, and this archetype can generate the necessary stubsfor you.

What type of endpoints does this transport use?

Mule supports a number of well-defined endpoints

• Resource endpoints (e.g., jms://my.queue)• URL endpoints (e.g., http://localhost:1234/context/foo?param=1)• Socket endpoints (e.g., tcp://localhost:1234)• Custom

The Custom option allows you to deviate from the existing endpoint styles and parse your own.

Which Mule transports do you want to include in this project?

If you are extending one or more existing transports, specify them here in a comma-separated list.

Which Mule modules do you want to include in this project?

By default, the Mule client module is included to enable easier testing. If you want to include othermodules, specify them here in a comma-separated list.

Example Console Output

********************************************************************************

Provide a description of what the transport does: [default: ]********************************************************************************[INFO] muleVersion: ********************************************************************************

Page 379: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 379

Which version of Mule is this transport targeted at? [default: 2.2.0]********************************************************************************[INFO] forgeProject: ********************************************************************************

Will this project be hosted on MuleForge? [y] or [n] [default: y]********************************************************************************[INFO] hasCustomSchema: ********************************************************************************

Will this transport have a custom schema for configuring the transport in Xml? [y] or [n] [default: y]********************************************************************************[INFO] hasReceiver: ********************************************************************************

Can the transport receive inbound requests? [y] or [n] [default: y]********************************************************************************[INFO] isPollingReceiver: ********************************************************************************

Does the Message Receiver need to poll the underlying resource? [y] or [n] [default: n]********************************************************************************[INFO] inboundTransformer: ********************************************************************************

If this transport will have a default inbound transformer, enter the name of thetransformer? (i.e. JmsMessageToObject) [default: n]********************************************************************************[INFO] hasDispatcher: ********************************************************************************

Can the transport dispatch outbound requests? [y] or [n] [default: y]********************************************************************************[INFO] outboundTransformer: ********************************************************************************

If this transport will have a default outbound transformer, enter the name of thetransformer? (i.e. ObjectToJmsMessage) [default: n]********************************************************************************[INFO] hasCustomMessageAdapter: ********************************************************************************

Does the transport need a custom MessageAdapter? [y] or [n](This is usually only required if the underlying transport has an API that has a message object i.e. JMSMessage or HttpServletRequest) [default: n]********************************************************************************[INFO] hasRequester: ********************************************************************************

Can the transport request incoming messages programmatically? [y] or [n] [default: y]********************************************************************************[INFO] hasTransactions: ********************************************************************************

Does this transport support transactions? [y] or [n]

Page 380: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 380

[default: n]********************************************************************************[INFO] hasCustomTransactions:

********************************************************************************

Does this transport use a non-JTA Transaction manager? [y] or [n](i.e. needs to wrap proprietary transaction management) [default: n]********************************************************************************[INFO] endpointBuilder: ********************************************************************************

What type of endpoints does this transport use? - [r]esource endpoints (i.e. jms://my.queue) - [u]rl endpoints (i.e. http://localhost:1234/context/foo?param=1) - [s]ocket endpoints (i.e. tcp://localhost:1234) - [c]ustom - parse your own [default: r]********************************************************************************[INFO] transports:********************************************************************************

Which Mule transports do you want to include in this project? If you intend extending a transport you should add it here:

(options: axis,cxf,ejb,file,ftp,http,https,imap,imaps,jbpm,jdbc, jetty,jms,multicast,pop3,pop3s,quartz,rmi,servlet,smtp, smtps,servlet,ssl,tls,stdio,tcp,udp,vm,xmpp): [default: vm]

********************************************************************************[INFO] modules:********************************************************************************

Which Mule modules do you want to include in this project? The client is added for testing:

(options: bulders,client,jaas,jbossts,management,ognl,pgp,scripting, spring-extras,sxc,xml): [default: client]

********************************************************************************

Command Line Options

By default, this plug-in runs in interactive mode, but it's possible to run it in silent mode by using thefollowing option:

-Dinteractive=false

The following options can be passed in:

Name Example Default Value

transportId -DtransportId=tcp none

description -Ddescription="some text" none

Page 381: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 381

muleVersion -DmuleVersion=2.2.0 none

hasCustomSchema -DhasCustomSchema=true true

forgeProject -DforgeProject=true true

hasDispatcher -DhasDispatcher=true true

hasRequester -DhasRequester=true true

hasCustomMessageAdapter(Since Mule 2.2)

-DhasCustomMessageAdapter=true

false

hasTransactions -DhasTransactions=false false

version -Dversion=1.0-SNAPSHOT <muleVersion>

inboundTransformer -DinboundTransformer=false false

groupId -DgroupId=org.mule.transport.tcp

org.mule.transport.<transportId>

hasReceiver -DhasReceiver=true true

isPollingReceiver -DisPollingReceiver=false false

outboundTransformer -DoutboundTransformer=false false

endpointBuilder -DendpointBuilder=s r

hasCustomTransactions -DhasCustomTransactions=false false

artifactId -DartifactId=mule-transport-tcp mule-transport-<transportId>

transports -Dtransports=vm,jms vm

modules -Dmodules=client,xml client

Page 382: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 382

Transport Service Descriptors

This page last changed on Dec 18, 2008 by jackie.wheeler.

Transport Service Descriptors

A service descriptor is a file containing properties that describes how the internals of a transport isconfigured, such as which dispatcher factory to use or which endpoint builder to use. The servicedescriptor file must have the same name as the protocol of the transport and must be stored in theMETA-INF directory.

META-INF/services/org/mule/providers/<protocol>.properties

Following are the properties that can be set in a transport service descriptor.

Property Description Required

connector The name of the defaultconnector class to use. Thismust be an implementation oforg.mule.api.transport.Connector.

Yes

dispatcher.factory The name of the dispatcherfactory class to use. Thismust be an implementation oforg.mule.api.transport.MessageDispatcherFactory.

No (if inbound only)

requester.factory The name of the requesterfactory class to use.org.mule.api.transport.MessageRequesterFactory.

No

message.receiver The name of the messagereceiver class to use. Thismust be an implementation oforg.mule.api.transport.MessageReceiver.

No (if inbound only)

transacted.message.receiver The name of the messagereceiver class to use fortransacted messages. Sometransports implement atransacted message receiverseparately, in which case theMessageReceiver class canbe specified here so Muleknows which receiver to usewhen creating endpoints thatare transacted. This mustbe an implementation oforg.mule.api.transport.MessageReceiver

No

xa.transacted.message.receiver If the transport supports XAtransactions, the name ofthe XA transacted messagereceiver implementation to use.

No

Page 383: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 383

Some transports implementan XA transacted messagereceiver separately, in whichcase the MessageReceiverclass can be specified here soMule knows which receiver touse when creating endpointsthat are XA transacted. Thismust be an implementation oforg.mule.api.transport.MessageReceiver.

message.adapter The name of the messageadapter class to use for thisconnector when receivingmessages. This must bean implementation oforg.mule.api.transport.MessageAdapter.

No (if outbound only)

inbound.transformer The default transformer touse on inbound endpointsusing this transport if notransform has been explicitlyset on the endpoint. Theproperty is the class name ofa transformer that implementsorg.mule.api.transformer.Transformer.

No

response.transformer The default transformer to useon inbound endpoints usingthis transport if no transformerhas been explicitly set forthe response message flowin Request/Response stylemessaging. The propertyis the class name of atransformer that implementsorg.mule.api.transformer.Transformer.

No

outbound.transformer The default transformer touse on outbound endpointsusing this transport if notransform has been explicitlyset on the endpoint. Theproperty is the class name ofa transformer that implementsorg.mule.api.transformer.Transformer.

No

endpoint.builder The class name of the endpointbuilder used to parse theendpoint and create the URI.Mule provides a standard setof endpoint builders such asResourceNameEndpointURIBuilderused by JMS and VM,SocketEndpointURIBuilder usedby TCP, HTTP, and UDP, andUrlEndpointURIBuilder usedby SOAP. Custom endpointbuilders should extend

Yes

Page 384: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 384

org.mule.endpoint.AbstractEndpointBuilder.

session.handler The name of the sessionhandler class to use forreading and writing sessioninformation to and from thecurrent message. This mustbe an implementation oforg.mule.api.transport.SessionHandler.

No

Page 385: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 385

Deployment Scenarios

This page last changed on Nov 25, 2008 by jackie.wheeler.

Deployment Scenarios

[ Embedding Mule in a Java Application or Webapp ] [ Embedding Mule in an Application Server ] [ UsingSpring ] [ Using Mule NetBoot ]

There are several ways in which you can deploy Mule. The simplest way is from the command prompt,or from a script or IDE. For more information, see Running Mule. Following are additional deploymentscenarios:

Embedding Mule in a Java Application or Webapp

You can start and stop Mule from a Java application or embed it in a Webapp (such as a JSP or servlet).For details, see Embedding Mule in a Java Application or Webapp.

Embedding Mule in an Application Server

You can deploy the Mule JCA Resource Adapter to several J2EE application servers, allowing EJBs to sendand receive Mule events. Following are details on specific application servers:

• Geronimo: The Geronimo application server uses ActiveMQ as its default JMS provider. For details,see ActiveMQ Integration.

• JBoss• WebLogic

Using Spring

Mule fully integrates with Spring, allowing you to take advantage of Spring's many features, includingsupport for JNDI and EJB session beans. You can also use Spring remoting to access Mule from anexternal applications. For details, see Using Mule with Spring.

Using Mule NetBoot

Mule NetBoot allows you to start and configure multiple instances of Mule simultaneously using Galaxy.For complete information, see Using Mule NetBoot.

Page 386: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 386

Deploying Mule to WebLogic

This page last changed on Mar 25, 2009 by jwheeler.

Deploying Mule to WebLogic

[ Creating a WebLogic Domain for Mule ] [ Configuring Logging ] [ Setting Up Web.xml ] [ Deploying Mule] [ Replacing the Mule Configuration File ]

This page describes how to deploy the Mule JCA Resource Adapter to the WebLogic Application Server,allowing EJBs to send and receive Mule events. For details on configuring WebLogic JMS in Mule, seeWebLogic JMS Integration.

These instructions assume you have downloaded and installed WebLogic Application Server version 10.3and that you have downloaded the Mule JCA Resource Adapter. Note that WebLogic 8.x and 9.x are alsosupported, but these instructions are specific to version 10.3, both on BEA Weblogic and Oracle WebLogic.

Note: You can also deploy the Mule JCA Resource Adapter within an EAR, in which case you follow thesame steps but deploy your EAR rather than the RAR. Alternatively, you can deploy Mule embeddedin a web application, in which case you will need to configure logging as described below, but you willnot need to switch configuration files in the RAR, and you won't use the JCA Resource Adapter, as yourweb.xml file will define the configuration file to use instead.

Creating a WebLogic Domain for Mule

The first step is to create a WebLogic domain for Mule using the BEA WebLogic Configuration Wizard.

1. Launch the Configuration Wizard. For example, on Windows choose Start > All Programs > BEAProducts > Tools > Configuration Wizard.

2. In the Welcome screen, select the option to create a new domain and click Next.3. In the Select Domain Source screen, select the option to generate a domain for WebLogic Server

and click Next.4. In the Configure Administrator Username and Password screen, enter the user name and password

you want to use, and then click Next.5. In the Configure Server Start Mode and JDK screen, select Development Mode, select the Sun SDK

1.5 instead of JRockit, and then click Next.6. In the Customize Environment and Services Settings screen, leave No selected and click Next.7. In the Create WebLogic Domain screen, enter Mule2 for the domain name, leave the location set to

the default user projects domains directory, and then click Create. Note that you can use whateverdomain name you like, but the rest of this page assumes the name Mule2.

8. When the domain has been created, click Done.

Configuring Logging

Mule uses Commons logging and Commons lang. Because WebLogic does not include the Commonslogging JAR, and because Mule requires a newer version of Commons lang, you must copy these filesand modify your classpath so they are used correctly by Mule and WebLogic. For more informationon using Commons logging and WebLogic, see http://e-docs.bea.com/wls/docs103/logging/config_logs.html#wp1015132.

1. Download the Commons logging JAR as a TAR or ZIP file here.2. Unzip the file and copy commons-logging-api.jar to any location on the WebLogic server

classpath, such as APP-INF/LIB or WEB-INF/LIB, or in Mule2/lib under the <WLHome>/user_projects/domains directory.

3. Copy wlcommons-logging.jar from <WLHome>/server/lib to the same location where you copiedcommons-logging.jar.

4. Copy commons-lang.osgi-2.4.jar from inside the Mule JCA Resource Adapter RAR file to theMule2/lib directory under the <WLHome/user_projects/domains directory. You can use anydecompression program that supports RAR files to extract the JAR from it, or unpackage the RARusing the jar xvf command, such as: jar xvf mule-enterprise-jca-2.2.1.rar

5. In the Mule2EE/bin directory, modify the startWebLogic file so that the

Page 387: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 387

commons-lang.osgi-2.4.jar in your Mule2/lib directory is loaded first. For example, on Windowsyou would modify startWebLogic.cmd and change this line:

set CLASSPATH=%CLASSPATH%;%MEDREC_WEBLOGIC_CLASSPATH%...

to this (type it all on one line):

set CLASSPATH=%WL_HOME%/user_projects/domains/Mule2/lib/commons-lang.osgi-2.4.jar; %CLASSPATH%;%MEDREC_WEBLOGIC_CLASSPATH%...

6. Configure a system property in WebLogic's startup script by adding the following line after theclasspath modification line:

set JAVA_OPTIONS=%JAVA_OPTIONS% -Dorg.apache.commons.logging.LogFactory=weblogic.logging.commons.LogFactoryImpl

Setting Up Web.xml

You must set up your WebLogic web.xml file to enable WebLogic to work with Mule. Open your web.xmlfile and modify it with the following information:

• The class prefix and name of your Mule configuration file• The listener class• The Mule servlet configuration, including the order in which the servlet should be loaded. Typically,

set this to a high number so that it is loaded last.

For example, the beginning of the file should look similar to this:

<web-app id="WebApp_ID"> <!--Mule configuration (Mule format)--> <context-param> <param-name>org.mule.config</param-name> <param-value>mule-config.xml</param-value> </context-param>

<listener> <listener-class> org.mule.config.builders.MuleXmlBuilderContextListener </listener-class> </listener>

<servlet> <servlet-name>muleServlet</servlet-name> <servlet-class>org.mule.transport.servlet.MuleReceiverServlet</servlet-class> <load-on-startup>100</load-on-startup> </servlet> <!--Mule configuration ends-->...</web-app>

Note: Make sure that the ports you specify in your Mule configuration file are open. You can use netstat-a to verify this.

Deploying Mule

There are many ways to deploy applications to the WebLogic server. These instructions demonstrate thetwo most common approaches: through auto-deployment, which provides a fast method for deployingfor testing and evaluation, and through the Administration console, which provides more control over theconfiguration. Note that this section also applies when deploying an EAR or WAR that embeds Mule toWebLogic, in which case you deploy the EAR or WAR instead of the RAR file.

Page 388: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 388

To Auto-deploy Mule:

1. Copy mule-enterprise-jca-2.2.1.rar (for Mule Enterprise users) or mule-jca-2.2.1.rar (forMule Community users) into the <WLHome>/user_projects/domains/Mule2/autodeploy directory.

2. Restart your domain server instance in development mode. During the starting process, the newRAR file will be auto-discovered and deployed by the domain server.

To Deploy Mule Using the Administration Console:

1. Start the WebLogic server. For example, on Windows choose Start > BEA Products > WebLogicServer.

2. Start the Admin Server for the Mule2 domain. For example, on Windows you would choose Start >BEA Products > User Projects > Mule2 > Start Admin Server for WebLogic Server Domain.

3. When prompted, log in to the console using the user name and password you specified whencreating the domain. If you close the console and need to restart it later, you can go to the URLhttp://localhost:7001/console/console.portal.

4. In the Domain Structure on the left, click Deployments, and then click Lock & Edit.5. Click Install, and then navigate to the location where you downloaded the Mule RAR file.6. Select the RAR file and click Next.7. Specify that you want to go to the deployment's configuration screen, and then click Finish.8. In the Change Center on the left, click Activate Change.

Mule is now deployed to WebLogic via the Mule JCA Resource Adapter. You must now replace the defaultconfiguration file in the RAR file with the configuration file for your Mule application.

Replacing the Mule Configuration File

Mule includes a placeholder configuration file called mule-config.xml in the RAR file under mule-module-jca-core-2.2.0.jar. If you simply want to modify this file, you can do the following:

1. Unpackage the RAR and the JAR file.2. Modify the configuration file.3. Repackage the JAR and RAR with the updated file and copy the RAR into the <WLHome>/

user_projects/domains/Mule2/autodeploy directory.4. Run the startWebLogic command.

If you want to replace this file, do the following:

1. Unpackage the RAR file and copy your configuration file to the top level where all the JAR files arelocated.

2. Open the META-INF folder, and then open weblogic-ra.xml for editing.3. Immediately after the <enable-global-access-to-classes>true</enable-global-access-to-

classes> entry and right before outbound-resource-adapter, add the following lines, where echo-axis-config.xml is the name of your configuration file:

<properties> <property> <name>Configurations</name> <value>echo-axis-config.xml</value> </property> </properties>

4. Repackage the RAR file and deploy it by copying it to the autodeploy directory and runningstartWebLogic.

Page 389: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 389

Embedding Mule in a Java Application or Webapp

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

Embedding Mule in a Java Application or Webapp

This page describes how to start and stop Mule from a Java application or to embed it in a Webapp (suchas a JSP or servlet), and how to interact with Mule from your code in both scenarios.

Starting Mule from a Java Application

To start Mule from any Java application, you can call one of its configuration builders. To use Mule XMLconfiguration:

DefaultMuleContextFactory muleContextFactory = new DefaultMuleContextFactory();SpringXmlConfigurationBuilder configBuilder = new SpringXmlConfigurationBuilder("mule-config.xml");muleContext = muleContextFactory.createMuleContext(configBuilder);

Make sure you store a reference to the MuleContext, as you will need it to stop Mule.

If you have multiple configuration files, you can provide a comma-separated list or an array ofconfiguration files:

SpringXmlConfigurationBuilder configBuilder = new SpringXmlConfigurationBuilder(new String[] { "mule-config.xml", "another-config.xml" });

You then call the start method to start the server:

muleContext.start();

Stopping Mule from a Java Application

To stop Mule, you stop its context like this:

muleContext.stop();muleContext.dispose();

Embedding Mule in a Webapp

To embed Mule inside a webapp, you provide one or more configuration file locations as context paramsand include a context listener to initialize the Mule Server. If you are using Mule XML configuration, usethe following -

<context-param> <param-name>org.mule.config</param-name> <param-value>mule-config-main.xml,mule-components.xml</param-value></context-param>

<listener> <listener-class>org.mule.config.builders.MuleXmlBuilderContextListener</listener-class>

Page 390: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 390

</listener>

The configuration parameter can be a classpath location or file location. You can also specify multipleconfiguration files on the classpath or on the file system.

Interacting with Mule from Your Code

To interact with the Mule server from your application, JSP, or servlet, you can use the Mule Client.

//create a clientMuleClient client = new MuleClient();

//send a jms message asynchronouslyclient.dispatch("jms://my.queue", "some data", null);

//or to receive a pop3 message via a configured mailboxMuleMessage message = client.receive("pop3://myInboxProvider", 3000);

//or synchonous send a inter-vm messageMuleMessage message2 = client.send("vm://my.object", "Some more data", null);

Page 391: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 391

JBoss Integration

This page last changed on Mar 25, 2009 by jwheeler.

Deploying Mule to JBoss

The recommended approach for integrating with enterprise application deployed in JBoss is to deployMule as a standalone application and use the Mule EJB Transport or components configured usingspring EJB proxies (http://static.springframework.org/spring/docs/2.5.x/reference/ejb.html using tointegrate with your EJB's in JBoss. If you need to deploy Mule in the JBoss application server for otherreasons (e.g., to use JBoss clustering), use the instructions on this page. Note that if you are using JBossclustering, you cannot use stateful routers.

There are three main approaches you can take to deploying Mule to JBoss:

1. Simple WAR deployment: in this approach, you simply embed Mule in your application and build theWAR. Your custom implementation classes are part of the WAR.

2. EAR application: you can embed the WAR inside the EAR file and include additional files such asEJBs.

3. JCA deployment: you can use the Mule JCA Resource Adapter. The Mule JCA adaptor allows you touse "JCA Message Inflow" to Message Driven Beans (MDB's) and use the Mule "ManagedConnection"for tighter integration when sending message from your Jee application via Mule.

Classloader Isolation

When JBoss comes to classloading, unless classloader isolation is specified, JBoss will first try to useits own classes for deployment and only when these are not found will it look for them in the librariesof the deployment file. Since the versions of the libraries used to load Mule are not the same as theones used by JBoss, various errors such as ClassCastExceptions can appear, so classloading isolation isimportant. Therefore, for best results, you should use classloader isolation in your JBoss configuration.For more information, see http://wiki.jboss.org/wiki/ClassLoadingConfiguration. If you're using the JCAadapter, and you have other applications running on JBoss, you should use classloader isolation. However,classloader isolation is not supported for JCA deployment on JBoss. Therefore, you must wrap your JCAadapter in an EAR and configure classloader isolation for the EAR.

Building an EAR File for the Deployment of the Mule JCAResource Adapter on JBoss 4.2.x

Although you can deploy the Mule JCA Resource Adapter directly, the best way to deploy Mule on JBoss isto place the resource adapter inside an EAR file. The advantages of this approach over using the Mule JCAResource Adapter directly are the following:

• JBoss allows EAR, WAR, and SAR files to have classloader isolation. This feature is not yet availablefor the RAR file.

• The Mule JCA Resource Adapter contained in the EAR file is specific for JBoss deployment.• In order to avoid deployment issues with JBoss the mule-jboss-ds.xml file has to be moved from

the mule-module-jca-jboss-<muleVersion>.jar file up to the EAR level.

Adaptation of the RAR File for Use with the EAR File

In mule-jca-jboss-x.rar (where x is the Mule version number), you must remove mule-jboss-ds.xmlfrom mule-module-jca-jboss-2.x.jar. Note that if you are going to repackage mule-jca-jboss-x.rar,repackage it in a simple zip file format instead of other compression formats.

Mule EAR File Structure

The file structure of the EAR file should have the following format:

Page 392: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 392

META-INF | - application.xml | - jboss-app.xml | - MANIFEST.MFmule-jca-jboss-x.rarmule-jboss-ds.xml

Mule EAR Configuration Files

Following are the configuration files for the XML files in the above file structure:

mule-jboss-ds.xml

<connection-factories> <tx-connection-factory> <jndi-name>mule/ConnectionFactory</jndi-name> <local-transaction /> <track-connection-by-tx /> <rar-name>my-ear.ear#mule-jca-jboss-2.x.rar</rar-name> <connection-definition>org.mule.module.jca.MuleConnectionFactory</connection-definition> </tx-connection-factory></connection-factories>

The mule-jboss-ds.xml file is an adaptation of the one you removed from mule-module-jca-jboss-2.x.jar. Note that because the RAR file is found inside the EAR, the name inside the <rar-name>tag should be the EAR file name and the RAR file name separated by the # symbol. This will be your datasource.

application.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE application PUBLIC "-//Sun Microsystems, Inc.//DTD J2EE Application 1.3//EN" "http://java.sun.com/dtd/application_1_3.dtd"><application> <display-name>mule-ear</display-name> <description>EAR packaging for Mule Resource Adapter</description> <module> <connector>mule-jca-jboss-2.x.rar</connector> </module></application>

This file is required for telling the EAR file to use mule-jca-jboss-2.x.rar as a connector, allowing it tobe deployed as a resource adapter.

jboss-app.xml

The following configuration file creates a loader-repository that loads the classes during the classloadingoperation. The java2ParentDelegation property must be set to false to enable classloader isolation.The configuration specifies mule-jboss-ds.xml as a service to be loaded.

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE jboss-app PUBLIC "-//JBoss//DTD J2EE Application 1.4//EN" "http://www.jboss.org/j2ee/dtd/jboss-app_4_0.dtd">

Page 393: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 393

<jboss-app> <loader-repository>org.mule:loader=mule-ear-2.2.1.ear <loader-repository-config> java2ParentDelegaton=false </loader-repository-config> </loader-repository> <module> <service>mule-jboss-ds.xml</service> </module></jboss-app>

Deploying Your Application

The resource adapter comes configured with a dummy mule-config.xml file, which you will replace withyour own configuration file. You can physically replace the mule-config.xml file in the Mule JCA ResourceAdapter (mule-module-jca-core-2.x.jar) with your own, but if your POJOs are bundled in a JAR, youcan take the following more elegant approach:

1. Put the resource files (xslt, properties, etc.) in your JAR file (these should be picked upautomatically when Mule starts)

2. Create a folder in the root of the mule-jca-jboss-2.x.rar file and put your Mule configuration inthere. For the time being, let's call this folder "conf".

3. Edit the ra.xml file found in the mule-jca-jboss-2.x.rar META-INF folder and reference yourconfiguration file name as seen below.

Alternatively you can put your jar files with classes/resources that will be used by mule in your EAR, butin order to do this you will need to add a "Class-Path" entry in the rar's MANIFEST.MF referencing therequired libraries.

<config-property-name>Configurations</config-property-name><config-property-type>java.lang.String</config-property-type><config-property-value>conf/my-config1.xml</config-property-value>

The <config-property-value> should contain a list of configuration files separated by a comma. The"conf/" is the path name telling the loader to look at the conf folder found in the root of the RAR file. Ifonly the name of the configuration file is given, the loader will only look for the configuration file insidethe mule-module-jca-core-2.x.jar.

JBoss MQ Configuration

For information on configuring a JBoss JMS connector, see JBoss Jms Integration.

Scenarios your User Application with Mule in JBoss

For this scenario, the deployment is very simple: you simply add your own JAR and WAR archives to youEAR file. Because everything will be deployed in the same EAR, all the classes required by both the userapplication and Mule share the same classloader. However sometimes other classes may be required thatare not deployed within your EAR..

Resolving Cross-dependencies

The situation becomes more complex when you want to deploy Mule-dependent code in a separate EARfile (for example, you have a custom transformer that extends Mule's AbstractTransformer class). Theuser 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 inthe user EAR. To solve these cross-dependencies, you can create a shared library (in another EAR file,perhaps) and specify the library in the <loader-repository> element of the jboss-app.xml file in

Page 394: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 394

both the Mule EAR and the user EAR. Mule Enterprise Edition users can see an example of this in theKnowledge Base article titled "Embedding in JBoss: How to Share Classes Between Your Mule EE EAR andAnother Application".

Page 395: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 395

Mule as MBean

This page last changed on Nov 25, 2008 by jackie.wheeler.

Mule as MBean

[ Creating a Simple MBean ] [ Creating JBoss Service Descriptor ] [ Deploying MBean to JBoss ] [ Copythe Dependencies ] [ References ]

An MBean is a named managed object representing a resource in an JMX environment. You can easilydeploy an MBean with Mule by taking the following steps:

1. Create an MBean2. Create service descriptor3. Deploy MBean (as .sar) to application server4. Copy dependencies to the service's classpath

This page describes these steps using the JBoss application server.

Creating a Simple MBean

To create an MBean, you need an interface and an implementation:

package foo.mbean;

public interface FooServiceMBean { public String getBar(); public void start(); public void stop();}

package foo.mbean;

import org.jboss.system.ServiceMBeanSupport;import org.mule.config.spring.SpringXmlConfigurationBuilder;import org.mule.api.MuleContext;import org.mule.api.context.notification.ServerNotification;

public class FooService extends ServiceMBeanSupport implements FooServiceMBean{ public String getBar() { return "bar"; }

public void start() { this.getLog().info("MBean being started"); try{ MuleContext context = new DefaultMuleContextFactory().createMuleContext(new SpringXmlConfigurationBuilder("foo-config.xml")); context.registerListener(this); context.start(); } catch(Exception e){ e.printStackTrace(); } this.getLog().info("MBean started"); }

Page 396: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 396

public void stop() { this.getLog().info("MBean being stopped");

try { if (context != null) { context.stop(); context.dispose(); // } this.getLog().info("Done stopping Mule MBean Service!"); } catch (Exception ex) { this.getLog().error("Stopping Mule caused and exception!", ex); } }}

The extension of ServiceMBeanSupport is simply to provide you more control over the API provided byJBoss.

Creating JBoss Service Descriptor

You must create a service descriptor and add it to to META-INF/. Following is a simple example:

<?xml version="1.0" encoding="UTF-8"?><server> <mbean code="foo.FooService" name="foo:service=Foo"> </mbean></server>

Deploying MBean to JBoss

Based on the examples above, your distribution looks like this:

.

./foo

./foo/FooService

./foo/FooServiceMBean

./META-INF

./META-INF/jboss-service.xml

Package the distribution either as a JAR, which you can then rename to a *.sar that you will eventuallyextract, or as a directory called <dirName>.sar.

Copy the Dependencies

Follow the steps below to copy the dependencies and complete the deployment:

1. Copy your <dirName>.sar/ directory to JBOSS_HOME/server/default/deploy/.2. Copy all dependencies of Mule, such as MULE_HOME/lib/*/*.jar to the <dirName>.sar/ directory3. Start JBoss. You will see the MBean appears in its MBean console.

Page 397: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 397

References

• Wikipedia - MBean• The Java Tutorials - Standard MBeans

Page 398: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 398

Developing Service Components

This page last changed on Dec 02, 2008 by jackie.wheeler.

Developing Service Components

[ Entry Point ] [ Default Message Flow Behavior ] [ Customizing the Message Flow Behavior ] [Component Lifecycle ]

When developing service components, you focus on developing code to handle the business logic, notto integrate the service component with Mule. For example, if you are developing a service componentthat adds customer data to an invoice, you focus on writing code that queries the customer databaseand updates the invoice as needed. You do not have to write any special code to handle the messagethat's passed to the service component or to integrate with Mule, as all integration is handled throughconfiguration. You can develop the service component as a POJO, or as a web service using popularcontainers such as Spring, EJB, or Plexus.

Mule does allow you to enable service components to obtain information about or even control the currentmessage instead of just working with the message payload. To enable the service component to workdirectly with the message, you must implement the Callable() interface in the service component (seeEntry Points below).

To get started with developing Mule service components, you can use the Mule IDE. The Mule IDE is anEclipse plug-in that provides an integrated development environment for developing Mule applications.You can also use the standard components provided with Mule, or use them as a starting point forbuilding your own.

Entry Point

The entry point is the method in your component that is invoked by Mule when a message is received. Tospecify the method explicitly on your endpoint, you can use the method argument on the endpoint, suchas:

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

or

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

If you do not specify this argument, Mule uses an entry point resolver to dynamically choose the methodto invoke based on the payload type of the message. When the match is found, the method is cachedwith the parameter types so that introspection is only done once per method for the life of the service. Ifmultiple methods in the component match the payload type, or no method matches, an error is thrown.You can also call a method on the component that has no arguments.

Alternatively, your component can implement the org.mule.api.lifecycle.Callable interface. If yourcomponent implements this interface, it will override any dynamic resolution and call the interfacemethod implementation instead.

For details on configuring entry point resolvers, see Entry Point Resolver Configuration Reference.

Legacy Entry Point Resolver Set

The LegacyEntryPointResolverSet that is used if no other resolver is configured. TheLegacyEntryPointResolverSet provides generic entry point resolution as follows:

1. Use the "method" attribute as described above, if one is specified (seeMethodHeaderPropertyEntryPointResolver ).

2. If the component implements the org.mule.api.lifecycle.Callable lifecycle interface, use theonCall(MuleEventContext) method to receive the message.

3. If the component has a transformer configured for it, the return type for the transformer willbe matched against methods on the component to see if there is a method that accepts the

Page 399: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 399

transformer return type. If so, this method will be used. Note if there is more than one match, anexception will be thrown.

4. The message type (without transformer) will be matched against methods on the component to seeif there is a method that accepts the transformer return type. If so, this method will be used. Note ifthere is more than one match, an exception will be thrown.

5. If none of the above finds a match, an exception will be thrown and the component registration willfail.

There are many scenarios where the LegacyEntryPointResolverSet is unsuitable. More control is availableby extending its set of implementations, or by configuring a completely new set. There are severalEntryPointResolver implementations, such as org.mule.model.resolvers.CallableEntryPointResolver, org.mule.model.resolvers.MethodHeaderPropertyEntryPointResolver , andorg.mule.model.resolvers.ReflectionEntryPointResolver . While these are used in theLegacyEntryPointResolverSet, they can be more comprehensively configured when specified separately.

Calling No-arguments Methods

If you want to call a method with no arguments, you can use theorg.mule.model.resolvers.NoArgumentsEntryPointResolver . Regardless of the payload of thecurrent message, this resolver looks only for no-argument methods in the component. Additionally,ReflectionEntryPointResolver supports the resolution of no-argument service methods if the payloadreceived is of type NullPayload.

Custom Entry Point Resolver

If you want to create your own entry point resolver, you create a class that implements theEntryPointResolver interface and specify it with the <custom-entry-point-resolver> element in yourMule configuration.

Default Message Flow Behavior

Mule has some default behavior rules about managing message flow to and from your component.

1. When a message is received, the entry point method is invoked as described above.2. The response or outbound message is obtained as follows:

• If the method invoked is not void, (that is, Callable.onEvent() returns an Object), the methodreturn value is used. If null is returned, no further processing is done for the current request.

• If the method is void, the parameters used to invoke the method are used. This assumes thatthe parameters themselves were altered or there was no change to the message.

3. If the inbound endpoint used in synchronous then the result of the component invocation is returnedto caller.

4. The outbound message is then routed according the services <outbound> configuration:

See Mule Messaging Styles for more detail about the different configuration options that affect messageflow.

Customizing the Message Flow Behavior

To customize the message flow behavior, you must get a reference to org.mule.api.MuleEventContext .You can get the reference by implementing the Callable interface, which passes the event context as aparameter on this interface:

public interface Callable{ public Object onCall(MuleEventContext eventContext) throws Exception;}

Page 400: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 400

From the MuleEventContext, you can send and receive events synchronously and asynchronously,manage transactions, and override the default event flow behavior. For example:

MuleEventContext context = RequestContext.getEventContext();OutboundEndpoint endpoint = ...

//to send asynchronouslycontext.dispatchEvent(new MuleMessage("IBM:0.01", null), endpoint);

//or to requestInboundEndpoint endpoint = ...MuleMessage quote = context.request(endpoint, 5000);

Even when you use the event context to manually control event flow, when your method returns, Mulewill route the outbound event as normal. You can stop Mule processing events further as follows:

• If your service method is not void, you can return null. This approach tells Mule there is no furtherevent information to process.

• If your service method is void, Mule will use the inbound message payload as the outbound messagepayload. You can override this behavior using the setStopFurtherProcessing method as describedbelow.

Halting Message Flow

To halt the message flow, you can either call setStopFurtherProcessing() from the MuleEventContextor else throw an exception. This will cause the ExceptionStrategy on the component to be invoked.

Note:The use of additional services or the use of component bindings is much preferred to the abovetechniques to control message flow from within your component implementation. This is because it allowsfor a much more decoupled implementation that can be modified via your configuration file and avoidsthe need to use Mule API in your component implementations. To take this approach, do one of thefollowing:

• Ensure your service components are implemented in such a way that they do a single unit of workthat do not need to do any message sending/receiving. This additional sending/receiving/routing isthen done using Mule services.

• Design your component in such a way that interface methods can be mapped to outbound endpointsand then use bindings to map these in configuration. For information on how to configure bindings,see Configuring Java Components.

Component Lifecycle

Your component can implement several lifecycle interfaces. The lifecycle flow typically looks like this, withonCall() often being replaced by an entry point resolver as described above:

Page 401: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 401

Following are the most commonly used interfaces:

• org.mule.api.lifecycle.Initialisable is called only once for the lifecycle of the component. It is calledwhen the component is created when the component pool initializes.

• org.mule.api.lifecycle.Startable is called when the component is started. This happens once whenthe server starts and whenever the component is stopped and started either through the API orJMX.

• org.mule.api.lifecycle.Stoppable is called when the component is stopped. This happens when theserver stops or whenever the component is stopped either through the API or JMX.

• org.mule.api.lifecycle.Disposable is called when the component is disposed. This is called once whenthe server shuts down.

For more information, see the org.mule.api.lifecycle Javadocs .

If your custom component already has its own lifecycle methods, possibly implementing your own API, oryou just prefer not to depend on Mule's, you can implement and configure a LifecycleAdaptorFactoryto map Mule's lifecyle to your component's lifecycle. To do this, you implement your ownorg.mule.api.component.LifecycleAdaptorFactory and org.mule.api.component.LifecycleAdaptor . SeeConfiguring Java Components for information on how to configure a custom life-cycle adaptor factory.

Page 402: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 402

Entry Point Resolver Configuration Reference

This page last changed on Feb 20, 2009 by jackie.wheeler.

Entry Point Resolver Configuration Reference

This page provides details on the elements you configure for entry point resolvers and entry pointresolver sets. This information is pulled directly from mule.xsd and is cached. If the information appearsto be out of date, refresh the page.

Entry Point Resolver Sets

<entry-point-resolver-set ...>

An extensible set of entry point resolvers. These determine how a message is passed to a componentin Java. Each entry point resolver is tried in turn until one succeeds in delivering the message to thecomponent. This element can be set on the model or component; the model value provides a default thatindividual component values can override.

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

abstract-entry-point-resolver

0..* A placeholder foran entry pointresolver element.Entry pointresolvers definehow payloads aredelivered to Javacode by choosingthe method tocall.

<legacy-entry-point-resolver-set ...>

An extensible set of entry point resolvers (which determine how a message is passed to a component inJava) that already contains resolvers to implement the standard logic. This is already provided by defaultand is only needed explicitly if it will be extended with other entry point resolvers. This element can beset on the model or component; the model value provides a default that individual component values canoverride.

Page 403: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 403

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

abstract-entry-point-resolver

0..* A placeholder foran entry pointresolver element.Entry pointresolvers definehow payloads aredelivered to Javacode by choosingthe method tocall.

<custom-entry-point-resolver-set ...>

A custom entry point resolver set. This allows user-supplied code to determine how a message is passedto a component in Java. This element can be set on the model or component; the model value provides adefault that individual component values can override.

Attributes

Name Type Required Default Description

class class name no Animplementationof theEntryPointResolverSetinterface.

Child Elements

Name Cardinality Description

spring:property 0..*

Entry Point Resolvers

<callable-entry-point-resolver ...>

An entry point resolver for components that implement the Callable interface. This passes aMuleEventContext to the component. This element can be set on the model or component; the modelvalue provides a default that individual component values can override. This element can also be useddirectly or as part of a set of resolvers; the resolvers in a set are used in turn until one is successful.

Page 404: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 404

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

<custom-entry-point-resolver ...>

A custom entry point resolver. This allows user-supplied code to determine how a message is passed toa component in Java. This element can be set on the model or component; the model value provides adefault that individual component values can override. This element can also be used directly or as partof a set of resolvers; the resolvers in a set are used in turn until one is successful.

Attributes

Name Type Required Default Description

class class name no Animplementationof theEntryPointResolverinterface.

Child Elements

Name Cardinality Description

spring:property 0..*

<property-entry-point-resolver ...>

Uses a message property to select the component method to be called. This element can be set on themodel or component; the model value provides a default that individual component values can override.This element can also be used directly or as part of a set of resolvers; the resolvers in a set are used inturn until one is successful.

Attributes

Name Type Required Default Description

transformFirst boolean no Whether themessage shouldbe transformedbefore beingdelivered to thecomponent. Bydefault, messagesare transformed.

Page 405: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 405

acceptVoidMethods boolean no Whether theresolver shouldcall void methods.By default, voidmethods arenot consideredas possiblecandidates formessage delivery.

property name (no spaces) no The name of themessage propertyused to select amethod on thecomponent.

Child Elements

Name Cardinality Description

<method-entry-point-resolver ...>

Delivers the message to a named method. This element can be set on the model or component; themodel value provides a default that individual component values can override. This element can also beused directly or as part of a set of resolvers; the resolvers in a set are used in turn until one is successful.

Attributes

Name Type Required Default Description

transformFirst boolean no Whether themessage shouldbe transformedbefore beingdelivered to thecomponent. Bydefault, messagesare transformed.

acceptVoidMethods boolean no Whether theresolver shouldcall void methods.By default, voidmethods arenot consideredas possiblecandidates formessage delivery.

Child Elements

Name Cardinality Description

include-entry-point 1..* A possible method for delivery.

Page 406: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 406

<reflection-entry-point-resolver ...>

Generates a list of candidate methods from the component via reflections. This element can be set on themodel or component; the model value provides a default that individual component values can override.This element can also be used directly or as part of a set of resolvers; the resolvers in a set are used inturn until one is successful.

Attributes

Name Type Required Default Description

transformFirst boolean no Whether themessage shouldbe transformedbefore beingdelivered to thecomponent. Bydefault, messagesare transformed.

acceptVoidMethods boolean no Whether theresolver shouldcall void methods.By default, voidmethods arenot consideredas possiblecandidates formessage delivery.

Child Elements

Name Cardinality Description

exclude-object-methods 0..1 If specified, methods in the JavaObject interface are not includedin the list of possible methodsthat can receive the message.

exclude-entry-point 0..* Explicitly excludes a namedmethod from receiving themessage.

<array-entry-point-resolver ...>

Delivers the message to a method that takes a single array as argument. This element can be set on themodel or component; the model value provides a default that individual component values can override.This element can also be used directly or as part of a set of resolvers; the resolvers in a set are used inturn until one is successful.

Page 407: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 407

Attributes

Name Type Required Default Description

transformFirst boolean no Whether themessage shouldbe transformedbefore beingdelivered to thecomponent. Bydefault, messagesare transformed.

acceptVoidMethods boolean no Whether theresolver shouldcall void methods.By default, voidmethods arenot consideredas possiblecandidates formessage delivery.

enableDiscovery boolean no true If no methodnames areconfigured,attempts todiscover themethod to invokebased on theinbound messagetype.

Child Elements

Name Cardinality Description

exclude-object-methods 0..1 If specified, methods in the JavaObject interface are not includedin the list of possible methodsthat can receive the message.

exclude-entry-point 0..* Explicitly excludes a namedmethod from receiving themessage.

include-entry-point 0..* A possible method for delivery.

<no-arguments-entry-point-resolver ...>

Calls a method without arguments (the message is not passed to the component).

Page 408: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 408

Attributes

Name Type Required Default Description

transformFirst boolean no Whether themessage shouldbe transformedbefore beingdelivered to thecomponent. Bydefault, messagesare transformed.

acceptVoidMethods boolean no Whether theresolver shouldcall void methods.By default, voidmethods arenot consideredas possiblecandidates formessage delivery.

enableDiscovery boolean no true If no methodnames areconfigured,attempts todiscover themethod to invokebased on theinbound messagetype.

Child Elements

Name Cardinality Description

exclude-object-methods 0..1 If specified, methods in the JavaObject interface are not includedin the list of possible methodsthat can receive the message.

exclude-entry-point 0..* Explicitly excludes a namedmethod from receiving themessage.

include-entry-point 0..* A possible method for delivery.

<include-entry-point ...>

A possible method for delivery.

Page 409: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 409

Attributes

Name Type Required Default Description

method name no The name of themethod.

Child Elements

Name Cardinality Description

Page 410: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 410

Error Handling

This page last changed on Mar 06, 2009 by jackie.wheeler.

Error Handling

[ Exception Strategies ] [ Using the Exception-based Router ] [ Using the Exception Type Filter ]

Mule provides several ways to handle errors. You can set exception strategies for models, components,and connectors. You can use the exception router to specify where the message goes when an erroroccurs. You can also use the exception type filter for fine-grained control. This page describes the variouserror-handling techniques. For information on setting retry policies, which control how a connectorbehaves when its connection fails, see Configuring Retry Policies.

Exception Strategies

Exception strategies are used to handle exception conditions when an error occurs during the processingof a message. Exception strategies are used by components and connectors. You can set a commonexception strategy for all components in a model by configuring the exception strategy on that model.

Cannot resolve external resource into attachment.

Exception strategies associated with components or the model are used to handle component exceptions.These are typically business logic exceptions. Typically, you customize the exception handler to controlhow component exceptions are logged and routed.

Exceptions strategies associated with the connector handle exceptions thrown when messages arereceived or sent using a connector. Typically, you do not need to customize connector strategies, but youcan configure them to route exceptions to a common error queue.

For details on configuring exception strategies, see Exception Strategy Configuration Reference.

Model and Component Exception Strategies

The default exception strategy used by the model (and thus all components managed by the model) isorg.mule.service.DefaultServiceExceptionStrategy , which you configure with the <default-service-exception-strategy> element. To configure it at the model level, add the element before the services:

<model name="CreditCheck"> <default-service-exception-strategy> <vm:outbound-endpoint path="systemErrorHandler"/> </default-service-exception-strategy> <service> ... </service> <service> ... </service></model>

To configure it on a service, add it at the end of the service:

<model name="CreditCheck"> <service> ... <default-service-exception-strategy> <vm:outbound-endpoint path="systemErrorHandler"/> </default-service-exception-strategy> </service></model>

Page 411: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 411

You set an endpoint on an exception strategy to forward the message that failed to a destination such asan error queue.

To implement your own strategy, your class can extend org.mule.AbstractExceptionListener , but arecommended approach is to extend org.mule.service.DefaultServiceExceptionStrategy and just overloadthe defaultHandler() method. You can set bean properties on your custom exception strategy in thesame way as other Mule-configured objects using a <properties> element.

It is up to the defaultHandler() method to do all necessary processing to contain the exception, so anexception should never be thrown from an exception strategy. The exception strategy must manage fatalerrors. For example, if an error queue is being used but the dispatch fails, you might want to stop thecurrent component and fire a server notification to alert a system monitor and write the event to file.

If you want to change the way exceptions are logged, override the logException() method fromorg.mule.AbstractExceptionListener .

Connector Exception Strategies

The default exception strategy used by a connector is org.mule.DefaultExceptionStrategy , which youconfigure with the <default-exception-strategy> element. This strategy simply logs exceptions andcontinues. The exceptions this strategy must handle are typically connection-related exceptions that mayor may not be recoverable.

Using the Exception-based Router

When an exception occurs, the exception-based router org.mule.routing.outbound.ExceptionBasedRouterdetermines where the message goes. You can have multiple endpoints specified on the exception-basedrouter, so that if the first endpoint fails with a FatalConnectionException, the next endpoint is tried,and then the next. If all endpoints fail, an org.mule.api.routing.RoutingException is thrown. Note thatthe exception-based router will override the endpoint mode to synchronous while looking for a successfulsend, and it will resort to using the endpoint's mode for the last item in the list.

Following is an example of configuring the exception-based router:

<outbound> <exception-based-router> <tcp:endpoint host="10.192.111.10" port="10001" /> <tcp:endpoint host="10.192.111.11" port="10001" /> <tcp:endpoint host="10.192.111.12" port="10001" /> </exception-based-router></outbound>

For more information on routers, see Using Message Routers.

Using the Exception Type Filter

You can use the exception type filter to gain fine-grained control over messages that produce errors.For example, assume you want a synchronous flow where the message is sent to a validation service,and then if it fails validation, the message and its exception are forwarded to another service AND themessage and its exception are returned to the caller. You could achieve this using a chaining router andthe <exception-type-filter> as follows:

<chaining-router> <vm:outbound-endpoint path="ValidationService" synchronous="true"/> <vm:outbound-endpoint path="ValidationError" synchronous="true"> <exception-type-filter expectedType="java.lang.Exception"/> </vm:outbound-endpoint>

Page 412: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 412

</chaining-router>

For more information on filters, see Using Filters.

Page 413: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 413

Functional Testing

This page last changed on Feb 27, 2009 by jackie.wheeler.

Functional Testing

[ FunctionalTestCase ] [ FunctionalTestComponent ] [ Additional Features ] [ Additional Example: EventCallback With a Spring Component ] [ Test Component Configuration Reference ] [ Component ] [ WebService Component ]

Because Mule is light-weight and embeddable, it is easy to run a Mule Server inside a test case. Muleprovides an abstract JUnit test case called org.mule.tck.FunctionalTestCase that runs Mule inside a testcase and manages the lifecycle of the server. The org.mule.tck.functional package contains a number ofsupporting classes for functionally testing Mule code, including FunctionalTestComponent . These classesare described in more detail in the following sections.

FunctionalTestCase

FunctionalTestCase is a base test case for Mule functional tests. Your test cases can extendFunctionalTestCase to use its functionality.

FunctionalTestCase fires up a Mule server using a configuration you specify by overriding thegetConfigResources():

protected String getConfigResources(){ return "mule-conf.xml";}

You can use the method getConfigResources to specify a configuration file or comma-separated list of configuration files to use. All configuration files must exist in yourclasspath.

You then create tests that interact with the Mule server. FunctionalTestCase extendsjunit.framework.TestCase, so JUnit the framework for creating and running your test cases. Forexample, this simple test would send a message to a vm endpoint .

public void testSend() throws Exception{ MuleClient client = new MuleClient(); String payload = "foo"; MuleMessage result = client.send("vm://test", new DefaultMuleMessage(payload)); assertEquals("foo Received", result.getPayloadAsString());}

Notice the use of MuleClient to interact with the running Mule server. MuleClient is used to sendmessages to and receive messages from endpoints you specify in your Mule configuration file (mule-conf.xml in this case). The example mule-conf.xml file used in this example is shown below:

<?xml version="1.0" encoding="UTF-8"?><mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.2" xmlns:test="http://www.mulesource.org/schema/mule/test/2.2"

Page 414: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 414

xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/vm/2.2 http://www.mulesource.org/schema/mule/vm/2.2/mule-vm.xsd http://www.mulesource.org/schema/mule/test/2.2 http://www.mulesource.org/schema/mule/test/2.2/mule-test.xsd"> <model name="TestComponentModel"> <service name="TestComponentService"> <inbound> <inbound-endpoint address="vm://test"/> </inbound> <test:component appendString=" Received"/> </service> </model></mule>

Watchdog Timeout

The base test case class includes a watchdog timeout feature that times out your functional test after 60seconds. To change this setting, add -Dmule.test.timeoutSecs=XX either to the mvn command you useto run Mule or to the JUnit test runner in your IDE.

FunctionalTestComponent

The previous example of FunctionalTestCase covers many common (synchronous) test scenarios, wherethe service responds directly to the caller. FunctionalTestComponent can help support richer tests, suchas:

1. Simulating asynchronous communication2. Returning mock data to the caller3. Common scenarios such as forced exceptions, storing message history, appending text to responses,

and delayed responses.

The component includes two methods: the onCall method and the onReceive method that basically dothe same thing.

• onCall: receives a MuleEventContext as input and returns an Object.• onReceive: receives an Object as input and returns an Object.

In both methods, FunctionalTestComponent takes the message that is passed to it (either from theMuleEventContext or from the Object) and transform it into a String. It then creates a message andsends it back to the caller. It also checks whether any of its properties are set and acts accordingly.

Asynchronous Tests with FunctionalTestComponent

The FunctionalTestComponent supports two event mechanisms for responding to a callerasynchronously: event callbacks and notifications. Both event callbacks and notifications fire eventsthat get handled by registered listeners. During functional testing, the listener will typically be a classaccessible in the FunctionalTestCase.

Event Callbacks

User-defined event callbacks get called when the test component is invoked. Following is an example of atest case and Mule configuration that uses callbacks:

public void testEventCallback() throws Exception

Page 415: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 415

{ EventCallback callback = new EventCallback() { public void eventReceived(MuleEventContext context, Object component) throws Exception { System.out.println("Thanks for calling me back"); } }; muleContext.getFunctionalTestComponent("TestComponentService").setEventCallback(callback); MuleClient client = new MuleClient(); client.send("vm://test", new DefaultMuleMessage("foo")); }

In this example, the eventReceived callback method is invoked as soon as theFunctionalTestComponent receives the message, and a message is printed to the console. Testassertions could be made in this method.

The corresponding Mule configuration used in this example is as follows:

<?xml version="1.0" encoding="UTF-8"?><mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.2" xmlns:test="http://www.mulesource.org/schema/mule/test/2.2" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/vm/2.2 http://www.mulesource.org/schema/mule/vm/2.2/mule-vm.xsd http://www.mulesource.org/schema/mule/test/2.2 http://www.mulesource.org/schema/mule/test/2.2/mule-test.xsd"> <model name="TestComponentModel"> <service name="TestComponentService"> <inbound> <inbound-endpoint address="vm://test"/> </inbound> <component> <singleton-object class="org.mule.tck.functional.FunctionalTestComponent"/> </component> </service> </model></mule>

Notice that in this configuration, we did not use the "<test:component>" element, since we needFunctionalTestComponent to be singleton for the callback to work properly.

For an example of an event callback on a Spring component, see the additional example below.

Page 416: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 416

Notifications

Notifications are an alternative to event callbacks. When an event is received, theFunctionalTestComponent fires a notification informing us that the event has been received. It is upto us to set up a listener (the FunctionalTestNotificationListener) on our test to capture thisnotification.

To do this, we must first make our test case implement the FunctionalTestNotificationListenerinterface. Then, we must implement the method exposed by this listener, which is onNotification.In the example below, we check notification.getAction to see whether it is theFunctionalTestNotification fired by the FunctionalTestComponent. If it is, we print it out to theconsole.

public void onNotification(ServerNotification notification){ if (notification.getAction() == FunctionalTestNotification.EVENT_RECEIVED) { System.out.println("Event Received"); }}

Now, in order for our listener to start listening for notifications, we must register it:

muleContext.registerListener(this,"myComponent");

Returning Mock Data from FunctionalTestComponent

FunctionalTestComponent can return mock data specified either in a file or embedded in the Muleconfiguration. For example, to have the FunctionalTestComponent return the message "donkey", youwould configure the component as follows:

<test:component> <test:return-data>donkey</test:return-data></test:component>

To return contents from a file, you could use:

<test:component> <test:return-data file="abc.txt"/></test:component>

The file referenced should exist on the Mule classpath.

Other Useful Features of FunctionalTestComponent

Forcing Exceptions

You can use throwException to always return the exception specified by exceptionToThrow, as follows:

Page 417: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 417

<test:component throwException="true" exceptionToThrow="your.service.exception"/>

Storing Message History

By default, every message that is received by the FunctionalTestComponent is stored and can beretrieved. If you do not want this information stored, you can set enableMessageHistory to false. Forexample, if you are running millions of messages through the component, an out-of-memory error wouldprobably occur eventually if this feature were enabled.

To enable:

<test:component enableMessageHistory="true" />

Messages are stored in an ArrayList. To retrieve a stored message, you use the getReceivedMessagemethod to retrieve it by number (e.g., getReceivedMessage(1) to retrieve the first message stored),or use getLastReceivedMessage to retrieve the last message that was received. You can usegetReceivedMessages to return the total number of messages stored.

Appending Text to Responses

You can use appendString to append text to the response message, as follows:

<test:component appendString="Received" />

Delayed Responses

You can set waitTime to delay responses from this FunctionalTestComponent. In this example,responses are delayed five seconds:

<test:component waitTime="5000" />

Disable Inbound Transformer

You can set doInboundTransform to false to disable the inbound transformer. For example:

<test:component doInboundTransform="false" />

Additional Features

The functional package includes several additional classes, such as CounterCallback, a test callbackthat counts the number of messages received. For complete information, see the org.mule.tck.functionalJavadoc.

Page 418: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 418

Additional Example: Event Callback With a Spring Component

This example is similar to the "Event Callbacks" example above, except the component used here is aSpring component. In this case, we can look up the component using the Spring registry.

public void testEventCallback() throws Exception { EventCallback callback = new EventCallback() { public void eventReceived(MuleEventContext context, Object component) throws Exception { System.out.println("Thanks for calling me back"); } }; ApplicationContext ac = (ApplicationContext)muleContext.getRegistry().lookupObject(SpringRegistry.SPRING_APPLICATION_CONTEXT); FunctionalTestComponent testComponent = (FunctionalTestComponent) ac.getBean("FTC"); testComponent.setEventCallback(callback); MuleClient client = new MuleClient(); client.send("vm://test", new DefaultMuleMessage("foo")); }

The corresponding Mule configuration would be as follows:

<?xml version="1.0" encoding="UTF-8"?><mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.2" xmlns:test="http://www.mulesource.org/schema/mule/test/2.2" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/vm/2.2 http://www.mulesource.org/schema/mule/vm/2.2/mule-vm.xsd http://www.mulesource.org/schema/mule/test/2.2 http://www.mulesource.org/schema/mule/test/2.2/mule-test.xsd">

<spring:bean id="FTC" class="org.mule.tck.functional.FunctionalTestComponent" />

<model name="TestComponentModel"> <service name="TestComponentService"> <inbound> <inbound-endpoint address="vm://test" /> </inbound> <component> <spring-object bean="FTC" /> </component> </service> </model>

Page 419: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 419

</mule>

Test Component Configuration Reference

Following is detailed information about the test components provided in the test framework (mule-test.xsd).

Component

A component that can be used for testing message flows. It is a configurable component. The return datafor the component can be set so that users can simulate a call to a real service. This component can alsotrack invocation history and fire notifications when messages are received.

Attributes of <component...>

Name Type Required Default Description

throwException boolean no Whether thecomponentshould throw anexception beforeany processingtakes place.

logMessageDetails boolean no Whether to outputall messagedetails to the log.This includes allheaders and thefull payload. Theinformation will beloogged at INFOlevel.

doInboundTransform boolean no Whether themessage will betransformed usingthe transformer(s)set on the inboundendpoint beforeit gets processed.The default istrue.

exceptionToThrow name (no spaces) no A fully qualifiedclassname of theexception objectto throw. Used inconjunction withthrowException.If this is notspecified, aFunctionalTestExceptionwill be thrown bydefault.

enableMessageHistoryboolean no Every messagethat is received

Page 420: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 420

by the testcomponent isstored and canbe retrieved. Ifyou do not wantthis informationstored, suchas if you arerunning millions ofmessages throughthe component,you can disablethis feature toavoid a potentialout of memoryerror.

enableNotifications boolean no Whether to fire aFunctionalTestNotificationwhen a messageis received by thecomponent. Testcases can registerto receive thesenotifications andmake assertionson the currentmessage.

appendString string no A string value thatwill be appenededto every messagepayload thatpasses throughthe component.Note that bysetting thisproperty youimplicitly selectthat the messagepayload will beconverted to astring and thata string payloadwill be returned.The inboundtransformer (ifany) will getapplied first, butif that does notreturn a string,MuleEventContext.getMessageAsString()will be calleddirectly after.

waitTime long no The time inmillisecondsto wait beforereturning a result.All processinghappens in thecomponent beforethe wait begins.

Page 421: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 421

Child Elements of <component...>

Name Cardinality Description

return-data 0..1 Defines the data to return fromthe service once it has beeninvoked. The return data canbe located in a file, which youspecify using the file attribute(specify a resource on theclasspath or on disk), or thereturn data can be embedddeddirectly in the XML.

callback 0..1 A user-defined callback thatis invoked when the testcomponent is invoked. Thiscan be useful for capturinginformation such as messagecounts. Use the class attributeto specify the callback classname, which must be anobject that implementsorg.mule.tck.functional.EventCallback.

Web Service Component

A component that can be used for testing web services. This componenthas the same properties as component element, but in addition toimplementing org.mule.api.lifecycle.Callable, it also implementsorg.mule.api.component.simple.EchoService, org.mule.tck.testmodels.services.DateService,and org.mule.tck.testmodels.services.PeopleService. When using this with WS endpoints such asCXF, be sure to set the serviceClass property of the endpoint to the type of service you are using.

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

Name Type Required Default Description

throwException boolean no Whether thecomponentshould throw anexception beforeany processingtakes place.

logMessageDetails boolean no Whether to outputall messagedetails to the log.This includes allheaders and thefull payload. Theinformation will beloogged at INFOlevel.

doInboundTransform boolean no Whether themessage will betransformed using

Page 422: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 422

the transformer(s)set on the inboundendpoint beforeit gets processed.The default istrue.

exceptionToThrow name (no spaces) no A fully qualifiedclassname of theexception objectto throw. Used inconjunction withthrowException.If this is notspecified, aFunctionalTestExceptionwill be thrown bydefault.

enableMessageHistoryboolean no Every messagethat is receivedby the testcomponent isstored and canbe retrieved. Ifyou do not wantthis informationstored, suchas if you arerunning millions ofmessages throughthe component,you can disablethis feature toavoid a potentialout of memoryerror.

enableNotifications boolean no Whether to fire aFunctionalTestNotificationwhen a messageis received by thecomponent. Testcases can registerto receive thesenotifications andmake assertionson the currentmessage.

appendString string no A string value thatwill be appenededto every messagepayload thatpasses throughthe component.Note that bysetting thisproperty youimplicitly selectthat the messagepayload will beconverted to astring and that

Page 423: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 423

a string payloadwill be returned.The inboundtransformer (ifany) will getapplied first, butif that does notreturn a string,MuleEventContext.getMessageAsString()will be calleddirectly after.

waitTime long no The time inmillisecondsto wait beforereturning a result.All processinghappens in thecomponent beforethe wait begins.

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

Name Cardinality Description

return-data 0..1 Defines the data to return fromthe service once it has beeninvoked. The return data canbe located in a file, which youspecify using the file attribute(specify a resource on theclasspath or on disk), or thereturn data can be embedddeddirectly in the XML.

callback 0..1 A user-defined callback thatis invoked when the testcomponent is invoked. Thiscan be useful for capturinginformation such as messagecounts. Use the class attributeto specify the callback classname, which must be anobject that implementsorg.mule.tck.functional.EventCallback.

Page 424: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 424

Open MQ Integration

This page last changed on Feb 09, 2009 by jackie.wheeler.

Open MQ Integration

This page describes how to integrate Mule with the Open MQ JMS broker, the community version ofSun Java System Message Queue. It includes examples for configuring a direct connection and a JNDIconnection.

Direct Connection

To create a direct connection, simply specify the connection factory and JMS connector as follows in yourMule configuration file:

<spring:bean name="connectionFactory" class="com.sun.messaging.ConnectionFactory"/>

<jms:connector name="JMSConnector" connectionFactory-ref="connectionFactory" specification="1.1"/>

JNDI Connection

To create a JNDI connection, take the following steps:

1. Configure Open MQ using the instructions from Sun here. You must use the Open MQ or MessageQueue Administration Console to define the connectionFactory (Factory type topic/queue connectionfactory) and to configure any Open MQ JMS endpoints you will specify in your Mule configuration file.

2. Configure the JMS connector, Spring beans, and endpoints in your Mule configuration file as follows,ensuring that you include all the tags shown below:

<jms:connector name="jmsConnector" connectionFactory-ref="openMQ" specification="1.1">

<spring:property name="jmsSupport" ref="jndiJmsSupport" /></jms:connector>

<spring:beans> <spring:bean name="jndiJmsSupport" class="org.mule.transport.jms.Jms102bSupport"> <spring:constructor-arg ref="jmsConnector" /> </spring:bean>

<spring:bean name="context" class="javax.naming.InitialContext"> <spring:constructor-arg type="java.util.Hashtable"> <spring:props> <spring:prop key="java.naming.factory.initial">com.sun.jndi.fscontext.RefFSContextFactory </spring:prop> <spring:prop key="java.naming.provider.url">file:///C:/pawan/openMQ/mq</spring:prop> </spring:props> </spring:constructor-arg> </spring:bean>

<spring:bean name="openMQ" class="org.springframework.jndi.JndiObjectFactoryBean"> <spring:property name="jndiName" value="MyTopicConnectionFactory" /> <spring:property name="jndiEnvironment"> <spring:props>

Page 425: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 425

<spring:prop key="java.naming.factory.initial">com.sun.jndi.fscontext.RefFSContextFactory </spring:prop> <spring:prop key="specifications">1.1</spring:prop> <spring:prop key="java.naming.provider.url">file:///C:/Temp</spring:prop> </spring:props> </spring:property> </spring:bean></spring:beans>

<endpoint name="MyEndPoint" address="jms://topic:my_topic" synchronous="false" connector-ref="jmsConnector"/>

3. Copy imq.jar and fscontext.jar from the $OPENMQ_HOME/lib directory to the $MULE_HOME/lib/user directory.

Page 426: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 426

Internationalizing Strings

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

Internationalizing Strings

[ Internationalized Messages ] [ Exceptions ] [ Using Custom Message Bundles ] [ Creating MessageInstances from your Code ]

Mule supports internationalization of exception messages and any other type of string message. Mule hassupport for the following Languages:

• English• Japanese

Internationalized Messages

Mule uses the Java ResourceBundle class to load messages from properties files on the classpath basedon the current system's locale. Mule provides a full set of messages in English and Japanese only, butthere may be additional languages provided in the future.

Mule's internationalized messages are represented by the org.mule.config.i18n.Message class. Instancesare constructed with a message ID and zero or more message parameters. You can see a list of coremessages that Mule provides in META-INF/service/org/mule/i18n/core-messages.properties.

You never create instances of Message directly. Instead, you use subclasses of MessageFactory . Themessages for Mule's core project are accessible through the org.mule.config.i18n.CoreMessages class.

Each of Mule's modules and transports has such a messages class. Its name is equal to the module withMessages appended. For example, for the JMS transport you will use JmsMessages to retrieve messages.

The dedicated messages class per module/transport has the following advantages:

• Encapsulation of the message code• Client code is not cluttered with Message constructors• Client code has typesafe access to its messages• Client code is not cluttered with formatting of message parameters. Instead, you handle tihs in the

module-specific messages class

Exceptions

MuleException is the base class of all Mule checked exceptions and can only be constructed usinginternationalized messages. To create a message for an exception, you use MuleExtension as follows:

MuleException e = new MuleException(CoreMessages.failedToGetPooledObject());throw e;

Using Custom Message Bundles

When writing Mule extensions or applications that will use the Mule internationalization class, you cansupply custom message bundles containing messages specific to your extension or application. You createa resource bundle as follows:

1=Error message one2=Error message with 2 parameters; param {0} and param {1}

Page 427: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 427

...

where the number is the message ID and the actual message comes after. Note that message parametersare specified using '{0}' notation, which is standard when using the Java MessageFormat class.

The file should be named x-messages.properties where x is the identifying name for this bundle.You must place this file either in your JAR file under META-INF/services/org/mule/i18n/x-messages.properties or any other location on the classpath.

To access the messages of your own resource bundle, you create a subclass of MessageFactory asfollows:

public class MyMessages extends MessageFactory{ // getBundlePath puts together the correct path (META-INF/services/org/mule/i18n/my-messages.properties) private static final String BUNDLE_PATH = getBundlePath("my");

public static Message errorMessageOne() { return createMessage(BUNDLE_PATH, 1); }

public static Message anotherErrorMessage(Object param1, Object param2) { createMessage(BUNDLE_PATH, 2, param1, param2); }}

To load a message from this bundle, pass in the resource bundle name as follows:

Message m = MyMessages.anotherErrorMessage("one", "two");System.out.pritln(m.toString());

This loads the message with ID 2 from x-messages.properties, formats the message with theparameters "one" and "two", and prints out the message to System.out as follows:

Error message with 2 parameters; param one and param two

Creating Message Instances from your Code

If you need Message instances from your custom code (e.g., from a custom transformer), you createthem as follows:

Message myMessage = MessageFactory.createStaticMessage("Oops");

Page 428: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 428

Introduction to Extending Mule

This page last changed on Dec 11, 2008 by jackie.wheeler.

Introduction to Extending Mule

[ Creating Extensions ] [ Developing Your Extension ] [ Promoting Your Extension on MuleForge ] [Internationalizing Mule ]

Mule provides a great deal of default functionality that you can use in your implementation. If you needdifferent functionality, you can extend Mule as described on this page.

Creating Extensions

There are four types of extensions you can create: projects, modules, transports, and examples.

• A project is a stand-alone Mule application, such as the Mule IDE.

• A module is a package of related functionality in Mule, such as the XML module, which providesXML-based utilities such as filters and routers. For a list of the available modules you can use, seeUsing Mule Modules.

• A transport is a type of module that carries messages between Mule services via a specificprotocol. For a list of the available transports you can use, see Available Transports.

• An example is a sample application that you create to help users get up and running more quickly.There are several examples provided with Mule.

Mule provides Maven archetypes that create the templates for each of these types of functionality inseconds, including the configuration files, unit tests, and packages:

• Project Archetype• Module Archetype• Transport Archetype• Example Archetype

An archetype acts as a wizard, prompting you to provide input, and then creates template configuration,source, and unit test files. Furthermore, if you run an archetype on an existing project or module youcreated, it will update it for you. For more information on Maven, see Using Maven.

When working with transports, note that you can configure an existing transport, or you can create a newone. The recommended approach is to try to use and configure an existing transport first.

Developing Your Extension

After using the Maven archetype to get started, the recommended practice is to use an integrateddevelopment environment (IDE) such as Eclipse or IntelliJ to develop your Mule project, transport,module, or example. The Mule IDE allows you to quickly get up and running developing with Mule inEclipse. For more information, see Using IDEs.

Promoting Your Extension on MuleForge

After you have created a new extension, you can submit it as a project on MuleForge. This allows youto share it with the Mule community so you can get feedback on the quality and design of the modulebefore putting it into production. By submitting to MuleForge, you get the benefit of others trying outyour module, and others get the benefit of your work. For more information, see About MuleForge.

Page 429: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 429

Internationalizing Mule

If you will use Mule in countries where English is not spoken, you can extend Mule by internationalizingthe strings in the messages and exceptions. Additionally, there are guidelines you should takeinto consideration to make sure your code handles different locales. For more information, seeInternationalizing Strings and Internationalization Guidelines.

Page 430: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 430

Introduction to Testing Mule

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

Introduction to Testing Mule

This page describes the types of testing you can perform on Mule.

Functional and Unit Tests

When you configure and customize Mule, you perform the following types of tests:

• Functional testing of your Mule configuration and setup• Unit testing of your simple extensions and customizations• Functional and unit testing of your custom modules and transports

Mule provides functional test classes in the org.mule.tck and org.mule.tck.functional packagesthat allow you to test your configuration as well as your custom modules and transports. For moreinformation, see Functional Testing. Additionally, the Mule test JAR file contains abstract test casesthat you can use for unit testing your simple extensions (e.g., AbstractTransformerTestCaseand AbstractOutboundRouterTestCase) as well as your custom modules and transports (e.g.,AbstractConnectorTestCase, AbstractReceiverTestCase, AbstractDispatcherTestCase, andAbstractEndpointTestCase). For more information, see Unit Testing.

Performance Tests

After you have ensured that your setup and configuration are correct and that your customizations areworking, you should ensure that your system is performing correctly. You can run Japex benchmark teststo test individual packages. Additionally, the Mule Profiler Pack helps you identify memory leaks in yourcustomizations.

Using MuleForge for Continuous Integration Testing

If you host your Mule project on MuleForge, you can take advantage of continuous integration testing.MuleForge projects are configured to be automatically built using Bamboo, a Continuous Integration BuildServer from Atlassian. The source code build frequency is set to 30 minutes, while the snapshot buildfrequency is set to 1 day. You can request that these frequencies be changed for your project.

For more information on hosting your project on MuleForge, see the Despot's Guide.

Page 431: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 431

Models

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

About Models

[ Configuring a Model ] [ Model Interface ]

A model is a grouping of services. A model manages the runtime behavior of the service componentsthat a Mule instance hosts. The manner in which these components are invoked and treated is allencapsulated inside the current Mule model.

Configuring a Model

To configure a model, you add the <model> element to your Mule configuration file. You then add serviceswithin the model. For configuration details, see the Model Configuration Reference.

Model Interface

Every Mule model implements the Model interface. This interface represents the behavior of a Mule serverand works with the following objects. For a complete list of fields and methods, see in the Model interfaceorg.mule.api.model.Model . Also, see org.mule.model.AbstractModel , which is an abstract class thatimplements this interface and is the parent for all models.

Object Description

Name A string that refers to the name of the model andis set as an attribute in the <model> element. Ifno name is given, a unique value is generatedautomatically.

ExceptionListener The exception strategy to use for the entiremodel. The exception strategy is used to handleany exceptions that occur when a component isprocessing a message. For more information onexception strategies, see Error Handling.

EntryPointResolverSet A set of classes that implement theEntryPointResolver interface. These will beused to determine the entry point for any hostedcomponent when a message is received. Youcan configure an entry point resolver using the<abstract-entry-point-resolver> elementor configure an entry point resolver set usingthe <abstract-entry-point-resolver-set>element. For more information on entry pointresolvers, see Developing Service Components.

LifecycleAdapterFactory Used by the model to create lifecycle adaptersthat are needed to translate Mule lifecycle eventsinto messages that components registered withthe model understand. You configure the lifecyleadapter on the <component> elements, not onthe model itself. For more information on lifecycleadapters, see Developing Service Components.

Page 432: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 432

Mule Agents

This page last changed on Feb 24, 2009 by jackie.wheeler.

Using Mule Agents

[ Configuring an Agent ] [ Creating Custom Agents ]

An agent is a service that is associated with or used by Mule but is not a Mule-managed component.Agents have the same lifecycle as the Mule instance they are registered with, so you can initialize anddestroy resources when the Mule instance starts or is disposed.

Mule provides several agents for JMX support, including notifications and remote management. Youcan also create custom agents to plug any functionality into Mule, such as running functionality as abackground process or embedding a server in Mule.

Configuring an Agent

Agents are defined in the Management module. To use an agent, specify the management namespace andschema, and then specify the properties for the agents you want to use. For example:

<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2"... xmlns:management="http://www.mulesource.org/schema/mule/management/2.2" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/management/2.2 http://www.mulesource.org/schema/mule/management/2.2/mule-management.xsd"...> <management:jmx-default-config port="1098" registerMx4jAdapter="true" />

<management:log4j-notifications logName="myMuleLog" logConfigFile="mule-log.txt"/>

<management:chainsaw-notifications chainsawPort="8080" chainsawHost="127.0.0.1" />

<management:publish-notifications endpointAddress="vm://myService" />...

For a list of agents provided with Mule and how to configure them, see Jmx Management. You can alsocreate a custom agent as described below.

Creating Custom Agents

To create your own agent, your agent class must implement org.mule.api.agent.Agent . You thenconfigure your agent using the <custom-agent> element, which takes two attributes: name specifies aunique name for this agent, and class specifies the class where it's defined. If your agent requires thatyou pass in properties, you can specify them as name/value pairs.

For example:

<management:custom-agent name="test-custom-agent" class="org.mule.tck.testmodels.mule.TestAgent"> <spring:property name="frobbit" value="woggle"/>

Page 433: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 433

</management:custom-agent>

Page 434: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 434

Jmx Management

This page last changed on Feb 24, 2009 by jackie.wheeler.

JMX Management

[ Using the Default JMX Support Agent ] [ Jmx Default Config ] [ Configuring the JMX Agent ] [ JmxServer ] [ Remote Management ] [ JMX Notifications Agent ] [ Endpoint Notifications Publisher Agent ] [Log4J Agent ] [ Log4J Notifications Agent ] [ Chainsaw Notifications Agent ] [ MX4J Adapter ] [ Jmx Mx4jAdaptor ] [ YourKit Profiler ]

Java Management Extensions (JMX) is a simple and standard way to manage applications, devices,services, and other resources. JMX is dynamic, so you can use it to monitor and manage resources asthey are created, installed, and implemented. You can also use JMX to monitor and manage the JavaVirtual Machine (JVM).

Each resource is instrumented by one or more Managed Beans, or MBeans. All MBeans are registered inan MBean Server. The JMX server agent consists of an Mbean Server and a set of services for handlingMbeans.

There are several agents provided with Mule for JMX support. The easiest way to configure JMX is to usethe default JMX support agent.

Using the Default JMX Support Agent

You can configure several JMX agents simultaneously using the <jmx-default-config> element. Whenset, this element registers the following agents:

• JMX agent• RMI registry agent (if necessary) on rmi://localhost:1099• Remote JMX access on service:jmx:rmi:///jndi/rmi://localhost:1099/server• Log4J JMX agent, which exposes the configuration of the Log4J instance used by Mule for JMX

management• JMX notification agent used to receive server notifications using JMX notifications• (Optional) MX4J adapter, which provides web-based JMX management, statistics, and configuration

viewing of a Mule instance

This element includes the following properties:

Jmx Default Config

Attributes of <jmx-default-config...>

Name Type Required Default Description

registerMx4jAdapter boolean no Whether to enablethe MX4J adaptor.

host string no The host to bindto. Normally,override this onlyfor multi-NICservers (default islocalhost).

port port number no The port onwhich the RMIregistry will run.This is also used

Page 435: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 435

for remote JMXmanagement.Default is 1099.

Child Elements of <jmx-default-config...>

Name Cardinality Description

credentials 0..1 A map of username/passwordproperties for remote JMXaccess. The configuration optiondelegates to the JmxAgent.

For example:

<?xml version="1.0" encoding="UTF-8" ?> <mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:management="http://www.mulesource.org/schema/mule/management/2.2" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/management/2.2 http://www.mulesource.org/schema/mule/management/2.2/mule-management.xsd"> <management:jmx-default-config port="1098" registerMx4jAdapter="true"> <management:credentials> <spring:entry key="jsmith" value="foo"/> <spring:entry key="dthomas" value="bar"/> <spring:entry key="clee" value="pwd"/> </management:credentials> </management:jmx-default-config> </mule>

Note: you only specify the port if you don't want to use the default of 1099.

The default agent does a lot of useful plumbing for JMX but at the expense of defaulting manyparameters. If you need to customize some subsystems, you could either:

• Subclass DefaultJmxSupportAgent and override the corresponding createXXX() factory methods.• Disassemble the services provided by this support agent into separate agents and configure them

individually.

Configuring the JMX Agent

The JMX agent enables the configuration of a local or remote JMX connection to Mule and registersMule services with the MBean server. You can then use JMX to view the configuration state of theMule Manager, stop and start the Mule instance, stop and start services, stop/start/resume servicecomponents, and query event processing and endpoint routing statistics on individual services or thewhole server instance.

You configure the JMX agent using the <jmx-server> element. You can set the following properties on theagent.

Page 436: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 436

Jmx Server

Attributes of <jmx-server...>

Name Type Required Default Description

server-ref name (no spaces) no The mBean serverto use.

locateServer boolean no true Whether the agentshould try locatingan MBeanServerinstance beforecreating one.

createServer boolean no true Whether theagent shouldcreate an MBeanserver if onecouldn't be foundor locateServerwas set to false.

enableStatistics boolean no true Whether statisticsreporting isenabled for theMule instance.

Child Elements of <jmx-server...>

Name Cardinality Description

connector-server 0..1 Configures the remote JMXconnector server by specifyingthe URL and whether to rebind.

credentials 0..1 A map of username/passwordentries used to authenticateremote JMX access. If notspecified, remote access is notrestricted.

For example:

<management:jmx-server > <management:connector-server url="service:jmx:rmi:///jndi/rmi://localhost:1099/server" rebind="false" /> <management:credentials> <spring:entry key="jsmith" value="foo" /> <spring:entry key="dthomas" value="bar" /> </management:credentials></management:jmx-server>

Note that the JMX domain for the Mule server is taken from the Mule server ID. To set the server ID, youthe -M-Dmule.serverId=YOUR_MULE_SERVER_ID system property or set it programatically by callingorg.mule.config.DefaultMuleConfiguration.setId().

Page 437: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 437

Remote Management

You can configure the Mule JMX subsystem for remote management with third-party tools like MC4J. Muleprovides an RMI registry agent, which binds to an existing RMI registry or creates a new one on a definedURI.

You configure the RMI registry agent using the <rmi-server> element. This element has two attributes:serverUri, which you set to the URI of the RMI server (thedefault is rmi://localhost:1099), and createRegistry, which you set to true if you want to create a newregistry instead of binding to an existing one.

For example:

<management:rmi-server serverUri="rmi://myServer.com:1099" createRegistry="true" />

JMX Notifications Agent

The <jmx-notifications> element configures the JMX notifications agent, which sends JMX servernotifications. This element takes the following attributes:

Attribute Description

ignoreManagerNotifications Whether to ignore notifications for state changeson the Mule manager such as initializing, starting,and stopping.

ignoreModelNotifications Whether to ignore notifications for state changeson models such as models initializing, starting,and stopping or components being registered orunregistered.

ignoreComponentNotifications Whether to ignore notifications for state changeson components such as when a component isstarted, stopped, paused, or resumed.

ignoreConnectionNotifications Whether to ignore notifications when a connectorattempts to connect to its underlying resource.Notifications are fired when a connection is made,released, or the connection attempt fails.

ignoreSecurityNotifications Whether to ignore notifications about security.

ignoreManagementNotifications Whether to ignore notifications for when a requestis denied security access.

ignoreCustomNotifications Whether to ignore notifications fired by objects tocustom notification listeners.

ignoreAdminNotifications Whether to ignore administrative notificationsabout requests being received by the Mule Adminagent. These are usually trigged by MuleClientcalls using the RemoteDispatcher, which proxiescalls to a remote server.

ignoreMessageNotifications Whether to ignore message notifications. Thesenotifications are fired when an event is sent orreceived in the system. They are very good for

Page 438: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 438

tracing, but they create a performance impact, sothey should only be used during testing.

For example:

<management:jmx-notifications ignoreAdminNotifications="true" ignoreMessageNotifications="true" />

Endpoint Notifications Publisher Agent

This agent routes server notifications to a specified endpoint URI. You configure it using the <publish-notifications> element and specify the endpoint using the endpointAddress attribute. For example:

<management:publish-notifications endpointAddress="vm://myService" />

Log4J Agent

The log4j agent exposes the configuration of the Log4J instance used by Mule for JMX management. Youenable the Log4J agent using the <jmx-log4j> element. It does not take any additional properties.

For example:

<management:jmx-log4j/>

Log4J Notifications Agent

The Log4J notifications agent logs server notifications to a file or console using Log4J. You configure thisagent using the <log4j-notifications> element. It takes the same attributes as the JMX notificationsagent plus two additional attributes: logName, a name used to identify this log, and logConfigFile, thename of the file where you want to output the log messages.

The Log4J notifications agent also takes the <level-mapping> child element, which takes one or morepairs of severity/eventId attributes. The severity attribute specifies the severity level of the notificationsyou want to log for the corresponding event ID. The severity level can be DEBUG, INFO, WARN, ERROR,or FATAL. The eventId attribute specifies the type of event to log. The event ID is the notification typeplus the action, such as ModelNotification.stop.

For example:

<management:log4j-notifications logName="myMuleLog" logConfigFile="mule-log.txt"> <management:level-mapping eventId="ModelNotification.stop" severity="WARN"/> </management:log4j-notifications>

Chainsaw Notifications Agent

The Chainsaw notifications agent logs server notifications to a Chainsaw console. You configure this agentusing the <chainsaw-notifications> element. It takes the same attributes as the JMX notificationsagent plus two additional attributes: chainsawHost and {chainsawPort}}, which specify the host nameand port of the Chainsaw console.

Page 439: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 439

The Chainsaw notifications agent also takes the <level-mapping> child element, which takes one ormore pairs of severity/eventId attributes. The severity attribute specifies the severity level of thenotifications you want to send to the Chainsaw console for the corresponding event ID. The severitylevel can be DEBUG, INFO, WARN, ERROR, or FATAL. The eventId attribute specifies the type ofevent to send to the Chainsaw console. The event ID is the notification type plus the action, such asModelNotification.stop.

For example:

<management:chainsaw-notifications chainsawHost="localhost" chainsawPort="20202"> <management:level-mapping eventId="ModelNotification.stop" severity="WARN"/> </management:chainsaw-notifications>

MX4J Adapter

MX4J is an open source implementation of the JMX technology. The MX4J agent for Mule configures anMX4J HTTP adapter to provide JMX management, statistics, and configuration viewing of a Mule instance.You configure the MX4J agent using the <jmx-mx4j-adaptor> element.

Jmx Mx4j Adaptor

Attributes of <jmx-mx4j-adaptor...>

Name Type Required Default Description

jmxAdaptorUrl string no The URL ofthe JMX webconsole. Thedefault is http://localhost:9999.

login string no The login namefor accessing theJMX web console.

password string no The password foraccessing the JMXweb console.

authenticationMethodnone/basic/digest no basic The type ofauthenticationto perform whenthe login andpassword areset: basic (thedefault), digest, ornone.

cacheXsl string no true Indicates whetherto cache thetransformationobjects, whichspeeds-up theprocess. It isusually set totrue, but you can

Page 440: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 440

set it to false foreasier testing.

xslFilePath string no Specifies the pathof the XSL filesused to customizethe adaptor'sstylesheet. Ifyou specify adirectory, itassumes that XSLfiles are locatedin the directory.If you specifya .jar or .zip file, itassumes that thefiles are locatedinside. Specifyinga file system isespecially usefulfor testing.

pathInJar string no If the xslFilePathis a JAR file,specifies thedirectory in theJAR where theXSL files arelocated.

Child Elements of <jmx-mx4j-adaptor...>

Name Cardinality Description

socketFactoryProperties 0..1 A map containing propertiesfor SSL server socket factoryconfiguration. If this elementcontains at least one property,the agent will switch to HTTPSconnections. These propertieswill be delegated as is to theagent's HTTP/S adaptor. For alist of available properties, seethe MX4J API documentation.

For example:

<management:jmx-mx4j-adaptor jmxAdaptorUrl="https://myjmxserver.com:9999"> <management:socketFactoryProperties> <spring:entry key="keystore" value="/path/to/keystore" /> <spring:entry key="storepass" value="storepwd" /> </management:socketFactoryProperties></management:jmx-mx4j-adaptor>

For security's sake, the management console is accessible from the localhost only. To loosen thisrestriction, change "localhost" to "0.0.0.0", which allows access from any computer on the LAN. For moreinformation, see the MX4J documentation.

Page 441: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 441

MX4J Security

You can protect the JMX web console with a user name and password. If the login property has beenspecified, the authentication scheme is applied.

In addition to protecting the console, you can protect the in-transit data using SSL. If thesocketFactoryProperties element contains at least one property, the agent switches to HTTPSconnections. If this element is omitted from the configuration, the agent will always use HTTP, even if youspecify https:// in the jmxAdaptorUrl property.

Viewing Statistics

Mule traps many different statistics about the running state of a server and number of events processed.You can view the Mule statistics report in the JMX Management Console by pointing your browser tohttp://localhost:9999/ and then clicking on any JMX domain name (except for JMImplementation), or goto the Statistics tab and query the JMX domain for statistics from there.

YourKit Profiler

This agent exposes the YourKit profiler to JMX to provide CPU and memory profiling. To use this agent,you must configure the <yourkit-profiler> element as shown below, and you must install and run theProfiler as described in Profiling Mule.

Page 442: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 442

<management:yourkit-profiler />

Page 443: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 443

Mule Server Notifications

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

Mule Server Notifications

[ Configuring Notifications ] [ Firing Custom Notifications ] [ Notification Interfaces ] [ RegisteringListeners Programmatically ] [ Notification Payloads ]

Mule provides an internal notification mechanism that you can use to access changes that occur on theMule Server, such as a service component being added, a Mule Model being initialized, or Mule beingstarted. You can set up your agents or service components to react to these notifications.

Configuring Notifications

Message notifications provide a snapshot of all information sent into and out of the Mule Server. Thesenotifications are fired whenever a message is received or sent. These additional notifications have someimpact on performance, so they are disabled by default. To enable message notifications, you set the typeof messages you want to enable using the <notifications> element in your Mule configuration file. Youalso register the notification listeners and associate interfaces with specific notifications.

For example, first you create beans for the notification listeners, specifying the class of the type ofnotification you want to receive:

<spring:bean name="componentNotificationLogger" class="org.myfirm.ComponentMessageNotificationLogger"/><spring:bean name="endpointNotificationLogger"class="org.myfirm.EndpointMessageNotificationLogger"/>

Next, you specify the notifications you want to receive using the <notification> element, and thenregister the listeners using the <notification-listener> element:

<notifications> <notification event="COMPONENT-MESSAGE"/> <notification event="ENDPOINT-MESSAGE"/> <notification-listener ref="componentNotificationLogger"/> <notification-listener ref="endpointNotificationLogger"/></notifications>

When you specify the COMPONENT-MESSAGE notification, a notification is sent before and after acomponent is invoked. When you set ENDPOINT-MESSAGE, a notification is sent whenever a messageis sent, dispatched, or received on an endpoint. Because the listeners implement the interface for thetype of notification they want to receive (for example, the ComponentMessageNotificationLogger classwould implement org.mule.api.context.notification.ComponentMessageNotificationListener),the listeners receive the correct notifications.

For a list of notification types, see Notifications Configuration Reference. For a list of notification listenerinterfaces, see Notification Interfaces below.

Specifying a Different Interface

If you want to change the interface that is associated with a notification, you specify the new interfacewith the interface-class and interface attributes:

<notifications>

Page 444: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 444

<notification event="COMPONENT-MESSAGE" interface-class="org.myfirm.MyMessageNotifications" interface="myComponentListener"/>

Configuring a Custom Notification

If you create a custom notification, you also specify the event-class attribute:

<notifications> <notification event="CUSTOM-MESSAGE" event-class="org.myfirm.MyMessageNotificationsCustomMessage" interface-class="org.myfirm.MyMessageNotifications" interface="myCustomListener"/>...

Disabling Notifications

If you want to block a specific interface from receiving a notification, you specify it with the <disable-notification> element. You can specify the notification type (event), event class, interface, and/orinterface class to block.

<notifications> <disable-notification interface="ComponentMessageNotificationListener"/>...

Using Subscriptions

When registering a listener, you can specify that it only receive notifications from a specific componentusing the subscription attribute. For example, to specify that the listener only receive notifications froma service component called "MyService1", you would configure the listener as follows:

<notification-listener ref="endpointNotificationLogger" subscription="MyService1"/>

You can also register listeners and filter the subscriptions from your Java code:

MuleServer.getMuleContext().registerListener(listener, "MyService1");

To register interest in notifications from all service components with "Service" in the name, you would usea wildcard string as follows:

MuleServer.getMuleContext().registerListener(listener, "*Service*");

For more information, see Registering Listeners Programmatically below.

Firing Custom Notifications

Custom notifications can be fired by objects in Mule to notify custom listeners. For example, a discoveryagent might fire a Client Found notification when a client connects.

Page 445: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 445

You fire a custom notification as follows:

CustomNotification n = new CustomNotification("Hello");MuleServer.getMuleContext().fireNotification(n);

Any objects implementing CustomNotificationListener will receive this notification. It's a good idea toextend CustomNotification and define actions for your custom notification type. For example:

DiscoveryNotification n = new DiscoveryNotification(client, DiscoveryNotification.CLIENT_ADDED);MuleServer.getMuleContext().fireNotification(n);

Note that non-system objects in Mule can only fire custom notifications through the manager. Attemptingto fire other notifications such as ModelNotification will cause an UnsupportedOperationException.

Notification Interfaces

The following table describes the Mule server notifications and the interfaces in theorg.mule.api.context.notification class an object can implement to become a listener for that notification.All listeners extend the ServerNotificationListener interface.

Notification Description Interface

Component Message Notification A message was processed by aservice component.

ComponentMessageNotificationListener

Connection Notification A connector connected toits underlying resource orreleased the connection, or theconnection attempt failed.

ConnectionNotificationListener

Custom Notification Can be fired by objectsthemselves to customnotification listeners and can beused to customize notificationson agents, service components,connectors, and more.

CustomNotificationListener

Endpoint Message Notification A message was sent or receivedfrom an endpoint.

EndpointMessageNotificationListener

Exception Notification An exception was thrown. ExceptionNotificationListener

Management Notification The state of the Mule instance orits resources have changed.

ManagementNotificationListener

Message Notification An event was sent or received inthe system. These notificationsare very good for tracing, butthey are not enabled by defaultbecause they have an impact onperformance.

MessageNotificationListener

Model Notification The state is changing on amodel, such as initializing,starting and stopping, or

ModelNotificationListener

Page 446: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 446

service components within themodel are being registered orunregistered.

Mule Context Notification An event occurred on the MuleManager.

MuleContextNotificationListener

Registry Notification An event occurred on theregistry.

RegistryNotificationListener

Routing Notification A routing event such as anasync-reply miss occurred.

RoutingNotificationListener

Security Notification A request was denied securityaccess.

SecurityNotificationListener

Server Notification Fired when the server, models,and components stop, start, orinitialize.

ServerNotificationListener

Service Notification An event occurred on a service. ServiceNotificationListener

Transaction Notification During transaction life cycleafter a transaction has begun,was committed, or was rolledback.

TransactionNotificationListener

The listener interfaces all have a single method:

public void onNotification(ServerNotification notification);

Depending on the listener implemented, only certain notifications will be received. For example, if theobject implements ManagerNotificationListener, only notifications of type ManagerNotification willbe received. Objects can implement more than one listener to receive more types of notifications.

Registering Listeners Programmatically

You can register listeners on the Mule Context as follows:

MuleServer.getMuleContext().registerListener(listener);

If you have local access to the Mule context already (for example, if you created it right beforeregistering the listener), you would simply call registerListener() on the existing context instead of onMuleServer.getMuleContext(). For example:

MuleContext context = new DefaultMuleContextFactory().createMuleContext(new SpringXmlConfigurationBuilder("foo-config.xml"));context.registerListener(listener, "*Service*");

Registering Listeners Dynamically

By default, you cannot register listeners in the Mule context after Mule has started. Therefore, you wouldregister your listeners in your code before starting Mule. For example:

Page 447: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 447

MuleContext context = new DefaultMuleContextFactory().createMuleContext(new SpringXmlConfigurationBuilder("foo-config.xml"));context.registerListener(listener, "*Service*");context.start();

To change this behavior so that you can add listeners dynamically at run time, you can set the dynamicattribute on the <notifications> element. If you just want to enable dynamic notifications for a specificconnector, you can set the dynamicNotification attribute on the connector.

Notification Action Codes

Each notification has an action code that determines the notification type. The action code can be queriedin the onEvent method to determine its type. For example, to have an object do something when themodel initializes:

public class MyObject implements ModelNotificationListener{ public MyObject() { MuleServer.getMuleContext().registerListener(this); }

public void onNotification(ServerNotification notification) { if (notification.getAction() == ModelNotification.MODEL_INITIALISED) { system.out.println("The model is initialized!"); } }}

For a list of the action codes available with each notification type, see the Javadocs for theorg.mule.context.notification package and click on the class of the notification type you want.

Notification Payloads

All notifications extend java.util.EventObject, and the payload of the object can be accessed using thegetSource() method. The following table describes the payloads for each type of notification.

Notification Payload Type Resource ID Description

Component MessageNotification

Component Component name The service componentthat triggered thisnotification

Connection Notification Connectable <connector-name>.receiver(<endpoint-uri>)

The message receiveror message dispatcherthat was connected

Custom Notification Any object Any String The object type iscustom to the objectfiring the notification

Page 448: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 448

Endpoint MessageNotification

ImmutableEndpoint Endpoint URI The endpoint thattriggered thisnotification

Exception Notification Throwable Component Name The service componentthat triggered thisnotification

ManagementNotification

Object The object ID The monitored objectthat triggered thisnotification

Message Notification MuleMessage Message ID The message sent orreceived

Model Notification Model Model Name The Model instanceon the Mule Context.Equivalent to callingMuleContext.getRegistry().lookupModel()

Mule ContextNotification

MuleContext Mule context ID The Mule contextinstance. Equivalentto callinggetMuleContext().

Registry Notification Registry Mule registry ID The Mule registry.Equivalent to callingMuleContext.getRegistry().

Routing Notification MuleMessage Message ID The message sent orreceived

Security Notification SecurityException The exception message The security exceptionthat occurred

Service Notification Service Service ID The service thattriggered thisnotification

Transaction Notification Transaction Component name The componentthat triggered thisnotification

Page 449: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 449

Profiling Mule

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

Profiling Mule

[ Installing the Profiler Pack ] [ Enabling the Profiler Agent ] [ Running the Profiler ] [ Embedded Mule ]

The Mule Profiler Pack uses YourKit to provide CPU and memory profiling, helping you identify memoryleaks in your custom Mule extensions. The Profiler is useful during development and testing. In yourproduction environment, you should turn off the Profiler because of the high performance overhead. Youcan also use any other Profiler, such as JProfiler, by adding it as an agent in your configuration.

Installing the Profiler Pack

If you are installing Mule Enterprise Edition, simply select the Profiler check box when installing theproduct.

If you are installing Mule Community Edition, go to the downloads page, and under the latest stablecommunity release, expand the Downloads section. You can then click the link to the .zip, .tar, or .gzversion of the Profiler pack. After downloading, unpack it on top of the Mule installation.

Enabling the Profiler Agent

The Profiler agent exposes the YourKit Profiler to JMX to provide CPU and memory profiling. You configurethe Profiler agent with the <management:yourkit-profiler> element. For more information, see JmxManagement.

Running the Profiler

To run the profiler, you run Mule with the -profile switch plus any extra YourKit startup options withmultiple parameters separated by commas, e.g. -profile onlylocal,onexit=memory. This integrationpack will automatically take care of configuration differences for Java 1.4.x and 5.x/6.x.

Embedded Mule

If you are running Mule embedded in a webapp, the Profiler configuration is completely delegated tothe owning container. Launch YourKit Profiler, Tools -> Integrate with J2EE server... and follow theinstructions. Typically, a server's launch script is modified to support profiling, and you then use thismodified start script instead of the original.

Page 450: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 450

Resource Adapter

This page last changed on Nov 12, 2008 by jackie.wheeler.

Mule JCA Resource Adapter

The Mule JCA resource adapter enables a Mule instance to be deployed to a J2EE application server. It canbe deployed to any JCA 1.5 compliant container. See Deployment Scenarios for links to information aboutspecific application server configurations.

You can download the resource adapter here.

EJB Configuration

The resource adapter supports inbound and outbound communication.

Outbound Bean Configuration

<session> <description>A stateless session bean that sends a message over a Mule transport </description> <display-name>SenderEJB</display-name> <ejb-name>SenderEJB</ejb-name> <home>org.mule.samples.ejb.SenderHome</home> <remote>org.mule.samples.ejb.Sender</remote> <ejb-class>org.mule.samples.ejb.SenderBean</ejb-class> <session-type>Stateless</session-type> <transaction-type>Container</transaction-type> <resource-ref> <res-ref-name>mule/connectionFactory</res-ref-name> <res-type>org.mule.module.jca.MuleConnectionFactory</res-type> <res-auth>Container</res-auth> <res-sharing-scope>Unshareable</res-sharing-scope> </resource-ref></session>

Inbound Configuration

The endpoint property must be a valid endpoint URI to receive Mule events.

<message-driven> <description>An MDB listening on a Tcp socket</description> <display-name>TcpReceiverMDB</display-name> <ejb-name>TcpReceiverMDB</ejb-name> <ejb-class>org.mule.samples.ejb.SimpleReceiverMessageBean</ejb-class> <messaging-type>org.mule.api.lifecycle.Callable</messaging-type> <transaction-type>Container</transaction-type> <activation-config> <activation-config-property> <activation-config-property-name>endpoint</activation-config-property-name> <activation-config-property-value>tcp://localhost:12345 </activation-config-property-value> </activation-config-property> </activation-config></message-driven>

Page 451: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 451

Suggested Reading

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

Suggested Reading

ESB

ESB Introduction Part 1This first article in this series described the basic concepts and role of the Enterprise Service Bus (ESB). Itfocuses on describing scenarios and issues for ESB deployment to support a Service-Oriented Architecture(SOA). One or more of these scenarios might apply to the SOA and ESB needs of your organization. - byRick Robinson

ESB Introduction Part 2In Part 2 of this series on the Enterprise Service Bus (EBS), the author describes and analyzes somecommonly observed scenarios in which ESBs and other Service-Oriented Architecture (SOA) solutions areimplemented. - by Rick Robinson

ESB Introduction Part 3In the third installment of this series, the author examines possible solutions for the various scenariosoutlined in Part 2. The ideas on the role of the Bus as explained in Part 1 provide the foundation for thescenarios. - by Rick Robinson

The ESB Learning Guide - everything you want to know about ESB is here.

Enterprise Integration

Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions - by GregorHohpe, Bobby WoolfProvides a consistent vocabulary and visual notation framework to describe large-scale integrationsolutions across many technologies. It also explores in detail the advantages and limitations ofasynchronous messaging architectures.

SEDA

SEDASEDA is an acronym for staged event-driven architecture, and decomposes a complex, event-drivenapplication into a set of stages connected by queues. This design avoids the high overhead associatedwith thread-based concurrency models, and decouples event and thread scheduling from applicationlogic. Mule uses ideas from SEDA to provide a highly scalable server.

An Architecture for Highly Concurrent,Well-Conditioned Internet Services - (PDF) Dissertation by MattWelsh that introduces SEDA

JBI

The Sun JBI Site

Concurrency

Java Concurrency in Practice by Brian Goetz

Concurrent Programming in Java: Design Principles and Patterns by Doug Lea

Open Source Development Process

Producing Open Source Software: How to Run a Successful Free Software Project by Karl Fogel

Page 452: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 452

The Cathedral and the Bazaar by Eric Raymond

Quality Improvement in Volunteer Free and Open Source Software Projects: Exploring the Impact ofRelease Management by Martin Michlmayr

Open Source Java

The Server Side

Page 453: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 453

Third-party Software in Mule

This page last changed on Mar 25, 2009 by jwheeler.

Third-party Software

Mule products include the following third-party software as part of the source code, examples, or asdependencies. The license type for each third-party software product is indicated in parentheses.

Software License

Acegi Apache 2.0

Antlr BSD Style

Apache Axis Apache 2.0

Apache Axis Jaxrpc Apache2.0

Apache Catalina Apache 2.0

Apache CocoonProject

Apache 2.0

Apache CommonsAttributes

Apache 2.0

Apache CommonsBeanutils

Apache 2.0

Apache CommonsCodec

Apache 2.0

Apache CommonsCollections

Apache 2.0

Apache CommonsDBUtils

Apache 2.0

Apache CommonsDigester

Apache 2.0

Apache CommonsDiscovery

Apache 2.0

Apache Commons-lang

Apache 2.0

Apache Commons-logging

Apache 2.0

Apache Commons IO Apache 2.0

Apache Commons Net Apache 2.0

Apache Derby Apache 2.0

Software License

Graphviz CPL 1.0

GreenMail LGPL 2.1

Groovy Apache 2.0

Hibernate LGPL 2.1

Hivemind Apache 2.0

Howl-logger BSD

Http-Client Apache 2.0

iHarder Base64 Public Domain/Permissive

IzPack Apache 2.0

Jakarta Oro Apache 1.1

Java Scripting API Sun BCLA

Java Service Wrapper Tanuki Software/SilverEgg Technology

Java UUID Generator Apache 2.0

Javaassist MPL 1.1

JavaDoc forJNDI ContainerImplementation

BSD Style

Jaxen BSD style

JBoss BusinessProcess Management– JBPM

LGPL 2.1

JBoss Transactions LGPL 2.1

JDOM BSD style license

Jetty 6.1.11 Apache 1.1

Page 454: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 454

Apache FtpServer Apache 2.0

Apache Geronimo Apache 2.0

Apache JakartaCommons TransactionSource

Apache 2.0

Apache Maven Apache 2.0

Apache Tomcat Utility Apache 2.0

Apache Xalan Apache 2.0

Apache XML Security Apache 2.0

Apache Velocity Apache 2.0

Apache WebServicesCommons

Apache 2.0

Apache Web ServicesAxis

Apache 2.0

Apache Web ServicesProject (Wss4j)

Apache 2.0

Apache Xerces Apache 2.

Apache XMLCommons XML APIs

Apache 2.0

Apache Xpath Apache 2.0

ASM – Bundled withCGLIB

BSD

Axis-Saaj Project Apache 2.0

Axis/Web Services Apache 2.0

Backport-util-concurrent

Creative CommonsPublic Domain

Bouncy Castle JavaCryptography APIs

Bouncy Castle License

c3p0: JDBCDataSources/ResourcePools

LGPL 2.1

CAROL: CommonArchitecture forObjectWeb

LGPL 2.1

Commons-cli Apache 1.1

Cryptix OpenPGP Cryptix GeneralLicense

Commons-pool Apache 2.0

JPEG Library (bundledwith GraphViz)

IJG/JPEG Permissivelicense

JUnit CPL 1.0

Libpng (bundled withGraphViz)

Libpng OSI license

Linguine Maps LGPL 2.1

Log4j Apache 2.0

Mockobjects Apache 2.0

Mx4j MX4J License 1.0

Mx4j-tools MX4J License 1.0

Nanocontainer BSD Style

OGNL Attribution

OpenSAML Apache 1.1

Picocontainer BSD

Quartz Apache 2.0

Retrotranslator BSD style

Simple LoggingFacade for Java(SLF4J)

MIT Style

Smack Apache 2.0

Spring Framework /Modules JBPM

Apache 2.0

StaX Apache 2.0

Sun JNDI Sun BCLA

TrueType FontLibrary (bundled withGraphViz)

GPL/LGPL

Truststore files Unknown

Web ServicesDescription Languagefor Java (wsdl4j)

CPL 1.0

Woodstox Apache 2.0

xapool LGPL 2.1

XMLUnit BSD style

XPP3

Page 455: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 455

CGLIB Apache 2.0

Cryptix Cryptix GeneralLicense

Dom4j BSD

DTDParser referencedby Linguine Maps

Apache Style

Expat Parser MIT

FreeType Project,bundled with GraphViz

FreeType License

Indiana UniversityExtreme! LabSoftware License

XStream BSD

YourKit Java Profiler Commercial

ZLIB (bundled withGraphViz)

Zlib license

Page 456: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 456

Transaction Management

This page last changed on Mar 24, 2009 by jwheeler.

Transaction Management

[ Single-resource (Local) Transactions ] [ Multi-resource Transactions ] [ XA Transactions ] [Transaction Manager Lookup ] [ Transaction Coordination ]

Mule's transaction framework is agnostic to the underlying transaction manager. The transactioncould be a JDBC transaction, XA transaction, or a JMS transaction or message acknowledgment. Alltransaction types can be handled the same way. Mule transactions are configured on synchronousendpoints, where an endpoint can be configured to start a new transaction or join an existingone. Transactions are configured on an endpoint using <transaction>, which maps to theorg.mule.transaction.MuleTransactionConfig class. This element defines what action an endpoint shouldtake when it receives an event and the transaction factory to use to create transactions.

If you have multiple inbound or outbound endpoints in a service and you specify atransaction for one of them, you must specify transactions for all of them. For example, ifyou have two outbound endpoints and you specify a transaction for the first one, you mustalso specify a transaction for the second one.

For an excellent article on distributed transactions using both XA and non-XA approaches, see http://www.javaworld.com/javaworld/jw-01-2009/jw-01-spring-transactions.html. The multi-resourcetransaction support described below maps to the Best Efforts 1PC pattern described in the article.

For more details on the elements you configure for transactions, see Transactions ConfigurationReference.

Single-resource (Local) Transactions

Single-resource transactions (also called "local transactions") are transactions that are provided by theunderlying resource, such as JDBC transactions and JMS transactions. These kind of transactions can beused to receive and/or send messages using a single resource only.

An example configuration for a single-resource transaction might look like this:

<jms:endpoint name="In" queue="test.In" connector-ref="jmsConnector1" /><jms:endpoint name="Out" queue="test.Out" connector-ref="jmsConnector1" />...<inbound> <inbound-endpoint ref="In"> <jms:transaction action="ALWAYS_BEGIN" /></inbound>...<outbound> <outbound-pass-through-router> <outbound-endpoint ref="Out"> <jms:transaction action="ALWAYS_BEGIN" /> </outbound-endpoint> </outbound-pass-through-router></outbound>

This configuration defines a global JMS endpoint that receives on a "test.In" queue and another globalJMS endpoint that sends on a "test.Out" queue. The action attribute tells Mule what to do for eachmessage. In this case, a new transaction will be created for every message received. The outboundendpoint will use the resource enlisted in the current transaction, if one is running. In this case, it will use

Page 457: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 457

the same JMS session that has been used to receive the event. When the message has been routed fromthe inbound endpoint to the outbound endpoint, the transaction will be committed or rolled back.

You can send multiple messages using the recipient list router, which will send all messages in the sametransaction.

You can set action values on the <transaction> element as follows:

• NONE - Never participate in a transaction.• ALWAYS_BEGIN - Always start a new transaction when receiving a message. If a previous

transaction exists, it commits that transaction.• BEGIN_OR_JOIN - If a transaction is already in progress when an event is received, join the

transaction, otherwise start a new transaction.• ALWAYS_JOIN - Always expects a transaction to be in progress when an event is received. If there is

no transaction, an exception is thrown.• JOIN_IF_POSSIBLE - Will join the current transaction if one is available. Otherwise, no transaction is

created.

Multi-resource Transactions

As of version 2.2, if you are using Mule Enterprise Edition, you can use the <multi-transaction>element to enable a series of operations from multiple JMS resources to be grouped into a singletransaction. Multi-resource transactions work without the overhead of XA. The trade-off is that XAreliability guarantees aren't provided, and your services must be ready to handle duplicates. This is verysimilar to a 1.5 phase commit concept.

Multi-resource transactions are useful for creating transactional non-XA bridges. For example, if youwant to bridge two different JMS connectors, each of which is running local transactions instead of XAtransactions, you could configure the multi-resource transaction as follows:

<?xml version="1.0" encoding="UTF-8"?><mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jms="http://www.mulesource.org/schema/mule/jms/2.2" xmlns:wmq="http://www.mulesource.org/schema/mule/ee/wmq/2.2" xmlns:ee="http://www.mulesource.org/schema/mule/ee/core/2.2" xmlns:test="http://www.mulesource.org/schema/mule/test/2.2" xsi:schemaLocation=" http://www.mulesource.org/schema/mule/test/2.2 http://www.mulesource.org/schema/mule/test/2.2/mule-test.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/ee/core/2.2 http://www.mulesource.org/schema/mule/ee/core/2.2/mule-ee.xsd http://www.mulesource.org/schema/mule/jms/2.2 http://www.mulesource.org/schema/mule/jms/2.2/mule-jms.xsd http://www.mulesource.org/schema/mule/ee/wmq/2.2 http://www.mulesource.org/schema/mule/ee/wmq/2.2/mule-wmq-ee.xsd>

<jms:activemq-connector name="jmsConnector" maxRedelivery="3" disableTemporaryReplyToDestinations="true"/>

<wmq:connector name="wmqConnector" hostName="winter" port="1414" disableReplyToHandler="true" disableTemporaryReplyToDestinations="true" queueManager="MY_QUEUE_MANAGER" targetClient="NONJMS_MQ" transportType="CLIENT_MQ_TCPIP" specification="1.1" numberOfConsumers="16"

Page 458: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 458

username="" password=""/>

<model name="Multi-TX Test Model"> <service name="TestService1\"> <inbound> <jms:inbound-endpoint queue="in"> <ee:multi-transaction action="ALWAYS_BEGIN"/> </jms:inbound-endpoint> </inbound> <test:component/> <outbound> <pass-through-router enableCorrelation="NEVER"> <wmq:outbound-endpoint queue="out"> <ee:multi-transaction action="ALWAYS_JOIN"/> </wmq:outbound-endpoint> </pass-through-router> </outbound> </service> </model></mule>

Because the inbound JMS endpoint has a multi-resource transaction configured on it, any outboundendpoints must also be configured with multi-resource transaction support to become part of thetransaction.

XA Transactions

You can use XA transactions if you want to enlist multiple managed resources within the same transactionand require 100% reliability. The inbound endpoints are configured in the same manner as for single-resource transactions, but the connectors need to be configured to use XA-enabled resources.

If you run Mule outside an application server, you can use JBoss Transaction Manager to configure anembedded transaction manager.

Currently, only the following transports support XA transactions:

• VM Transport• JDBC Transport• JMS Transport• Mule WMQ Transport (as of Mule Enterprise Edition 2.2)

The following example of an XA transaction configuration uses a single transaction to read from a JMSqueue and write to a database.

<service name="JmsToJdbc"> <inbound> <inbound-router> <jms:inbound-endpoint queue="my.queue" reuseSession="false"/> <xa-transaction action="ALWAYS_BEGIN" timeout="60000"/> </jms:inbound-endpoint> </inbound-router> </inbound> <outbound> <outbound-pass-through-router> <jdbc:outbound-endpoint address="writeTest" type="2"> <xa-transaction action="ALWAYS_JOIN"/> </jdbc:outbound-endpoint> </outbound-pass-through-router> </outbound>

Page 459: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 459

</service>

Because the inbound JMS endpoint has an XA transaction configured on it, any outbound endpoints mustalso be configured with XA transaction support to become part of the XA transaction. This requires thatthe transport type supports XA transactions. For this configuration to work, you will need to configure aJMS connector that uses a JMS XA Connection Factory and a JDBC connector that is configured to use anXA data source.

Setting the Polling Frequency

When you configure an inbound JMS endpoint with XA transactions, the receiver polls every 100 ms. Youcan change the polling frequency by setting the pollingFrequency property as follows:

<jms:inbound-endpoint queue="my.queue" reuseSession="false"> <xa-transaction action="ALWAYS_BEGIN" timeout="60000"/> <properties> <spring:entry key="pollingFrequency" value="5000"/> </properties></jms:inbound-endpoint>

This property is only applicable if you are using the XaTransactedJmsMessageReceiver , which is thedefault receiver on inbound JMS endpoints that use XA transactions.

Transaction Manager Lookup

Mule uses javax.transaction.TransactionManager for managing transaction spanning multipleresources (XA). If you need the SUSPEND semantics for your transactions (which is what EJB'sRequiresNew transaction attribute value does), you must use the transaction manager. Conversely,the more typical javax.transaction.UserTransaction is just a thin handle to a transaction managerwith limited (though in most cases sufficient) functionality that does not let you suspend the currenttransaction.

Note: Depending on your application server vendor, the transaction manager might be available via JNDIor only through proprietary APIs.

The following table summarizes some common Java EE servers:

ApplicationServer

Remote Embedded CommonLocation

Lookup class

JBoss java:/TransactionManager

org.mule.transaction.lookup.JBossTransactionManagerLookupFactory

Weblogic javax.transaction.TransactionManagerorg.mule.transaction.lookup.WeblogicTransactionManagerLookupFactory

WebSphere Proprietary APIcall

org.mule.transaction.lookup.WebsphereTransactionManagerLookupFactory

Resin java:comp/TransactionManager

org.mule.transaction.lookup.Resin3TransactionManagerLookupFactory

JRun java:/TransactionManager

org.mule.transaction.lookup.JRunTransactionManagerLookupFactory

Other Specified via ajndiName property

org.mule.transaction.lookup.GenericTransactionManagerLookupFactory

Page 460: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 460

For example, to use Weblogic's transaction manager, you would configure Mule as follows:

<transaction-manager factory="org.mule.transaction.lookup.WeblogicTransactionManagerLookupFactory" />

Transaction Coordination

Transaction demarcation is set on endpoints. The actual management of transactions is handled by theMule Transaction Coordinator . 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 providesmethods for binding and unbinding transaction and retrieving the current transaction state.

Page 461: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 461

Tuning Performance

This page last changed on Nov 11, 2008 by jackie.wheeler.

Tuning Performance

[ About Thread Pools ] [ About Threading Profiles ] [ About Pooling Profiles ] [ Calculating Threads ] [Additional Performance Tuning Tips ] [ Threading Profile Configuration Reference ] [ Receiver ThreadingProfile ] [ Dispatcher Threading Profile ] [ Pooling Profile Configuration Reference ] [ Pooling Profile ]

A Mule application is a collaboration of a set of services. Messages are processed by services in threestages:

1. Connector receiving stage2. Service component processing stage3. Connector dispatching stage

Tuning performance in Mule involves analyzing and improving these three stages for each service. Youcan start by applying the same tuning approach to all services and then further customize the tuning foreach service as needed.

About Thread Pools

Each request that comes into Mule is processed on its own thread. A connector's receiver has a threadpool with a certain number of threads available to process requests on the inbound endpoints that usethat connector.

Keep in mind that Mule can send messages asynchronously or synchronously. By default, messages areasynchronous, which is the "fire-and-forget" style where a message is sent with no response. If you needa response back, you must configure the Mule service as synchronous. When a service is configured asasynchronous, a connector receiver and dispatcher are used, whereas a synchronous service uses onlythe connector receiver.

If you are using synchronous processing, the same thread will be used to carry the message all the waythrough Mule, whereas if you are doing asynchronous processing, the receiver thread is used only tocarry the message to the component, at which point the message is transferred to a component thread,and the receiver thread is released back into the receiver thread pool so it can carry another message.The following diagram illustrates these threads.

Page 462: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 462

After the component has finished processing an asynchronous message, it is transferred to a dispatcherthread and is sent on its way. Therefore, the receiver, component, and dispatcher all have separatethread pools that are in use during asynchronous processing, whereas only the receiver thread pool is inuse for synchronous processing.

About Threading Profiles

The threading profile specifies how the thread pools behave in Mule. You specify a separate threadingprofile for each receiver thread pool, component thread pool, and dispatcher thread pool. The mostimportant setting of each is maxThreadsActive, which specifies how many threads are in the thread pool.

About Pooling Profiles

Unlike singleton components, pooled components (see PooledJavaComponent ) each have a componentpool, which contains multiple instances of the component to handle simultaneous incoming requests.A service's pooling profile configures its component pool. The most important setting is maxActive,which specifies the maximum number of instances of the component that Mule will create to handlesimultaneous requests. Note that this number should be the same as the maxThreadsActive setting onthe receiver thread pool, so that you have enough component instances available to handle the threads.You can use Mule HQ to monitor your component pools and see the maximum number of componentsyou've used from the pool to help you tune the number of components and threads.

Calculating Threads

To calculate the number of threads to set, you must take the following factors into consideration.

• Concurrent User Requests: In general, the number of concurrent user requests is the totalnumber of requests to be processed simultaneously at any given time by the Mule server. For aservice, concurrent user requests is the number of requests a service inbound endpoint can processsimultaneously. Concurrent user requests at the connector level is the total concurrent requests ofall services that share the same connector. Typically, you get the total concurrent user requests fromthe business requirements.

• Processing Time: Processing time is the average time Mule takes to process a user request fromthe time a connector receiver starts the execution until it finishes and then sends the response tothe outbound endpoint by connector dispatcher or back to the caller by the connector receiver aftera round trip. Typically, you determine the processing time from the unit tests.

• Response Time: If a service runs in synchronous mode, the response time is the actual amountof time the end user is required to wait for the response to come back. If the service runs inasynchronous mode, it is the total time from when a request arrives in Mule until it is dispatchedout of the service by the outbound dispatcher. In a thread pooling environment, when a requestarrives, there is no guarantee that a thread will be immediately available. In this case, the requestis put into an internal thread pool work queue to wait for the next available thread. Therefore, theresponse time is a function of the following:Response time = average of thread pool waiting time in work queue + average of processing timeYour business requirements will dictate the actual response time required from the application.

• Timeout Time: If your business requirements dictate a maximum time to wait for a responsebefore timing out, it will be an important factor in your calculations below.

After you have determined these requirements, you can calculate the adjustments you need to maketo maxThreadsActive and maxBufferSize for the service and the receiver thread pool. In general, theformula is:

Concurrent user requests = maxThreadsActive + maxBufferSize

Where maxThreadsActive is the number of threads that run concurrently and maxBufferSize is thenumber of requests that can wait in the queue for threads to be released.

Page 463: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 463

Calculating the Service Threads

Your business requirements dictate how many threads each service must be able to process concurrently.For example, one service might need to be able to process 50 requests at a time, while another mightneed to process 40 at a time. Typically, you use this requirement to set the maxThreadsActive attributeon the service (maxThreadsActive="40").

If you have requirements for timeout settings for synchronous processing, you must do some additionalcalculations for each service.

1. Run synchronous test cases to determine the response time.2. Subtract the response time from the timeout time dictated by your business requirements. This is

your maximum wait time (maximum wait time = timeout time - response time).3. Divide the maximum wait time by the response time to get the number of batches that will be

run sequentially to complete all concurrent requests within the maximum wait time (batches =maximum wait time / response time). Requests wait in the queue until the first batch is finished,and then the first batch's threads are released and used by the next batch.

4. Divide the concurrent user requests by the number of batches to get the thread size for the service'smaxThreadsActive setting (where maxThreadsActive = concurrent user requests / processingbatches). This is the total number of threads that can be run simultaneously for this service.

5. Set maxBufferSize to the concurrent user requests minus the maxThreadsActive setting (wheremaxBufferSize = concurrent user requests - maxThreadsActive). This is the number of requeststhat can wait in the queue for threads to become available.

For example, assume a service must have the ability to process 200 concurrent user requests, yourtimeout setting is 10 seconds, and the response time is 2 seconds, making your maximum wait time8 seconds (10 seconds timeout minus 2 seconds response time). Divide the maximum wait time(8 seconds) by the response time (2 seconds) to get the number of batches (4). Finally, divide theconcurrent user requests requirement (200 requests) by the batches (4) to get the maxThreadsActivesetting (50) for the service. Subtract this number (50) from the concurrent user requests (200) to getyour maxBufferSize (150).

In summary, the formulas for synchronous processing with timeout restrictions are:

• Maximum wait time = timeout time - response time• Batches = maximum wait time / response time• maxThreadsActive = concurrent user requests / batches• maxBufferSize = concurrent user requests - maxThreadsActive

Calculating the Receiver Threads

A connector's receiver is shared by all services that specify the same connector on their inboundendpoint. The previous section described how to calculate the maxThreadsActive attribute for eachservice. To calculate the maxThreadsActive setting for the receiver, that is, how many threads you shouldassign to a connector's receiver thread pool, sum the maxThreadsActive setting for each service thatuses that connector on their inbound endpoints:

maxThreadsActive = # (service 1 maxThreadsActive, service 2 maxThreadsActive...service nmaxThreadsActive)

For example, if you have three components whose inbound endpoints use the VM connector, and yourbusiness requirements dictate that two of the services should handle 50 50 requests at a time and thethird service should handle 40 requests at a time, set maxThreadsActive to 140 in the receiver threadingprofile for the VM connector.

Calculating the Component Threads and Instances

In the component stage, the transformed message from the inbound endpoint is passed to thecomponent thread. As you can see from the previous illustration, there are two pools involved here:a component thread is taken from component's thread pool, and a POJO instance is taken from thecomponent object pool (if the component is configured as a pooled component instead of a singleton).Therefore, the number of component threads must match the number of component instances in thecomponent pool. Otherwise, a bottle neck on either side will develop.

Page 464: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 464

If most of your components use asychronous processing, typically use the same number of componentthreads as you set for the receiver threads. If most of your components do synchronous processing,however, component threads won't be used as often, so this number can be much lower.

Like the receiver thread pool, the component thread pool can be shared if multiple services use the samecomponent. In this case, use the following formula:

Component threads = # (service 1 + service 2 + ...+ service n)

Calculating the Dispatcher Threads

Like component threads, dispatcher threads are used only for asynchronous processing. Typically, set thedispatcher threads to the same number as the component threads.

Other Considerations

You can trade off queue sizes and maximum pool sizes. Using large queues and small pools minimizesCPU usage, OS resources, and context-switching overhead, but it can lead to artificially low throughput.If tasks frequently block (for example, if they are I/O bound), a system may be able to schedule timefor more threads than you otherwise allow. Use of small queues generally requires larger pool sizes,which keeps CPUs busier but may encounter unacceptable scheduling overhead, which also decreasesthroughput.

Additional Performance Tuning Tips

• In the log4j.properties file in your conf directory, set up logging to a file instead of the console,which will bypass the wrapper logging and speed up performance. To do this, create a new fileappender (org.apache.log4j.FileAppender), specify the file and optionally the layout and othersettings, and then change "console" to the file appender. For example:

log4j.rootCategory=INFO, mulelogfile

log4j.appender.mulelogfile=org.apache.log4j.FileAppenderlog4j.appender.mulelogfile.layout=org.apache.log4j.PatternLayoutlog4j.appender.mulelogfile.layout.ConversionPattern=%-22d{dd/MMM/yyyy HH:mm:ss} - %m%nlog4j.appender.mulelogfile.file=custommule.log

• If polling is enabled for a connector, one thread will be in use by polling, so you should incrementyour maxThreadsActive setting by one. Polling is available on connectors such as File, FTP, andSTDIO that extend AbstractPollingMessageReceiver .

• If you are using VM to pass a message between components, you can typically reduce the totalnumber of threads because VM is so fast.

• If you are processing very heavy loads, or if your endpoints have different simultaneous requestrequirements (for example, one endpoint requires the ability to process 20 simultaneous requestsbut another endpoint using the same connector requires 50), you might want to split up theconnector so that you have one connector per endpoint.

Thread pools in Mule use the JDK 1.4-compatible util.concurrent backport library, so allthe variables defined on org.mule.config.ThreadingProfile are synonymous withThreadPoolExecutor.

Threading Profile Configuration Reference

Following are the elements you configure for threading profiles. You can create a threading profile at the<configuration>, <connector>, or <service> level and reference it.

Page 465: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 465

Receiver Threading Profile

The threading profile to use when a connector receives messages.

Attributes of <receiver-threading-profile...>

Name Type Required Default Description

maxThreadsActive integer no The maximumnumber of threadsthat will be used.

maxThreadsIdle integer no The maximumnumber of idle orinactive threadsthat can be in thepool before theyare destroyed.

threadTTL integer no Determines howlong an inactivethread is kept inthe pool beforebeing discarded.

poolExhaustedAction WAIT/DISCARD/DISCARD_OLDEST/ABORT/RUN

no When themaximum poolsize or queue sizeis bounded, thisvalue determineshow to handleincoming tasks.Possible valuesare: WAIT(wait until athread becomesavailable; don'tuse this valueif the minimumnumber of threadsis zero, in whichcase a threadmay neverbecome available),DISCARD(throw away thecurrent requestand return),DISCARD_OLDEST(throw away theoldest requestand return),ABORT (throw aRuntimeException),and RUN (thedefault; thethread making theexecute requestruns the taskitself, which helps

Page 466: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 466

guard againstlockup).

threadWaitTimeout integer no How long to waitin millisecondswhen the poolexhaustedaction is WAIT.If the value isnegative, it willwait indefinitely.

doThreading boolean no true Whether threadingshould be used(default is true).

maxBufferSize integer no Determines howmany requestsare queued whenthe pool is atmaximum usagecapacity and thepool exhaustedaction is WAIT.The buffer is usedas an overflow.

Dispatcher Threading Profile

The threading profile to use when a connector dispatches messages.

Attributes of <dispatcher-threading-profile...>

Name Type Required Default Description

maxThreadsActive integer no The maximumnumber of threadsthat will be used.

maxThreadsIdle integer no The maximumnumber of idle orinactive threadsthat can be in thepool before theyare destroyed.

threadTTL integer no Determines howlong an inactivethread is kept inthe pool beforebeing discarded.

poolExhaustedAction WAIT/DISCARD/DISCARD_OLDEST/ABORT/RUN

no When themaximum poolsize or queue sizeis bounded, thisvalue determineshow to handleincoming tasks.Possible valuesare: WAIT

Page 467: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 467

(wait until athread becomesavailable; don'tuse this valueif the minimumnumber of threadsis zero, in whichcase a threadmay neverbecome available),DISCARD(throw away thecurrent requestand return),DISCARD_OLDEST(throw away theoldest requestand return),ABORT (throw aRuntimeException),and RUN (thedefault; thethread making theexecute requestruns the taskitself, which helpsguard againstlockup).

threadWaitTimeout integer no How long to waitin millisecondswhen the poolexhaustedaction is WAIT.If the value isnegative, it willwait indefinitely.

doThreading boolean no true Whether threadingshould be used(default is true).

maxBufferSize integer no Determines howmany requestsare queued whenthe pool is atmaximum usagecapacity and thepool exhaustedaction is WAIT.The buffer is usedas an overflow.

Pooling Profile Configuration Reference

Each service has its own pooling profile. You configure the pooling profile using the <pooling-profile>element on the <pooled-component> element.

Page 468: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 468

Pooling Profile

Attributes of <pooling-profile...>

Name Type Required Default Description

maxActive string no Controls themaximumnumber of Mulecomponents thatcan be borrowedfrom a sessionat one time.When set to anegative value,there is no limitto the number ofcomponents thatmay be active atone time. WhenmaxActive isexceeded, thepool is said to beexhausted.

maxIdle string no Controls themaximumnumber of Mulecomponents thatcan sit idle in thepool at any time.When set to anegative value,there is no limitto the number ofMule componentsthat may be idleat one time.

initialisationPolicy INITIALISE_NONE/INITIALISE_ONE/INITIALISE_ALL

no INITIALISE_ONE Determines howcomponents ina pool shouldbe initialized.The possiblevalues are:INITIALISE_NONE(will not loadany componentsinto the poolon startup),INITIALISE_ONE(will load oneinitial componentinto the poolon startup), orINITIALISE_ALL(will load allcomponents in thepool on startup)

Page 469: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 469

exhaustedAction WHEN_EXHAUSTED_GROW/WHEN_EXHAUSTED_WAIT/WHEN_EXHAUSTED_FAIL

no WHEN_EXHAUSTED_GROWSpecifies thebehavior of theMule componentpool when thepool is exhausted.Possiblevalues are:"WHEN_EXHAUSTED_FAIL",which will throw aNoSuchElementException,"WHEN_EXHAUSTED_WAIT",which will blockby invokingObject.wait(long)until a new oridle object isavailable, orWHEN_EXHAUSTED_GROW,which will create anew Mule instanceand returnit, essentiallymaking maxActivemeaningless. If apositive maxWaitvalue is supplied,it will block for atmost that manymilliseconds,after which aNoSuchElementExceptionwill be thrown. IfmaxThreadWaitis a negativevalue, it will blockindefinitely.

maxWait string no Specifies thenumber ofmilliseconds towait for a pooledcomponent tobecome availablewhen the pool isexhausted and theexhaustedActionis set toWHEN_EXHAUSTED_BLOCK.

Page 470: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 470

Unit Testing

This page last changed on Jan 07, 2009 by kevin.depew.

Unit Testing

Mule provides a Test Compatibility Kit (TCK) of unit tests that you can use to test your simpleextensions as well as your custom modules and transports. The unit tests are located in the -tests.jar file, such as mule-core-2.0.2-tests.jar for Mule version 2.0.2. All unit tests inherit fromorg.mule.tck.AbstractMuleTestCase

These unit tests are beneficial for the following reasons:

• Components tested with a TCK test case ensure that the common behavior of the component iscompatible with the Mule framework.

• Using a TCK test case allows the developer to concentrate on writing tests for specific behavior oftheir component.

• Where testing of a method in the Service Component API cannot be tested by the TCK test case,the test cases provides an abstract method for the test, ensuring the developer tests all areas of thecomponent.

• The TCK provides a default test model that is a simple set of test classes. The developer doesn'tneed to worry about writing new test classes for their test cases each time.

• The abstract test cases in the TCK use JUnit's TestCase, so they are compatible with other testcases.

Following is a description of some of the unit tests in the Mule TCK:

Testing Component Description

AbstractMuleTestCase A helper test case providing methods for creatingtest and mock object types. This is the base classfor all other abstract TCK classes.

AbstractConnectorTestCase Used to test the common behavior of a connector.This tests dispatching and sending events usingmock objects.

AbstractMessageAdapterTestCase Provides tests for all the standard methodsdefined in the MessageAdapter interface. It'susually enough to just extend this test casewithout writing any further tests.

AbstractMessageReceiverTestCase Used to test the common behavior of aMessageReceiver. This tests receiving messagesusing mock objects.

AbstractComponentTestCase This is the base class for unit tests thattest custom component implementations.Concrete subclasses of this base classinclude DefaultJavaComponentTestCase,PooledJavaComponentTestCase, andSimpleCallableJavaComponentTestCase,each of which contains methods for testingthat component type. For example, theDefaultJavaComponentTestCase includesmethods for testing the creation, lifecycle, anddisposal of a basic Java component.

AbstractTransformerTestCase Used to test transformers. This class definesa number of tests that ensures that thetransformer works in single scenarios as wellas in round trip scenarios. There are manyconcrete sub-classes of this abstract class that

Page 471: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 471

test specific types of transformers, such asStringByteArrayTransformersTestCase.

DefaultMuleContextTestCase Tests the creation and disposal of the Mulecontext.

AbstractServiceTestCase An abstract test case that provides methods fortesting the starting, stopping, pausing, resuming,and disposing of services.

Page 472: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 472

Using IDEs

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

Using IDEs

You can use an integrated development environment (IDE) such as Eclipse, IntelliJ, and Mule IDE torapidly develop Mule applications. For more information on the Mule IDE, see the Mule IDE User Guide.

Usually, you simply attach the src.zip file that comes with the Mule distribution to the Mule JARs in yourproject so you can browse the source code while developing your classes. If you want to build Mule fromsource, see the following topics in the Mule Developer's Guide:

• Setting Up the Development Environment• Working with an IDE• Building from Source

Page 473: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 473

Using Mule HQ

This page last changed on Mar 25, 2009 by jwheeler.

Using Mule HQ

[ Overview ] [ HQ Architecture ] [ Enabling Mule to Use Mule HQ ] [ Installing Mule HQ ] [ Startingand Stopping Mule HQ ] [ Logging in to Mule HQ ] [ Importing Mule ] [ Configuring Mule in Mule HQ ] [Setting Up Availability Alerts ] [ Configuring Remote Agents Manually ] [ Monitoring and Controlling YourResources ] [ Uninstalling Mule HQ ]

Overview

Mule HQ provides a centralized way to manage all of your stand-alone Mule deployments as well as all ofthe disparate systems and services in your SOA infrastructure. For example, a typical stack that Mule HQmonitors might include Redhat Enterprise Linux, MySQL, JBoss Application Server, OpenMQ, and Mule.

Mule HQ provides integrated log, configuration, and server event tracking. It can detect Mule serversand associated software and hardware, and report real-time and historical details of events. If you needto debug a problem with your deployment, you can turn on the Profiler and view the details of memoryconsumption at the message level.

Mule HQ is available with Mule Enterprise Edition only. It can monitor both Community Edition andEnterprise Edition instances of Mule 1.x and 2.x servers. Mule HQ supports stand-alone Mule deploymentsonly and cannot monitor embedded Mule instances.

HQ Architecture

Mule HQ is based on Hyperic HQ. This section describes the Hyperic HQ Server and Agent.

Hyperic HQ Server

As HQ's central nervous system, the HQ Server coordinates all system functions, including:

• Processing incoming monitoring data• Detecting alert conditions and sending out alerts• Managing inventory, including merging auto-discovery information into current inventory• Enforcing security• Maintaining HQ operational schedules (for control actions and auto-discovery scans)• Processing user-driven actions initiated via the HQ GUI or command line interface

In large environments, the HQ Server can be clustered to enhance fault tolerance and to share the overallsystem load across multiple machines.

Page 474: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 474

Hyperic HQ Agent

Acting as the sensory facilities of the HQ system, Agents are deployed throughout the networkinfrastructure to provide points-of-presence for discovering inventory, gathering data, controllingsoftware, and other "in the trenches" tasks.

The HQ Shell's Agent installer makes quick work of installing and managing all your HQ Agents - withoutever having to visit each managed machine.

Enabling Mule to Use Mule HQ

To use Mule with Mule HQ, you must enable the JMX support agent and (if installed) the Mule Profiler inyour Mule configuration.

Your Mule configuration files must be available to Mule HQ on a relative or absolute path.They cannot be embedded in a JAR file.

Configure the JMX Support Agent

The default JMX support agent configures several JMX agents simultaneously. To add this to yourconfiguration, you add the management namespace and the <management:jmx-default-config>element to your configuration file. For example, the following example includes the xmlns:managemententry, the declaration of the XSD location (http://www.mulesource.org/schema/mule/management/2.2http://www.mulesource.org/schema/mule/management/2.2/mule-management.xsd) and the<management...> entries:

<?xml version="1.0" encoding="UTF-8" ?> <mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:management="http://www.mulesource.org/schema/mule/management/2.2" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.mulesource.org/schema/mule/core/2.2

Page 475: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 475

http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/management/2.2 http://www.mulesource.org/schema/mule/management/2.2/mule-management.xsd"> <management:jmx-default-config port="1098"> <management:credentials> <spring:entry key="jsmith" value="foo"/> <spring:entry key="dthomas" value="bar"/> <spring:entry key="clee" value="pwd"/> </management:credentials> </management:jmx-default-config> ...</mule>

Note: you only specify the port if you don't want to use the default of 1099.

You can also provide more advanced configuration, such as using the RMI registry agent and specifyingthe JMX server explicitly:

<management:rmi-server serverUri="rmi://localhost:9000"/><management:jmx-server> <management:connector-server url="service:jmx:rmi:///jndi/rmi://localhost:9000/server"/> <management:credentials> <spring:entry key="user" value="pass"/> </management:credentials></management:jmx-server>

For more information, see Jmx Management.

Enable the Profiler Pack

The Mule Profiler pack allows you to profile your application (see Profiling Mule). After downloading andinstalling the Profiler pack, you add the following element to your Mule configuration file:

<management:yourkit-profiler />

You must also add the -profile attribute to the bash/cmd script. For example, if you are using Windows,you would edit stockquote.bat as follows:

IF '%Choice%'=='1' call "%MULE_BASE%\bin\mule.bat" -config".\conf\stdio-config.xml,.\conf\stockquote-rest-config.xml" -builder spring -profile

If you are using a non-Windows operating system, you would edit it as follows:

if [ 1 = $i ]then exec "$MULE_BASE/bin/mule" -config "./conf/stdio-config.xml,./conf/stockquote-rest-config.xml" -builder spring -profile

The configuration file you specify in the batch file depends on which variation and Mule instance you wantto use. The previous example specified the REST version of the Stock Quote example.

Page 476: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 476

Setting the Server ID

When you run Mule, you must specify the -M-Dmule.serverId=MULE_SERVER_ID switch on the commandline (where MULE_SERVER_ID is the name of your Mule server) or set it programatically by callingorg.mule.config.DefaultMuleConfiguration.setId(). This will create the Mule.MULE_SERVER_ID JMXdomain, which Mule HQ will use to detect the Mule instance. You'll set this same domain ID when youconfigure Mule in Mule HQ.

Verify the Configuration

Verify that your configuration changes were applied by starting the Mule instance you just configured (besure to specify the server ID as described in the previous section). For example, launch the stock quoteexample and select REST when prompted:

You should see an output similar to the one below at the end:

Page 477: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 477

Installing Mule HQ

This section describes how to install the HQ Server and Agent. By default, Mule HQ uses its owninternal database. To install Mule HQ with an external database, see Installing Mule HQ with an ExternalDatabase.

Prerequisites

Before you install Mule HQ, you must do the following:

1. If you have not already done so, contact MuleSource Sales to obtain a license (you can get a triallicense for free). Mule HQ will not run without a license.

2. Log in as a non-root user and install Mule. Make sure that this non-root user account has Java inthe environment variable PATH and has write permission to <MULE_BASE>/conf/wrapper files or<MULE_HOME>/conf/wrapper files, depending on whether MULE_BASE is set. If you already haveMule installed, ensure that your system is still using the supported platforms (e.g., a supportedversion of Java).

3. Configure your Mule instance to support Mule HQ (see Enabling Mule to Use Mule HQ).4. On UNIX platforms, ensure that libXp.so.6 is installed. HQ Server requires this library to create

charts and other graphics in the user interface.

For more information on prerequisites, see the Installation Overview on the Hyperic site.

Install Mule HQ

1. On the computer where you want to install Mule HQ, log in as the same non-root user you usedwhen you installed Mule, and then create a directory called MuleHQ, such as C:\Program Files\MuleHQ.

2. Download the Mule HQ distribution (mule-hq-installer) and decompress it to the Mule HQdirectory.

3. In the Mule HQ directory, run setup.bat (on Windows) or setup.sh (on UNIX) at the commandprompt.

4. Follow the instructions on the screen (see the example below for details) and enter the followingvalues:

• When prompted to choose which software to install, press 1 and 3 to install both the HQ serverand agent.

• For the HQ server installation path, specify the MuleHQ directory you created in step 1, such asC:\Program Files\MuleHQ.

Example Installation

This example illustrates what you see during installation. For simplicity, everything will be installed on thelocalhost. The values you enter during installation are marked in bold.

Buildfile: C:\Temp\mule-hq-installer\installer-3.1.2-EE\bin\..\data\setup.xml

Initializing Mule HQ 3.1.2-EE Installation...

Loading taskdefs...Taskdefs loadedChoose which software to install:1: Mule HQ Server2: Mule HQ Shell3: Mule HQ AgentYou may enter multiple choices, separated by commas.1,3HQ server installation path [default 'C:\Program Files']:C:\Program Files\MuleHQHQ agent installation path [default 'd:/server/MuleHQ']:

Loading install configuration...Install configuration loaded.Preparing to install...

Page 478: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 478

Validating agent install configuration...Validating server install configuration...Checking server webapp port...Checking server secure webapp port...Checking server JRMP port...Checking server JNP port...Verifying admin user propertiesValidating server DB configuration...Installing the agent...Looking for previous installationUnpacking agent to: d:/server/MuleHQ/agent-3.1.2-EE...Installing the JRE ...Unpacking JRE x86-win32-jre.exe to: d:/server/MuleHQ/agent-3.1.2-EE...Setting permissions on agent binaries...Fixing line endings on text files...--------------------------------------------------------------------------------

Installation Complete:Agent successfully installed to: d:/server/MuleHQ/agent-3.1.2-EE--------------------------------------------------------------------------------

You can now start your HQ agent by running this command:

d:\server\MuleHQ\agent-3.1.2-EE\hq-agent.exe start

Installing the server...Unpacking server to: d:/server/MuleHQ/server-3.1.2-EE...Creating server configuration files...Copying binaries and libraries to server installation...Copying server configuration file...Copying server control file...Copying server binaries...Copying server libs...Setting up server database...Setting up JDBC driver...Copying database files...Configuring database...Starting repopulation of configuration table...Waiting for built-in database to start (on port 9432)...Starting built-in database...Preparing database...Vacuuming database...Waiting for server to stop...Stopping built-in database...Built-in database stopped.Installing the JRE ...Unpacking JRE x86-win32-jre.exe to: d:/server/MuleHQ/server-3.1.2-EE...Setting permissions on server binaries...Fixing line endings on text files...--------------------------------------------------------------------------------

Installation Complete:Server successfully installed to: d:/server/MuleHQ/server-3.1.2-EE--------------------------------------------------------------------------------

You should now install the HQ server as a Windows Service using this command:

d:\server\MuleHQ\server-3.1.2-EE\bin\hq-server.exe -i

You can then use the Service Control Manager (Control Panel->Services) tostart the HQ server. Note that the first time the HQ server starts up it maytake several minutes to initialize. Subsequent startups will be much faster.

Once the HQ server reports that it has successfully started, you can log into your HQ server at:

Page 479: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 479

[http://localhost:7080/]username: hqadminpassword: hqadmin

To change your password, log in to the HQ server, click the "Administration"link, choose "List Users", then click on the "hqadmin" user.

Setup completed.A copy of the output shown above has been saved to:D:\Temp\mule-hq-installer\installer-3.1.2-EE\bin\../hq-install.log

Press the Enter key to exit setup.

Detailed HQ Installation Instructions

For more detailed installation instructions, see the following Hyperic documentation:

• Windows• Non-Windows

Install the HQ Server as a Windows Service

You can install the HQ Server as a Windows Service so that you can leave the HQ Server running evenafter you log out of Windows. To install it as a service, navigate to the Mule HQ Server bin directory(such as C:\Program Files\MuleHQ\server-3.1.2-EE\bin) and enter the following command at thecommand prompt:

hq-server.exe -i

This command creates two services: Hyperic HQ Database and Hyperic HQ Server. You start the databaseservice first and then the server.

Customize the JVM used by Mule HQ

You can set the environment variable HQ_JAVA_HOME to use a Java VM other than the one that shipswith Mule HQ.

Starting and Stopping Mule HQ

The first time you start the HQ Server, it can take several minutes to initialize. Note that this happensonly the first time you start the server; subsequent starts are much faster.

Starting Mule HQ

To start Mule HQ, you start the database, then the server, and then the agent.

Start the Database and Server

Navigate to the Mule HQ Server bin directory and execute the following commands:

db-starthq-server

Note that there will be no console output from the first script. The second script should indicate that thecore system was initialized and that it is configuring from URL: resource:log4j.xml. Leave this commandwindow open while you are running Mule HQ.

If you installed the HQ Server as Windows services, you can start and stop the services from the Servicesapplication in the Control Panel, or you can enter the following commands at the command prompt:

net start "Hyperic HQ Database"net start "Hyperic HQ Server

Page 480: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 480

Start the Agent

In a new command window, navigate to the agent directory (such as C:\Program Files\MuleHQ\agent-3.1.2-EE) and enter the following command at the command prompt:

hq-agent

You must now answer several questions at the prompt. If you are testing the setup, you can specifylocalhost for the server IP address and accept the defaults for everything else. For more information onthe agent settings, see Mule HQ Agent Settings.

If the connection fails, and you are using an evaluation version of Mule HQ, your licensemay have expired. Click here to contact MuleSource about purchasing a license.

Stopping Mule HQ

To stop the server, log out of your Windows session, or enter the following command:

hq-server stop

If you installed the HQ Server as a Windows service, you can stop the service from the Servicesapplication, or by entering net stop "Hyperic HQ Server" at the command prompt.

Logging in to Mule HQ

To log in to Mule HQ, do the following:

1. In a web browser, navigate to port 7080 of the server on which Mule HQ is installed, such ashttp://localhost:7080/ or http://hostname.network.com:7080/.The Mule HQ Login screen appears.

If the login screen does not appear, and you are using an evaluation version ofMule HQ, your license may have expired. Click here to contact MuleSource aboutpurchasing a license.

2. Enter the default Administrator Login (hqadmin)and Password (hqadmin).The Mule HQ Dashboard displays. Mule might be in the Auto-discovery list already. If it is not,continue to the next section to import Mule into HQ.

Importing Mule

The Dashboard consists of several portlets that provide information about the HQ deployment. The firstportlet is the Auto-Discovery portlet, which discovers platforms, servers, and services on your systemand displays them here. After first starting Mule HQ, the portlet displays several entries (platform andservers) for the newly registered HQ Agent on the local machine and for any other resource it has foundon the host so far. These resources need to be "imported" (added to the HQ inventory) so that the Agentcan start collecting default metrics for them. You will know that the platform has been successfullyimported when you see its hostname in the Recently Added portlet (at the left).

You can manually import the platform, or use scripts to manage integration with Mule.

Importing the Platform Manually

On the Dashboard, select the radio button next to your host (and next to any other platform and serverentries in this portlet) and click Add to Inventory.

Using the Mule Integration Scripts

Mule HQ provides scripts for managing integration with Mule from the command line or programmatically.To enable these scripts, copy the file commons-cli-1.1.jar from MULE_HOME\lib\boot to the followinglocation under your Mule HQ server directory: hq-engine\server\default\deploy\hq.ear\lib

Page 481: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 481

To run these scripts, you enter the following command at the command prompt:

java -jar mule-sdk.jar <subcommand> <hq_host> <hq_port> <hq_username> <hq_password>

The following optional parameters constrain the subcommand to a specific Mule platform (otherwise, allMule platforms are affected):

• hq_host is the host where Mule HQ server is installed• hq_port is the port of Mule HQ server• hq_username, hq_password are credentials for the Mule HQ user

The subcommand must be one of the following:

Command Description

ai:approve Automatically approves and configures pendingMule resources in the auto-discovery list.

ai:delete Deletes the pending Mule resources from theauto-discovery list. In complex scenarios, youmust call this before calling ai:rescan.

ai:rescan Rescans Mule resources so that they will re-appear in the auto-discovery list.

delete Deletes all approved Mule platforms from MuleHQ.

ai:revert Reverts all skipped Mule instances from theignored state so that they can reappear in theauto-discovery list.

Viewing Imported Resources

After importing a Mule instance manually or through the scripts, the Mule servers are added to Mule HQ.

Page 482: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 482

Page 483: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 483

All imported Mule servers appear on the Mule Center tab.

After importing the Mule platform, if you want to run auto-discovery manually to discover recently addedMule instances, do the following:

1. At the top of the Mule HQ window, click Browse Resources.2. On the Platforms tab, click the Mule platform to display its details.3. Click Tools Menu in the upper-right corner, and then choose New Auto-Discovery.

Page 484: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 484

4. Select the Mule check box and specify your Mule home directory for the directories to scan.5. Leave the defaults for everything else and click OK.

Page 485: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 485

Click the Dashboard to see the newly discovered resources that are ready for import.

Page 486: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 486

Configuring Mule in Mule HQ

After you have imported Mule into Mule HQ, you might need to perform some additional configuration.

To configure Mule:

1. On the Dashboard, click the Mule platform, click the Mule instance you want to configure, and clickthe Inventory tab.

2. Scroll down until you see the Configuration Properties group, click it to expand its contents, andthen click Edit.

3. Enter the following settings:• Specify the domain as Mule followed by a period followed by the Mule server ID you specified

when you ran Mule (see Setting the Server ID), such as Mule.MyMuleServer. This step is veryimportant. If the domain was already imported through auto-discovery, you can leave it as is.

• Specify the JMX URL used by your Mule instance. This URL is displayed on the startup screenwhen you start Mule under Agents Running. If you do not see the JMX Agent listed, you havenot properly configured your Mule instance to work with Mule HQ--see Enabling Mule to UseMule HQ above.

• Leave the user name and password as empty values.• Enable the Auto-Discover Components, Connectors, and Other Services option.

Make sure the metrics you want are collected often enough so you see theresults faster. Otherwise, it defaults to 1 minute.

4. Click OK.

For complete instructions on configuring resources in HQ, see Getting Started with HQ.

Setting Up Availability Alerts

Mule HQ can alert you when availability is lost. To enable this feature, take the following steps:

Page 487: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 487

1. Navigate to the conf directory in your Mule HQ Server directory, and then open hq-server.conf forediting.

2. Configure your mail server and set up email addresses for all Mule HQ users you want to notify, thensave and close the file.

3. In Mule HQ, click Mule, click the Alert tab, click New, and then specify a condition where theavailability metric's value is less than 100%.

4. Save the alert definition and specify the users to be notified for this condition.

For complete information on configuring alerts, click here.

Configuring Remote Agents Manually

JBoss 4.2 does not provide or expose the JMX service URL. You can view Mule within JBoss by enabling aremote JMX connection. This approach makes JBoss visible through JConsole and enables some remoteactions. However, this approach does not enable Mule HQ access.

To work around this limitation, Mule can start a local RMI registry (the JBoss 4.x registry will not work,as it is not pure RMI) and connect via this lookup. To enable this approach, set the port attribute onthe <jmx-default-config> element in Mule as shown in Configure the JMX Support Agent above. Thisensures both the registry and JMX connector are coordinated properly and allows you to assign customconnection ports. You then specify the JMX ServiceURL in MuleHQ as:

service:jmx:rmi:///jndi/rmi://localhost:1099/server

Because Mule HQ will not automatically discover this Mule instance, you must add it manually in the MuleHQ application. You can specify a dummy server directory but specify the correct JMX URL and port. Afterloading Mule HQ Server, the new Mule instance is discovered along with its components, routers, andmore.

For complete information on configuring agents in Mule HQ, click here.

Monitoring and Controlling Your Resources

Now that you have completed the installation and configuration, see the following topics for moreinformation on using Mule HQ:

• Monitoring Basics• Controlling Resources

Following is a description of some of the key features for monitoring and controlling your resources inMule HQ.

As you monitor your components, note that statistics are not generated forBridgeComponents, such as the BridgeComponent in the Stock Quote example.

Stopping, Starting, and Restarting Mule from Mule HQ

You can use the Stop, Start, and Restart control actions on the Control tab in Mule HQ to control a Muleserver, component, endpoint, router, or connector.

Page 488: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 488

• The Stop command stops the Mule server and all related processes.

• The Start command launches a new Mule server instance using the HQ Agent. The HQ Agent createsand executes a new command line using the configuration parameters stored in the inventory.

• The Restart command send a "restart" signal to restart the JVM and re-read the configurationfile. The Wrapper is not stopped, and external parameters like debug, profile, service, and theconfiguration file are unchanged. Therefore, Restart is not the same as using the Stop and Startcommands.

Profiling Mule

Mule is integrated with YourKit Java Profiler 7.0, the industry leader among profiling tools. If you installedMule and Mule HQ with the profiling option, you can use the Profiling tab in Mule HQ to create a snapshot,start CPU profiling, and more. Captured snapshots are saved in ~/Snapshots/ on Linux.

If you did not install the Profiling kit with Mule or did not enable it, the Profiling tab indicates that theprofiler is not installed or enabled. If you want to install it now, you can download the ZIP or GZ versionof the mule-profiler-pack file here and follow the instructions here to install it.

Page 489: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 489

Patch Management

The Mule Center tab in Mule HQ provides a list of all your Mule servers. It also allows you to install Mulepatches to remote servers that have been distributed to you by MuleSource.

Viewing Mule Log Files

You can view the Mule log files from remote servers in Mule HQ by clicking the Show Log link on theIndicators tab when viewing the details of a Mule server.

Uninstalling Mule HQ

To uninstall Mule HQ, you run the hq-server and hq-agent scripts with the -u parameter. For example, onWindows you would run:

hq-server.exe -u

Page 490: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 490

hq-agent.exe -u

For complete information on uninstalling HQ, see Uninstalling Hyperic HQ on the Hyperic site.

Page 491: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 491

Installing Mule HQ with an External Database

This page last changed on Dec 10, 2008 by jackie.wheeler.

Installing Mule HQ with an External Database

By default, Mule HQ uses its own internal database. This section describes how to install Mule HQ witha standalone PostgreSQL, Oracle, or MySQL database. To install, navigate to the Mule HQ directory, andthen run one of the following commands to perform a quick install, which prompts you for the databaseconnection information and uses defaults for all other settings:

PostgreSQL

UNIX: setup.sh -postgresql

Windows: setup.bat -postgresql

Oracle

UNIX: setup.sh -oracle

Windows: setup.bat -oracle

MySQL

UNIX: setup.sh -mysql

Windows: setup.bat -mysql

Notes

PostgreSQL 8.0

During installation, Mule HQ creates a language in the PostgreSQL database, but Mule HQ cannot createthe language automatically in PostgreSQL 8.0. Therefore, to use version 8.0, you must run the followingcommand on the Mule HQ database before starting the Mule HQ Server.

createlang plpgsql [MULEHQ:DATABASE NAME]

The createlang executable is located in the bin directory of your PostgreSQL installation.

MySQL 5.0

MySQL 5.0 or higher is not yet supported by Hyperic HQ and is currently in Beta. Support is expected forHyperic HQ 3.2.

For advanced database preparation, see the Database Preparation Guide

Page 492: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 492

Mule HQ Agent Settings

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

Mule HQ Agent Settings

When you run the Mule HQ Agent, it prompts you for connection information to your HQ Server.

[MULEHQ: Running agent setup ]What is the HQ server IP address: 172.30.46.145Should Agent communications to HQ always be secure [MULEHQ:default=yes]: yesWhat is the HQ server port [MULEHQ:default=7080]: 7080- Testing secure connection ... SuccessWhat is your HQ login [MULEHQ:default=hqadmin]: hqadminWhat is your HQ password: **Not echoing value**What IP should HQ use to contact the agent [MULEHQ:default=172.30.46.145]: 172.30.46.145What port should HQ use to contact the agent [MULEHQ:default=2144]: 2144- Received temporary auth token from agent- Registering agent with HQ- HQ gave us the following agent token1192444751142-7096515327909319777-6396758454203270452- Informing agent of new HQ server- Validating- Successfully setup agent

To make the Agent deployment process easier, you can specify these settings in the agent.propertiesfile located in the agent root directory. The file looks like this:

agent.setup.camIP=172.30.46.145agent.setup.camPort=7080agent.setup.camSSLPort=7443agent.setup.camSecure=yesagent.setup.camLogin=hqadminagent.setup.camPword=hqadminagent.setup.agentIP=*default*agent.setup.agentPort=*default*

where values of camIP, camLogin and camPword parameters should be replaced with your HQ Server IP,user name, and password. By setting these values in the file, you will no longer need to interactivelyanswer questions when you first start up the Mule HQ Agent.

Additionally, the MuleServerDetector uses an Internet connection to get some DTDs. If you use anexternal HTTP proxy for your Internet connection, you must add the following value to the agent.javaOptsproperty:

-Dhttp.proxyHost=<PROXY_HOST> -Dhttp.proxyPort=<PROXY_PORT>

For more information on agent properties see the HQ Agent Configuration page on the Hyperic site.

Page 493: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 493

Using Mule Modules

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

Using Mule Modules

Modules are similar to transports in that they provide pluggable functionality, configured via dedicatedschema, but they differ in that there is no underlying transport to send or receive data. Following is a listof the default Mule modules.

Acegi Module Security via Acegi.

Client Module MuleClient and the remote dispatcher, givingsimple access to the Mule server.

JAAS Module Security via JAAS.

JBoss Transaction Manager JBoss transaction support.

Management Module Mule agents for server management using JMX.

OGNL Module Provides a filter using OGNL expressions. Fordetails, see Using OGNL Expressions.

PGP Module Security via PGP.

Scripting Module Interface between Mule and scripting languages(currently Groovy).

Spring Extras Module Extensions for using the Spring framework withMule.

SXC Module A very fast streaming XPath router and filter.

XML Module XML based utilities (mainly filters and routers).

Page 494: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 494

Acegi Module

This page last changed on Feb 20, 2009 by jackie.wheeler.

Acegi Module

This module provides Acegi-based security and delegates authorization to some other provider.

Security Manager

Child Elements of <security-manager...>

Name Cardinality Description

delegate-security-provider 0..1 An Acegi-based security providerthat delegates authorization tosome other provider.

Delegate Security Provider

An Acegi-based security provider that delegates authorization to someother provider.

Attributes of <delegate-security-provider...>

Name Type Required Default Description

delegate-ref name (no spaces) no

Child Elements of <delegate-security-provider...>

Name Cardinality Description

security-property 0..*

Http Security Filter

This appears to authenticate users via information in standard HTTP headers.

Attributes of <http-security-filter...>

Name Type Required Default Description

realm string no

securityProviders string no The delegate-security-providerto use forauthenticating.Use this element

Page 495: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 495

in case youhave multiplesecurity managersdefined in yourconfiguration.

Page 496: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 496

JAAS Module

This page last changed on Feb 20, 2009 by jackie.wheeler.

JAAS Module

This module provides security via JAAS.

Security Manager

This is the security provider type that is used to configure JAAS related functionality.

Child Elements of <security-manager...>

Name Cardinality Description

security-provider 0..1 This is the security provider typethat is used to configure JAASrelated functionality.

password-encryption-strategy 0..*

Security Provider

This is the security provider type that is used to configure JAAS related functionality.

Attributes of <security-provider...>

Name Type Required Default Description

loginContextName string no

credentials string no

loginConfig string no

loginModule string no

Jaas Security Filter

Authenticates users via JAAS.

Page 497: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 497

JBoss Transaction Manager

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

JBoss Transaction Manager

This module enables Mule to use the JBoss transaction manager (previously Arjuna) to configure XAtransactions. Developers can configure one Transaction Manger per Mule instance. For more information,see JBoss Transactions.

Transaction Manager

To configure an instance of the JBoss transaction manager within Mule, add this element to your MuleXML config file. You can configure arbitrary properties on the transaction manager that will be passed onto the underlying transaction manager. For example:

<jbossts:transaction-manager> <property key="test" value="TEST"/></jbossts:transaction-manager>

You can then declare XA transactions on endpoints supporting XA transactions, and all those transactionswill be managed by the JBoss transaction manager.

Page 498: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 498

Scripting Module

This page last changed on Mar 04, 2009 by jackie.wheeler.

Scripting Module

[ Script Configuration Builder ] [ Component ] [ Script ] [ Transformer ] [ Groovy Refreshable ] [ Lang ]

The scripting module provides facilities for using scripting languages in Mule. Any scripting languagesthat supports JSR-223 can be used inside Mule. Scripts can be used as implementations of servicecomponents or transformers. Also, scripts can be used for expression evaluations, meaning messagerouting can be controlled using script evaluations on the current message. You can even configure Muleinstances from scripts.

Script Configuration Builder

The ScriptConfigurationBuilder allows developers to create a Mule instance from a JSR-223 compliantscript. To load the manager from Groovy:

ConfigurationBuilder builder = new ScriptConfigurationBuilder("groovy", "../conf/mule-config.groovy");MuleContext muleContext = new DefaultMuleContextFactory().createMuleContext(builder);

Or to start the server from the command line:

mule -M-Dorg.mule.script.engine=groovy-builder org.mule.module.scripting.builders.ScriptConfigurationBuilder-config ../conf/mule-config.groovy

For more information about configuring a Mule instance from code or script see Configuration Overview.

Component

Defines a script component backed by a JSR-223 compliant script engine such as Groovy, JavaScript, orRuby. Scripting allows you to either directly embed your script inside the XML config or reference a scriptusing Spring's dynamic language support: http://static.springframework.org/spring/docs/2.5.x/reference/dynamic-language.html.

Attributes of <component...>

Name Type Required Default Description

script-ref name (no spaces) no A reference toa script objectbean, that is, a<script:script ...>definition.

Child Elements of <component...>

Name Cardinality Description

Page 499: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 499

script 0..1 A script to be executed bya JSR-223 compliant scriptengine such as Groovy,JavaScript(Rhino), Python, Ruby,or Beanshell.

java-interface-binding 0..* A binding associates a Muleendpoint with an injected Javainterface (this is like usingSpring to inject a bean, butinstead of calling a method onthe bean a message is sent toan endpoint). Script bindingswill only work with Java-basedscripting languages. Rightnow there is no validation onwhen languages support Javabindinngs because there are somany scripting languages.

The following example demonstrates how to configure a Groovy script component with an in-line script:

<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:script="http://www.mulesource.org/schema/mule/scripting/2.2" xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.2" xsi:schemaLocation=" http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/scripting/2.2 http://www.mulesource.org/schema/mule/scripting/2.2/mule-scripting.xsd http://www.mulesource.org/schema/mule/vm/2.2 http://www.mulesource.org/schema/mule/vm/2.2/mule-vm.xsd">

<vm:connector name="vmConnector" queueEvents="true"/>

<script:script name="myScript" engine="groovy"> return "$payload Received" </script:script>

<model> <service name="inlineScript"> <inbound> <inbound-endpoint address="vm://in1"/> </inbound> <script:component> <script:script engine="groovy"> return "$payload Received" </script:script> </script:component> <outbound> <pass-through-router> <outbound-endpoint address="vm://out1"/> </pass-through-router> </outbound> </service>...

The following example demonstrates how to orchestrate message flows using bindings. The example callsout to two different services and passes the results on to the outbound router.

Page 500: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 500

Click here to expand...

<service name="scriptWithBindings"> <inbound> <inbound-endpoint ref="client_request"/> </inbound> <script:component> <script:script engine="groovy"> msg = CalloutService.doSomething(payload) return CalloutService.doSomethingElse(msg) </script:script> <script:java-interface-binding interface="org.mule.components.script.CalloutService" method="doSomething"> <outbound-endpoint ref="callout_1" synchronous="true"/> </script:java-interface-binding> <script:java-interface-binding interface="org.mule.components.script.CalloutService" method="doSomethingElse"> <outbound-endpoint ref="callout_2" synchronous="true"/> </script:java-interface-binding> </script:component> <outbound> <pass-through-router> <outbound-endpoint ref="client_response"/> </pass-through-router> </outbound> </service>

<service name="Callout1"> <inbound> <inbound-endpoint ref="callout_1"/> </inbound> <test:component appendString=" Received by #[mule:context.serviceName]"/> </service>

<service name="Callout2"> <inbound> <inbound-endpoint ref="callout_2"/> </inbound> <test:component appendString=" Received by #[mule:context.serviceName]"/> </service>

Script

Represents a script that can be used as a component for a service or a transformer. The script text canbe pulled in from a script file or can be embedded inside this element. A script can be executed by anyJSR-223 compliant script engine such as Groovy, JavaScript(Rhino), Python, Ruby, or Beanshell.

Attributes of <script...>

Name Type Required Default Description

name string no The name usedto identify thisscript object. Thisis used when youwant to referencethis script objectfrom a componentor transformer.

Page 501: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 501

engine string no The name of thescript enginebeing used.All scriptinglanguages thatsupport JSR-223have a scriptengine name suchas groovy, ruby,python, etc. If thisvalue is not set,but a script file isconfigured, Mulewill attempt toload the correctscript engineaccording tothe script file'sextension.

file string no The script fileto load for thisobject. The filecan be on theclasspath or localfile system.

Child Elements of <script...>

Name Cardinality Description

text 0..1 Used for embedding script codeinside the XML. This is usefulfor simple scripts where youare just mocking up a quickapplication.

Script Context Bindings

When run inside Mule, scripts have a number of objects available to them in the script context:

Name Description

log A logger that can be used to write to Mule's logfile.

muleContext A reference to the MuleContext object.

eventContext A reference to the event context. This allows youto dispatch events progammatically from yourscript.

message The current message.

originalPayload The payload of the current message before anytransforms.

Page 502: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 502

payload The transformed payload of the currentmessage if a transformer is configured on theservice. Otherwise this is the same value asoriginalPayload.

src Same as payload, kept for backwardcompatability.

service A reference to the current service object.

id The current message ID.

result A placeholder object where the result of the scriptcan be written. Usually it's better to just returna value from the script unless the script methoddoesn't have a return value.

message properties Any message properties can be used as variablesfor the script.

Transformer

Runs a script to perform transformation on the current message.

Child Elements of <transformer...>

Name Cardinality Description

script 0..1 A script to be executed bya JSR-223 compliant scriptengine such as Groovy,JavaScript(Rhino), Python, Ruby,or Beanshell.

To use Groovy as an example, the following transformer configuration will convert a comma-separatedstring of values to a java.util.List.

<script:transformer name="stringReplaceWithParams"> <script:script engine="groovy"> <property key="oldStr" value="l"/> <property key="newStr" value="x"/> <script:text> return payload.toString().replaceAll("$oldStr", "$newStr") </script:text> </script:script> </script:transformer>

Groovy Refreshable

A wrapper for a component object that allows the underlying object to be reloaded at runtime. Thismakes it possible to hot-deploy new component logic without restarting.

Page 503: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 503

Attributes of <groovy-refreshable...>

Name Type Required Default Description

name string no The name for thisrefreshable groovybean wrapper.

refreshableBean-ref

name (no spaces) no The reference to agroovy.lang.Groovyobject to use forthis component.

methodName string no The entrypointmethod to invokewhen a messageis received for theobject.

Lang

This element allows the http://www.springframework.org/schema/lang namespace to be embedded.Within this element developers can include the Spring lang namespace.

Page 504: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 504

Spring Extras Module

This page last changed on Nov 25, 2008 by jackie.wheeler.

Spring Extras Module

This module provides extensions for using the Spring framework with Mule, such as using the Springcontainer to build components managed by Mule.

Package Description

org.mule.module.spring.events A Spring EventMulticaster that allows any Springbean to send and receive Mule events through theApplicationContext and event listeners.

org.mule.module.spring.i18n Spring messages that can be localized.

org.mule.module.spring.remoting Classes for using Spring remoting. For moreinformation, see the Spring Remoting example.

org.mule.module.spring.transaction Provides classes for a transaction factory andtransaction manager factory.

Page 505: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 505

SXC Module

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

SXC Module

The SXC module contains an outbound router and a filter that use the SXC project for streaming XPathrouting.

SXC allows listening for XPath expressions as the document is being parsed. As soon as an expressionis found, an event is fired, and parsing is stopped. This allows for much more efficient XPath evaluation.XPath evaluators such as Jaxen work with a DOM model, so even when working with lazy-loading DOMs,such as AXIOM, there is more overhead than in just reading directly off the XML stream.

SXC supports a limited subset of XPath expressions. For details, see the SXC documentation. To requestsupport for a missing XPath feature, please file a SXC JIRA.

Using the SXC Outbound Router and Filter

SXC requires a special filtering outbound router, inside of which you configure the SXC filterand any other filters that do not work on the XML payload itself (such as AndFilter, OrFilter, andMessagePropertyFilter). For example, this configuration routes a message based on an XML attribute:

<sxc:filtering-router> <outbound-endpoint address="vm://log"/> <sxc:filter pattern="//purchaseOrder[@country]"/> <sxc:namespace prefix="test" uri="http://foo"/></sxc:filtering-router>

Following is another example of a filter that looks for messages where the billing address is within theUnited States:

<sxc:filtering-router> ... <sxc:filter pattern="/customer/billingaddress/country[text()='US']"/> ...</sxc:filtering-router>

Page 506: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 506

XML Module

This page last changed on Feb 23, 2009 by jackie.wheeler.

XML Module

[ XML Formats ] [ Transformers ] [ Filters ] [ Splitters ]

The XML module contains several tools to help you read, transform, and write XML.

In addition to the functionality described on this page, you can also use the SXC Module, which enablesefficient XPath XML routing.

XML Formats

Mule understands a wide variety of XML Java representations:

• org.w3c.dom.Document, org.w3c.dom.Element• org.dom4j.Document• javax.xml.transform.Source• InputStream, String, byte[]• OutputHandler• XMLStreamReader• org.mule.module.xml.transformer.DelayedResult

Any transformer that accepts XML as an input will also understand these types.

Transformers

There are several standard transformers that process XML inside Mule.

Transformer Description

XmlToObject <-> ObjectToXml Converts XML to a Java object and back againusing XStream.

XSLT Transforms XML payloads using XSL.

DomToXml <-> XmlToDom Converts DOM objects to XML and back again.

XmlToXMLStreamReader Converts XML from a message payload to a StAXXMLStreamReader.

XPath Extractor Queries and extracts object graphs using XPathexpressions using JAXP.

JXPath Extractor Queries and extracts object graphs using XPathexpressions using JXPath.

XmlPrettyPrinter Allows you to output the XML with controlledformatting, including trimming white space andspecifying the indent.

Efficient Transformations with DelayedResult

Mule contains a special XML output format called DelayedResult. This format allows very efficient XMLtransformations by delaying any XML serialization until an OutputStream is available.

For example, here is an XSLT transformer set up to use DelayedResult:

Page 507: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 507

<mxml:xslt-transformer name="transform-in" xsl-file="xslt/transform.xslt" returnClass="org.mule.module.xml.transformer.DelayedResult"/>

If the result of this transformation were being sent to an HTTP client, the HTTP client would ask Mule foran OutputHandler and pass in the OutputStream to it. Only then would Mule perform the transformation,writing the output directly to the OutputStream.

If DelayedResult were not used, the XML result would first be written to an in-memory buffer beforebeing written to the OutputStream. This will cause your XML processing to be slower.

Filters

The XML module contains various XPath filters. For general details on how to use filters, see Using Filters.

XPath Filter

The XPath filter uses the JAXP libraries to filter XPath expressions. This filter is available as of Mule 2.2.

The following configuration routes messages to the "vm://echo" endpoint when the value of "/e:purchaseOrder/e:shipTo/@country" is "US".

<outbound> <filtering-router> <outbound-endpoint address="vm://echo" synchronous="true"/> <mule-xml:xpath-filter pattern="/e:purchaseOrder/e:shipTo/@country" expectedValue="US"> <mule-xml:namespace prefix="e" uri="http://www.example.com"/> </mule-xml:jxpath-filter> </filtering-router>....</outbound>

Schema Validation Filter

The schema validation filter uses the JAXP libraries to validate your message against a schema. This filteris available as of Mule 2.2.

The following configuration will validate your message against a schema called schema.xsd.

<mule-xml:schema-validation-filter schemaLocations="com/myapp/schemas/schema.xsd com/myapp/schemas/anotherSchema.xsd"/>

Jaxen Filter

The Jaxen filter uses the Jaxen library to filter messages based on XPath expressions.

The following configuration routes messages to the "vm://echo" endpoint when the value of "/e:purchaseOrder/e:shipTo/@country" is "US".

<outbound> <filtering-router> <outbound-endpoint address="vm://echo" synchronous="true"/>

Page 508: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 508

<mule-xml:jaxen-filter pattern="/e:purchaseOrder/e:shipTo/@country" expectedValue="US"> <mule-xml:namespace prefix="e" uri="http://www.example.com"/> </mule-xml:jaxen-filter> </filtering-router>....</outbound>

JXPath Filter

The JXPath filter is very similar to the Jaxen filter. It is still used for historical purposes (it existed beforethe Jaxen filter).

<outbound> <filtering-router> <outbound-endpoint address="vm://echo" synchronous="true"/> <mule-xml:jxpath-filter pattern="/e:purchaseOrder/e:shipTo/@country" expectedValue="US"> <mule-xml:namespace prefix="e" uri="http://www.example.com"/> </mule-xml:jxpath-filter> </filtering-router>....</outbound>

Splitters

The XML module contains two splitters, a filter-based splitter and a round-robin splitter. For moreinformation on these splitters, see Using Message Routers.

Page 509: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 509

DomToXml Transformer

This page last changed on Nov 11, 2008 by jackie.wheeler.

DOM/XML Transformers

Mule contains several transformers that convert between a W3C DOM object and its serializedrepresentation. The DomToXml transformer converts DOM objects to XML, the XmlToDom transformerconverts XML strings to DOM objects, and the DomToOutputHandler transformer converts from a DOM toan OutputHandler serialization.

These transformers support the standard transformer attributes plus the following:

Dom To Xml Transformer

Converts an XML payload (Document, XML stream, Source, etc.) to a serialized String representation.

Attributes of <dom-to-xml-transformer...>

Name Type Required Default Description

outputEncoding string no The encodingto use for theresulting XML/Text.

Dom To Output Handler Transformer

Converts an XML payload (Document, XML stream, Source, etc.) to an OutputHandler for efficientserialization.

Attributes of <dom-to-output-handler-transformer...>

Name Type Required Default Description

outputEncoding string no The encodingto use for theresulting XML/Text.

Xml To Dom Transformer

Transforms an XML message payload to an org.w3c.dom.Document.

Attributes of <xml-to-dom-transformer...>

Name Type Required Default Description

outputEncoding string no The encodingto use for theresulting XML/Text.

Page 510: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 510

Example

To use the DOM/XML transformers, you add them to your Mule XML configuration as follows:

<xm:dom-to-xml-transformer name="DomToXml"/><xm:xml-to-dom-transformer name="xmlToDom" returnClass="org.w3c.dom.Document" /><xm:xml-to-output-handler-transformer name="xmlToOutputHandler" />

You can then reference them by name from endpoints:

<vm:inbound-endpoint name="testEndpoint" path="another.queue" connector-ref="vmConnector1" transformer-refs="DomToXml" />...<vm:outbound-endpoint ref="xml-dom-out" transformer-refs="xmlToDom" /> ...

Page 511: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 511

JXPath Extractor Transformer

This page last changed on Feb 09, 2009 by jackie.wheeler.

JXPath Extractor Transformer

The JXPath extractor transformer evaluates an XPath expression against the current message andreturns the result. By default, a single result will be returned. If multiple values are expected, set thesingleResult property to false, which will return a list of values. This property is available for stringsonly (not XML nodes).

You configure the JXPath extractor transformer as follows:

<jxpath-extractor-transformer name="invoice" expression="/book/title" singleResult="false"/>

Page 512: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 512

XmlObject Transformers

This page last changed on Feb 04, 2009 by jackie.wheeler.

XML-Object Transformers

[ Object to XML ] [ XML to Object ] [ Testing the Transformers ]

This pair of transformers converts XML code to serialized objects and back again. For serialization of JavaXML objects, see DomToXml Transformer.

Object to XML

The Object to XML transformer converts any object to XML using XStream. You configure this transformerusing the <object-to-xml-transformer> element. It takes the standard transformer attributes plusone additional attribute, acceptUMOMessage, which specifies whether to serialize the whole message toXML and not just its payload. This is useful with transports such as TCP where message headers are notsupported and would otherwise be lost.

In Mule 2.2, the acceptUMOMessage attribute is named acceptMuleMessage.

For example:

<xml:object-to-xml-transformer name="ObjectToXml" acceptUMOMessage="true"/>

You can then reference this transformer from an endpoint:

<vm:inbound-endpoint path="another.queue" transformer-refs="ObjectToXml" />

XML to Object

The XML to Object transformer converts XML created by the Object to XML transformer in to a Java objectgraph using XStream. You configure this transformer using the <xml-to-object-transformer> element.It takes the standard transformer attributes.

For example:

<xm:xml-to-object-transformer name="XmlToObject" />

Testing the Transformers

The transformers can be tested using functional tests. For example, the following functional test usesFunctionalTestCase, which is part of Mule's Test support, to test the Object to XML transformer.

public class MuleEndpointConfigurationTestCase extends FunctionalTestCase{

protected String getConfigResources() {

Page 513: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 513

return "org/mule/test/integration/test-endpoints-config.xml"; }

... public void testComponent4Endpoints() throws Exception { // test inbound Service service = muleContext.getRegistry().lookupService("TestComponent4"); assertNotNull(service); assertNotNull(service.getInboundRouter().getEndpoints()); assertEquals(1, service.getInboundRouter().getEndpoints().size()); ImmutableEndpoint endpoint = (ImmutableEndpoint)service.getInboundRouter().getEndpoints().get(0); assertNotNull(endpoint); assertEquals(VMConnector.VM, endpoint.getConnector().getProtocol().toLowerCase()); assertEquals("queue4", endpoint.getEndpointURI().getAddress()); assertFalse(endpoint.getTransformers().isEmpty()); assertTrue(endpoint.getTransformers().get(0) instanceof ObjectToXml); assertTrue(endpoint instanceof InboundEndpoint); }...}

Page 514: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 514

XmlToXMLStreamReader Transformer

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

XmlToXMLStreamReader Transformer

The XmlToXMLStreamReader transformer converts XML representations to a StAX XMLStreamReader.XMLStreamReaders allow XML to be parsed as a series of events that are "pulled" from the stream. It isvery efficient.

This transformer supports the following input formats:

• javax.xml.transform.Source.class• org.xml.sax.InputSource.class• org.dom4j.Document.class• org.w3c.dom.Document.class• org.w3c.dom.Element.class• org.mule.module.xml.transformer.DelayedResult.class• String• byte[]• InputStream

Examples

To use the transformer, you must declare a custom transformer element:

<custom-transformer name="XmlToXSR" class="org.mule.module.xml.transformer.XmlToXMLStreamReader"/>

You can also create a "reversible" XMLStreamReader:

<custom-transformer name="XmlToXSR" class="org.mule.module.xml.transformer.XmlToXMLStreamReader"> <property key="reversible" value="true"/></custom-transformer>

This allows you to cache XML events and replay them:

MuleMessage message = ...;ReversibleXMLStreamReader xsr = (ReversibleXMLStreamReader) message.getPayload();

// start caching eventsxsr.setTracking(true);

// parse....while (...) { xsr.next(); }

// Go back to the beginning of the XML documentxsr.reset();

....

// Don't cache events any morexsr.setTracking(false);

Page 515: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 515

XPath Extractor Transformer

This page last changed on Feb 09, 2009 by jackie.wheeler.

XPath Extractor Transformer

New in Mule 2.2, the XPath extractor transformer evaluates an XPath expression against the currentmessage and returns the result using the JAXP libraries. By default, a string result of the XPathexpression is returned. The transformer can be configured to return other types of results such as aNode, NodeSet, Boolean, or Number.

You configure the XPath transformer as follows:

<xpath-extractor-transformer name="title" expression="/book/title" resultType="NODESET"/>

Page 516: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 516

XSLT Transformer

This page last changed on Mar 06, 2009 by jackie.wheeler.

<xslt-transformer ...>

The XSLT transformer uses XSLT to transform the message payload. Transformation objects are pooledfor better performance. You can set transformation context properties on the transformer and can pullthese properties from the message using Expression Evaluators. This works in a very similar way to theXQuery Transformer on MuleForge.

Attributes

Name Type Required Default Description

outputEncoding string no The encodingto use for theresulting XML/Text.

maxIdleTransformers integer no Transformersare pooled forbetter throughput,since performingand XSLtransformationcan be expensive.This attributecontrols howmany instanceswill remain idle inthe transformerpool.

maxActiveTransformers integer no The totalnumber of XSLTtransformers thatwill get pooled atany given time.

xsl-file string no The full path tothe XSL templatefile to use whenperforming thetransformation.This can be apath on the localfile system or onthe classpath.This attribute isnot required ifthe <xslt-text>element has beenset.

uriResolver name (no spaces) no The URI resolverto use whenvalidating the XSLoutput. If not set,a default resolverwill be usedthat checks for

Page 517: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 517

resources on thelocal file systemand classpath.

transformerFactoryClassname (no spaces) no The fully qualifiedclass name of the{{javax.xml.TransformerFactory}}instance to use.If not specified,the defaultJDK factory{{TransformerFactory.newInstance()}}will be used.

Child Elements

Name Cardinality Description

xslt-text 0..1 The inline XSLT script definition.This is not required if the {{xslt-file}} attribute is set.

context-property 0..* A property that wil be madeavailable to the transformcontext. Expression Evaluatorscan be used to grab theseproperties from the message atruntime.

Example

The following example demonstrates how to configure an inline XSLT transformer pulling parameters fromthe current message.

To use the XSLT transformer, you add it to your Mule XML configuration as follows:

<mulexml:xslt-transformer name="xslt"> <mulexml:xslt-text> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml"/> <xsl:param name="title"/> <xsl:param name="rating"/> <xsl:template match="catalog"> <xsl:element name="cd-listings"> <xsl:attribute name="title"> <xsl:value-of select="$title"/> </xsl:attribute> <xsl:attribute name="rating"> <xsl:value-of select="$rating"/> </xsl:attribute> <xsl:apply-templates/> </xsl:element> </xsl:template>

<xsl:template match="cd"> <xsl:element name="cd-title"> <xsl:value-of select = "title" /> </xsl:element> </xsl:template> </xsl:stylesheet>

Page 518: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 518

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

This example configures a transformer using inline XSLT expressions. It also defines two contextparameters:

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

These parameters are pulled from the current message and made available in the XSLT context so thatthey can be referenced in your XSLT statements. You can use any valid expression. In this example, theheader evaluator is used to pull a header from the current message.

Your configured XSLT transformer can be referenced by an endpoint. In the following example, the resultis written to System.out. The test data looks like this:

<catalog> <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <company>Columbia</company> <price>10.90</price> <year>1985</year> </cd> <cd> <title>Hide your heart</title> <artist>Bonnie Tyler</artist> <country>UK</country> <company>CBS Records</company> <price>9.90</price> <year>1988</year> </cd>

The result written to System.out looks like this:

<cd-listings title="MyList" rating="6"> <cd-title>Empire Burlesque</cd-title> <cd-title>Hide your heart</cd-title> <!-- ... </cd-listings> -->

The full configuration for this example is shown below.

Click here to expand...

<?xml version="1.0" encoding="UTF-8"?><mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mule="http://www.mulesource.org/schema/mule/core/2.2" xmlns:mulexml="http://www.mulesource.org/schema/mule/xml/2.2" xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.2" xmlns:stdio="http://www.mulesource.org/schema/mule/stdio/2.2" xmlns:spring="http://www.springframework.org/schema/beans"

Page 519: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 519

xsi:schemaLocation=" http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/vm/2.2 http://www.mulesource.org/schema/mule/vm/2.2/mule-vm.xsd http://www.mulesource.org/schema/mule/stdio/2.2 http://www.mulesource.org/schema/mule/stdio/2.2/mule-stdio.xsd http://www.mulesource.org/schema/mule/xml/2.2 http://www.mulesource.org/schema/mule/xml/2.2/mule-xml.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<mulexml:xslt-transformer name="xslt"> <mulexml:xslt-text> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml"/> <xsl:param name="title"/> <xsl:param name="rating"/> <xsl:template match="catalog"> <xsl:element name="cd-listings"> <xsl:attribute name="title"> <xsl:value-of select="$title"/> </xsl:attribute> <xsl:attribute name="rating"> <xsl:value-of select="$rating"/> </xsl:attribute> <xsl:apply-templates/> </xsl:element> </xsl:template>

<xsl:template match="cd"> <xsl:element name="cd-title"> <xsl:value-of select = "title" /> </xsl:element> </xsl:template> </xsl:stylesheet> </mulexml:xslt-text> <mulexml:context-property key="title" value="#[header:ListTitle]"/> <mulexml:context-property key="rating" value="#[header:ListRating]"/> </mulexml:xslt-transformer>

<model name="main"> <service name="Echo"> <inbound> <!-- this endpoint is used by the functional test --> <vm:inbound-endpoint path="test.in" transformer-refs="xslt" synchronous="true"/> </inbound> <echo-component/> <outbound> <pass-through-router> <stdio:outbound-endpoint system="OUT"/> </pass-through-router> </outbound> </service> </model></mule>

Testing the Transformer

This transformer can be tested using the following functional test. Note that it uses FunctionalTestCase,which is part of Mule's Test support.

Click here to expand...

Page 520: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 520

public class XSLTWikiDocsTestCase extends FunctionalTestCase{ protected String getConfigResources() { return "org/mule/test/integration/xml/xslt-functional-test.xml"; }

public void testMessageTransform() throws Exception { //We're using Xml Unit to compare results //Ignore whitespace and comments XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreComments(true);

//Read in src and result data String srcData = IOUtils.getResourceAsString( "org/mule/test/integration/xml/cd-catalog.xml", getClass()); String resultData = IOUtils.getResourceAsString( "org/mule/test/integration/xml/cd-catalog-result-with-params.xml", getClass());

//Create a new Mule Client MuleClient client = new MuleClient();

//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));

//Invoke the service MuleMessage message = client.send("vm://test.in", srcData, props); assertNotNull(message); assertNull(message.getExceptionPayload()); //Compare results assertTrue(XMLUnit.compareXML(message.getPayloadAsString(), resultData).similar()); } }

Page 521: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 521

Using Mule with Spring

This page last changed on Nov 21, 2008 by tcarlson.

Using Mule with Spring

Mule and Spring can integrate on different levels. You can can choose as much or little Mule in yourSpring application or Spring in your Mule application. The following pages describe in detail how you canuse Mule and Spring together.

• XML ConfigurationThe default way to configure Mule is via a Spring 2.0 XML file.

• Spring Application ContextsDescribes different options for how Mule creates and manages Spring Application Contexts.

• Using Spring Beans as Service ComponentsHow to configure Spring beans as service components in Mule.

• Sending and Receiving Mule Events in SpringA really easy way for your beans to send and receive Mule events via the Spring Application Contextwithout any code changes.

• Spring RemotingAn example of accessing Mule from an external application using Spring remoting.

Additionally, there are two Spring-related projects in the Developer Sandbox.

Page 522: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 522

Sending and Receiving Mule Events in Spring

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

Sending and Receiving Mule Events in Spring

You can configure Spring beans to publish events to Mule and configure Spring event listeners to receiveMule events. This page describes how to set up the configuration.

Spring Events Overview

Spring provides a simple mechanism for sending and receiving events between beans. To receive anevent, a bean implements ApplicationListener, which has a single method:

public void onEvent(ApplicationEvent event);

To publish events to listeners, you call the publishEvent() method on the ApplicationContext. This willpublish the same event to every listener in the context. You can also plug in custom event handlers to theapplication context.

Mule Events in Spring

To start receiving Mule events, you create a bean based on MuleEventMulticaster in your Muleconfiguration file. This class is an Application Event Multicaster that enables Spring beans to send andreceive Mule events. You also add one or more endpoints on which to receive events:

xmlns:spring="http://www.springframework.org/schema/beans"...<spring:beans> <spring:bean id="applicationEventMulticaster" class="org.mule.module.spring.events.MuleEventMulticaster"> <spring:property name="subscriptions"> <spring:list> <spring:value>jms://my.queue</value> <spring:value>pop3://ross:[email protected]</value> </spring:list> </spring:property> </spring:bean></spring:beans>

With this configuration, any emails received for [email protected] or any JMS messages sent tomy.queue will be received by all Spring event listeners. Note that the MuleEventMulticaster doesnot interfere with normal Spring event behavior. If a non-Mule applicationEvent is sent via theApplicationContext, all beans registered to receive events will still get the event.

The inbound endpoints can be any valid Mule Endpoint, so you can receive JMS messages, SOAPrequests, files, HTTP and servlet requests, TCP, multicast, and more.

Adding Bean Subscriptions

You can have beans subscribe only to relevant events. The MuleSubscriptionEventListener includes twomethods for getting and setting an array of endpoints on which the bean will receive events.

package org.mule.module.spring.events;public class TestSubscriptionEventBean extends TestMuleEventBean implements MuleSubscriptionEventListener

Page 523: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 523

{ private String[] subscriptions; public void setSubscriptions(String[] subscriptions) { this.subscriptions = subscriptions; } public String[] getSubscriptions() { return subscriptions; }}

You configure this bean like any other bean:

xmlns:spring="http://www.springframework.org/schema/beans"...<spring:beans> <spring:bean id="subscriptionBean" class="org.mule.module.spring.events.TestSubscriptionEventBean"> <spring:property name="subscriptions"> <spring:list> <spring:value>vm://event.*</value> </spring:list> </spring:property> </spring:bean></spring:beans>

Publishing Events to Mule

Publishing events is just as easy as receiving them. You use the standard publishEvent() method onthe application context. Your bean can get a reference to the application context by implementingApplicationContextAware or by querying MuleApplicationEvent .

//Create a new MuleEvent.Object message = new String("This is a test message");MuleApplicationEvent muleEvent = new MuleApplicationEvent( message, "jms://processed.queue");

//Call publishEvent on the application context, and Mule does the restapplicationContext.publishEvent(muleEvent);

For more information on publishing events, see the Error Handler Example.

Page 524: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 524

Spring Application Contexts

This page last changed on Mar 05, 2009 by jackie.wheeler.

Spring Application Contexts

[ Single Application Context ] [ Multiple Application Contexts ] [ Using an Existing Application Context ] [Using an Existing Application Context as Parent ]

This page describes the options available for controlling how Mule creates and manages Springapplication contexts for your application.

Single Application Context

By default, Mule will combine all resource files into a single ApplicationContext, whether they are"pure" Spring files or Mule configuration files. For example, the following code will create a singleapplication context consisting of the objects in spring-beans.xml plus the objects in mule-config.xml:

MuleContext muleContext = new DefaultMuleContextFactory().createMuleContext();

ConfigurationBuilder builder = new SpringXmlConfigurationBuilder("spring-beans.xml, mule-config.xml");builder.configure(muleContext);

muleContext.start();

Or, in a more abbreviated form:

MuleContext muleContext = new DefaultMuleContextFactory().createMuleContext( new SpringXmlConfigurationBuilder("spring-beans.xml, mule-config.xml"));muleContext.start();

Multiple Application Contexts

(Since 2.1.0) You can instruct Mule to create a separate application context for each Mule configurationfile. The following code will create two application contexts, one for each configuration resource:

MuleContext muleContext = new DefaultMuleContextFactory().createMuleContext();

ConfigurationBuilder builder1 = new SpringXmlConfigurationBuilder("spring-beans.xml");builder1.configure(muleContext);

ConfigurationBuilder builder2 = new SpringXmlConfigurationBuilder("mule-config.xml");builder2.configure(muleContext);

muleContext.start();

Using an Existing Application Context

(Since 2.1.2) If you already have an application context, you can instruct Mule to use it as follows:

Page 525: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 525

ApplicationContext myAppContext = getMyAppContextFromSomewhereElse();

MuleContext muleContext = new DefaultMuleContextFactory().createMuleContext();

ConfigurationBuilder builder1 = new SpringConfigurationBuilder(myAppContext);builder1.configure(muleContext);

ConfigurationBuilder builder2 = new SpringXmlConfigurationBuilder("mule-config.xml");builder2.configure(muleContext);

muleContext.start();

Using an Existing Application Context as Parent

(Since 2.1.2) You can designate an existing application context as a parent context for Mule, so that theMule configuration can refer to and/or override beans in the application context:

ApplicationContext myAppContext = getMyAppContextFromSomewhereElse();

MuleContext muleContext = new DefaultMuleContextFactory().createMuleContext();

ConfigurationBuilder builder = new SpringXmlConfigurationBuilder("mule-config.xml");builder.setParentContext(myAppContext);builder.configure(muleContext);

muleContext.start();

As of Mule 2.2, the MuleXmlBuilderContextListener class checks to see if an application context(WebApplicationContext) has already been created by Spring, and if there is one, Mule uses it as theparent automatically.

Page 526: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 526

Using Spring Beans as Service Components

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

Using Spring Beans as Service Components

[ Defining the Beans ] [ Configuring the Beans ] [ Configuring the Component ] [ Using JNDI and EJBSession Beans ]

You can construct service components from Spring beans that you define in a separate Springcontext file or right in the Mule configuration file. This pages provides an example using two beans; aRestaurantWaiter bean that receives and logs orders and then passes them to the KitchenService bean,which receives the orders.

Defining the Beans

The Java code for the beans look like this:

public class RestaurantWaiter{ private KitchenService kitchen = null;

public void takeOrder(Order order) { //log order

//notify kitchen this.kitchen.submitOrder(order); }

public void setKitchenService(KitchenService kitchen) { this.kitchen = kitchen; }

public KitchenService getKitchenService() { return kitchen; }}

Configuring the Beans

First, you configure the beans in your Spring application context:

<beans> <bean id="restaurantWaiter" scope="prototype" class="com.foo.RestaurantWaiter"> <property name="kitchenService"> <ref local="kitchenService"/> </property> </bean>

<bean id="kitchenService" class="com.foo.KitchenService"/></beans>

We now have beans called restaurantWaiter and kitchenService that will be created by Spring. Noticethe resturantWaiter bean scope is set to prototype (by default, all beans in Spring are singletons unlessspecified otherwise). This is important because Mule will pool your components, and telling Spring not tocreate a singleton ensures that each pooled instance will be a unique instance.

Page 527: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 527

If you want to configure the beans right in your Mule configuration file instead of in a separate Springcontext file, you could specify them like this:

xmlns:spring="http://www.springframework.org/schema/beans"...<spring:beans> <spring:bean id="restaurantWaiter" scope="prototype" class="com.foo.RestaurantWaiter"> <spring:property name="kitchenService"> <spring:ref local="kitchenService"/> </spring:property> </spring:bean> <spring:bean id="kitchenService" class="com.foo.KitchenService"/></spring:beans>

Configuring the Component

After you have configured the beans, you can create your reference to restaurantWaiter inthe component. For example, the following configuration creates a component that will enablerestaurantWaiter to receive events from VM. This example assumes the beans are in a separate file, so ifyou configured them right in the Mule configuration file, you do not need the <spring:import> tag.

xmlns:vm="http://www.mulesource.org/schema/mule/vm/2.0" xmlns:spring="http://www.springframework.org/schema/beans"...<spring:import resource="conf/applicationContext.xml"/>...<service name="Restaurant Waiter"> <inbound> <vm:inbound-endpoint path="order.queue"/> </inbound> <pooled-component> <spring-object bean="restaurantWaiter"/> </pooled-component></service>

When the Mule server starts, each of the <service> elements are loaded, and the bean you specified inthe <spring-object> tag is created. When an event is received on vm://orders.queue, an Order objectis passed to the takeOrder() method on the RestaurantWaiter, which then logs the order and passes itto the KitchenService.

For more information on component configuration, see Configuring Components. For more information onthe elements you use to configure components, see Component Configuration Reference.

Using JNDI and EJB Session Beans

If you define JNDI and EJB session beans in Spring using the generic <bean> element, you configurethem exactly as any other Spring bean in Mule. However, if you use the <jee> elements to define themin Spring (<jee:jndi-lookup>, <jee:local-slsb>, and <jee:remote-slsb>), you must include the jeenamespace and schema locations in your Mule configuration file as follows:

xmlns:jee="http://www.springframework.org/schema/jee" xsi:schemaLocation="...http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd"...<jee:remote-slsb id="creditAgencyEJB" jndi-name="local/CreditAgency"

Page 528: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 528

business-interface="org.mule.example.loanbroker.credit.CreditAgency"> <jee:environment> java.naming.factory.initial=org.openejb.client.LocalInitialContextFactory java.naming.provider.url=rmi://localhost:1099 openejb.base=${openejb.base} openejb.configuration=${openejb.configuration} logging.conf=${logging.conf} openejb.nobanner=${openejb.nobanner} </jee:environment> </jee:remote-slsb>...<mule:service name="CreditAgencyService"> <mule:inbound> <mule:inbound-endpoint ref="CreditAgency" /> </mule:inbound> <mule:component> <mule:spring-object bean="creditAgencyEJB" /> </mule:component></mule:service>...

For more information, see Enterprise Java Beans (EJB) integration and the jee schema reference on theSpring site.

Page 529: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 529

Using the Mule Client

This page last changed on Feb 26, 2009 by jackie.wheeler.

Using the Mule Client

[ Using Send and Dispatch ] [ Configuring the Mule Client ] [ MuleClient as a Web Services Client ] [Performing an Event Request Call ] [ Associating Properties with the Message ] [ When Not to Use theMule Client ] [ Handling Message Collections ] [ Future Results ] [ Using the Remote Dispatcher ] [Sending Messages to Components Directly ]

In most Mule applications, messages are triggered by an external occurrence such as a message beingreceived on a queue or a file being copied to a directory. However, if you want to send and receivemessages programmatically, you can create a Mule client.

The Mule client is a simple interface for Java clients to send and receive messages from a Mule server andother applications. The client serves the following functions:

• Sending and receiving messages to and from a local or remote Mule server• Communicating with other applications using any Mule transport• Making requests to a Mule server behind a firewall using the RemoteDispatcher

The Mule client can be used as a web services client to make SOAP requests using popular SOAPimplementations such as Apache CXF. It can also send messages directly to a service component andbypass the transports layer completely, which is useful for testing your service components or whentriggering an event from a script or JSP page.

The Mule client can be used with any of the Mule transports, making it a universal client for many typesof transports such as JDBC, JMS, FILE, POP3, XMPP, HTTP, etc.

The following sections describe how to use the MuleClient in various scenarios.

Using Send and Dispatch

The Mule client allows the user to send and receive messages programmatically. For example, to send aJMS message to any application or Mule component listening on my.queue, you can use the dispatch()method. The dispatch() method provides the ability to "fire and forget" messages over an endpoint.

MuleClient client = new MuleClient();client.dispatch("jms://my.queue", "Message Payload" null);

To make a regular synchronous call to a service and receive a result, you can use the send() method:

MuleClient client = new MuleClient();MuleMessage result = client.send("tcp://localhost:3456", "Message Payload", null);

The client send() and dispatch() methods expect the following arguments:

1. The Mule URL endpoint: any valid Mule Endpoint used to determine the transport, endpoint, andother information about delivery of the message. This can also be an endpoint name stored inconfiguration.

2. The message payload: any object carried by the message.3. Properties: any properties or meta-data to associate with the message being sent

Don't use physical endpoints in your code

Page 530: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 530

For clarity, the examples on this page use a physical endpoint URI, such as jms://myQueue.However, it is much better practice to define all your endpoints inside a Mule configurationfile using the <endpoint> tag and then reference those endpoint names in your code.

Configuring the Mule Client

If you are using the Mule client in the same classloader (e.g., a Web App or Mule stand-alone), the clientwill have access to the server configuration. For example, if you had some endpoints defined in yourserver configuration file:

<http:endpoint host="192.168.0.1" port="80" path="/services" name="serviceEndpoint"/>

This endpoint will be accessible by the Mule client:

MuleClient client = new MuleClient();client.dispatch("serviceEndpoint", dataObject, null);

Essentially, the Mule client will have the same configuration information as the Mule server, since they willboth have access to the same registry.

If you are running the Mule client in stand-alone mode, you can still configure it using its own Mule XMLconfiguration file(s). You pass in these files when the client is created:

MuleClient client = new MuleClient("http-client-config.xml, shared-client-config.xml");client.getMuleContext().start();

Note that you must start the local Mule context used by the client. You can also create your own Mulecontext and pass it into the client:

//Create a MuleContextFactoryMuleContextFactory muleContextFactory = new DefaultMuleContextFactory();

//create the configuration builder and optionally pass in one or more of theseConfigurationBuilder builder = new SpringConfigurationBuilder("http-client-config.xml, shared-client-config.xml"));//The actual context builder to useMuleContextBuilder contextBuilder = new DefaultMuleContextBuilder();

//Create the contextMuleContext context = muleContextFactory.createMuleContext(builder, contextBuilder);

//Start the contextcontext.start();

//Create the client with the contextMuleClient client = new MuleClient(context);

MuleClient as a Web Services Client

The Mule client can be used as a web services client to make SOAP requests using popular SOAPimplementations such as Apache Axis or CXF.

Page 531: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 531

MuleClient client = new MuleClient();

//Arguments for the addPerson WS methodString[] args = new String[]{"Ross", "Mason"};

//Call the web serviceclient.dispatch("axis:http://localhost:38004/PersonService?method=addPerson", args, null);

//Call another method to look up the newly added personMuleMessage result = client.send ("axis:http://localhost:38004/PersonService?method=getPerson", "Ross", null);

//A person object is returned, and all type mapping is handled for youPerson person (Person)result.getPayload();

System.out.println(person.toString());

The Mule SOAP Transport supports Apache Axis and CXF. For more information about Mule Axis support,see Axis Web Services and Mule.

Performing an Event Request Call

Making a request to an endpoint is useful when using a transport that has a store of events that you wantto request rather then have a listener on the resource.

To make a request for a message, use the request() method:

MuleClient client = new MuleClient();MuleMessage result = client.request("pop3://ross:[email protected]", 5000);

This code will attempt to receive a message from a mailbox called ross on mail.my.org and will returnafter five seconds if no message was received. Calling request() works for all Mule supported transports,but it is more usual to make event request calls where there is a store to be queried such as a queue, filedirectory, or some other repository.

Associating Properties with the Message

The previous examples set the properties argument to null. Properties can be arbitrary, such as to passaround custom metadata with your messages, or they can be transport-specific. The following exampledemonstrates an asynchronous request/response using JMS and the JMS-specific JMSReplyTo property.When the JMSReplyTo is set, it is stated in the JMS spec that a receiver of the message should send backany results to the destination defined in the JMSReplyTo header. Mule does this for you.

//create the client instanceMuleClient client = new MuleClient();

//create properties to associate with the messageMap props = new HashMap();

//Set the JMSReplyTo property, which is where the response message will be sentprops.put("JMSReplyTo", "replyTo.queue");

//dispatch the message asynchronouslyclient.dispatch("jms://test.queue", "Test Client Dispatch message", props);

Page 532: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 532

//Receive the return message on the replyTo.queueMuleMessage message = client.request("jms://replyTo.queue", 5000);

//This is the message sent back from the first component to process our messageSystem.out.println(message.getPayload());

When Not to Use the Mule Client

It's generally not good practice to make calls using the Mule client from your service objects or withinextensions to Mule such as routers or transformers.

When you need to dispatch or request events in Mule, you should use the currentorg.mule.api.MuleEventContext and call the send/dispatch/request methods on the context instead.

To gain access to the MuleEventContext inside your services, you can implement theorg.mule.api.lifecycle.Callable interface.

If you need to make an event request from a transformer, filter, or interceptor, you should reconsider yourdesign strategy for that event flow.

Handling Message Collections

Since Mule 2.1, some outbound routers such as the Message Splitter, Multicaster, and Recipient List mayreturn more that one result message in the following cases:

• There is more than one endpoint configured on the router• More than one of the endpoints has the synchronous=true attribute set

To handle situations where multiple results occur, Mule has introduced a new message typeorg.mule.api.MuleMessageCollection . This type of message contains all message results in the order theywere received. Note that org.mule.api.MuleMessageCollection extends org.mule.api.MuleMessage , sothe interface is similar. If there are multiple results, the MuleMessage.getPayload() method returns ajava.util.List containing the payloads of each of the returned messages.

When using the Mule client, you can cast the message return type to get access to all MuleMessageobjects.

MuleClient client = new MuleClient();MuleMessage result = client.send("myEndpoint", "some data", null);

if(result instanceof MuleMessageCollection){ MuleMessageCollection resultsCollection = (MuleMessageCollection)result; System.out.println("Number of messages: " + resultsCollection.size()); MuleMessage[] messages = resultsCollection.getMessagesAsArray();}

Future Results

The Mule client allows you to make synchronous calls without blocking by using the sendAsync() method,which returns a FutureMessageResult that can be queried later.

MuleClient client = new MuleClient();FutureMessageResult result = client.sendAsync("http://localhost:8881", "Message Payload", null);//Do some more stuff here

Page 533: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 533

if(result.isready()) { Object payload = result.getMessage().getPayload();}

The FutureMessageResult returned is a placeholder for the real result message when the call returns.By using a future result, you can continue with other tasks while the remote call executes. CallinggetMessage() will block until the call returns. Optionally, you can specify a timeout of how long to wait(as shown in the example). You can also check if the call has returned using result.isReady().

Using the Remote Dispatcher

The Mule client can connect to, send, and receive messages from a remote Mule server through afirewall using a remote dispatcher. This should only be used when the remote service being invoked doesnot expose an endpoint accessible by the Mule client. Note that there is performance overhead whenusing the remote dispatcher, because all requests and responses are serialized, sent to the server, anddeserialized before the real invocation is made from within the firewall.

To use the remote dispatcher, you enable it on the server instance by configuring the remote dispatcheragent. You can ensure that the server can handle both asynchronous and synchronous calls by setting thesynchronous attribute to true. You can also set the responseTimeout setting, although often it is betterto control it at the MuleClient call level, as each call might have a different timeout requirement.

<?xml version="1.0" encoding="UTF-8"?><mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:client="http://www.mulesource.org/schema/mule/client/2.2" xsi:schemaLocation=" http://www.mulesource.org/schema/mule/client/2.2 http://www.mulesource.org/schema/mule/client/2.2/mule-client.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd"> ... <client:remote-dispatcher-agent> <client:remote-endpoint address="http://localhost:81" synchronous="true" responseTimeout="10000"/> </client:remote-dispatcher-agent> ...</mule>

On the client side, you can now communicate with the remote server via the remote dispatcher agent.For example:

MuleClient client = new MuleClient();RemoteDispatcher dispatcher = client.getRemoteDispatcher("http://localhost:81");

MuleMessage result = dispatcher.sendToRemoteComponent("StockManager", "give me the price of XXX", null);

StockQuote sq = (StockQuote)result.getPayload();

The Mule client executes the StockManager component on a remote Mule server, returning the result tothe client. Mule handles all the call marshalling. The first null argument is an optional string of comma-separated transformers to use on the result message. The second null argument contains propertiesassociated with the request.

If you do not want to wait for the result to be returned from the remote server, you can use thesendAsyncToRemoteComponent() method, which returns a FutureMessageResult:

Page 534: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 534

MuleClient client = new MuleClient();RemoteDispatcher dispatcher = client.getRemoteDispatcher("tcp://localhost:60504");FutureMessageResult result = dispatcher.sendAsyncToRemoteComponent("StockManager", null, "give me the price of XXX", null);

//do some other stuff

StockQuote sq = (StockQuote)result.getMessage(1000).getPayload();

Specifying the Wire Format

You can specify the wire format to use for dispatching messages by configuring one of the following:

• <xml-wire-format>: uses the XML-Object transformers• <serialization-wire-format>: uses the ByteArray-Serializable transformers• <custom-wire-format>: set the class attribute to the class file of the transformer you want to use.

If you do not set the wire format, the serialization format is used. For more information on transformers,see Using Transformers.

For example:

<?xml version="1.0" encoding="UTF-8"?><mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:client="http://www.mulesource.org/schema/mule/client/2.2" xsi:schemaLocation=" http://www.mulesource.org/schema/mule/client/2.2 http://www.mulesource.org/schema/mule/client/2.2/mule-client.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd"> ... <client:remote-dispatcher-agent> <client:remote-endpoint address="http://localhost:81" synchronous="true" responseTimeout="10000"/> <client:xml-wire-format/> </client:remote-dispatcher-agent> ...</mule>

Sending Messages to Components Directly

The Mule client provides a convenient way to send a message directly to a component without needingto use a transport when the Mule server is running in the same classloader as the client. This approachcan be very useful in testing as well as triggering messages from a JSP page or JavaScript. For example,to dispatch a message directly to your stock quote component called StockManager, you would do thefollowing:

MuleClient client = new MuleClient();MuleMessage result = client.sendDirect("StockManager", null, "give me the price of XXX", null);

StockQuote sq = (StockQuote)result.getPayload();

Page 535: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 535

Note that the call is sendDirect, which tells the Mule client to go directly to the component and notthrough a transport. You can specify a comma-separated list of transformers to use in the secondargument of this call.

Page 536: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 536

Using the Mule RESTpack

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

Using the Mule RESTpack

[ Understanding REST ] [ Architecting RESTful Applications ] [ Mule REST Connectors ]

The Mule RESTpack is geared toward helping you build RESTful applications with Mule. REST is a verypowerful concept that enables scalable, decentralized growth.

Understanding REST

REST can be confusing. For an introduction to its advantages, disadvantages, and notes on using it, seeMaking Sense of REST.

Architecting RESTful Applications

Mule is well suited for building RESTful applications, as it can easily bridge between the web and nearlyanything else in your enterprise. For more information on architecture considerations when using RESTwith Mule, see Architecting RESTful HTTP applications.

Mule REST Connectors

The Mule RESTpack uses a series of connectors for building RESTful services. This section describes eachconnector and links to more information on downloading and using them.

HTTP Connector

The Mule HTTP Transport contains most of the basic HTTP functionality that the connectors in theRESTpack build on, including:

• Client and Server HTTP transport• Support for running over a Servlet• Support for polling resources via the PollingHttpMessageReceiver

The Mule HTTP transport is included with your Mule installation.

Apache Abdera Connector

The Mule Abdera connector makes it possible to integrate easily with Atom feeds and Atom PublishingProtocol servers via the Apache Abdera project. The connector supports consuming Atom feeds,publishing of Atom entries and server side AtomPub service.

To download and learn about using the Mule Abdera connector, go to the MuleForge Abdera page.

Jersey JAX-RS Connector

Jersey is the open source JAX-RS (JSR 311) reference implementation for building RESTful web servicesvia simple annotations. The Mule Jersey connector enables developers to embed these JAX-RS servicesinside of Mule.

To download and learn about using the Mule Jersey connector, go to the MuleForge Jersey page.

Restlet Connector

Restlet is an open source REST framework, providing a powerful abstraction for building and consumingRESTful services. The Mule Restlet connector facilitates the deployment and consumption of RESTful

Page 537: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 537

services using the Restlet APIs inside of Mule. In addition, the transport exploits Restlet's simple URLrouting engine to provide RESTful routing of messages to Mule services.

To download and learn about using the Restlet connector, go to the MuleForge Restlet page.

Page 538: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 538

Architecting RESTful HTTP applications

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

Architecting RESTful HTTP Applications

[ Modeling services and data ] [ Reliability ] [ Security ]

Modeling services and data

An important step in achieving the benefits REST has to offer is modeling your services and datacorrectly. It is very different from the typical RPC (Remote Procedure Call) mindset that most people areused to. It is however similar to object-oriented programming.

Imagine that each resource is an object. You can then perform the following operations on this object:

Operation Description

Get() Get a representation of the resource. This is asafe operation. It does not change the state of theresource.

Post(Representation) Perform an unsafe operation that changes thestate of the server and puts a new resourcessomewhere or modifies an existing resource.

Put(Representation) Store a new representation of the resource.

Delete() Delete the resource

Head() Get metadata about the resource. This is a safeoperation. It does not change the state of theresource

Options() Get information about which operations areavailable to be used on the resource. This is asafe operation. It does not change the state of theresource.

Modeling your application can be broken down into roughly four steps:1. Decompose your application into resources whose state you wish to access and modify.2. Define the applicable operations of each resource3. Give each resource a URI4. Decide how to represent each resource

Decompose the application into resources

Anything inside your application can be a resource. So how do you decide what resources to create?Typically you'll want to make a piece of your application a resource if:1. You wish to link to that specific piece of data2. You wish to modify or delete the data the resource represents

The prototypical example is often a CRUD based application. For instance, you may have a database oforders which need to be fulfilled. If this was to be broken down into resources, you may have a "/orders"URI for listing the contents of the orders database. You would also have an individual resource for eachorder (i.e. "/order/1") which could be accessed, modified or deleted.

Page 539: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 539

Give Each Resource a URI

Define the applicable methods of each resource

After (or while) breaking down your application into resources, you must determine which HTTP methodsyou wish to support. It is very important that you respect the semantics of each HTTP method. GET,HEAD, and OPTIONS are safe. PUT and DELETE are idempotent. POST is unsafe and may have side-effects.

See the section on reliability for an explanation of how to apply these methods to build a robust service.

Decide how to represent each resource

There are many different data types you can choose to represent your resource. Many times you will nothave to think about what data type to use as it will be obvious. For instance, if you store an image of aproduct in the database - the typical way to serve that would be return an image type, i.e. "image/jpeg".A structured data type such as XML would make no sense.

For structured data, the choices are more complex. There is XML, specific formats of XML such as Atom,JSON, XHTML, CSV, etc. On top of this, you may wish to multiple different representations of the resourceas well.

The most common formats for structured data are XML, Atom, JSON and XHTML. The table below gives aquick summary of these formats and when you may wish to consider applying them.

XMLXML is the universal data format. Every system can understand it. It also has advanced tools formodeling, parsing and querying such as XML schema, XPath, and XQuery. It is typically slower than otherformats as it is verbose, but can perform well for most applications.

AtomAtom is a standard XML format for syndication. An Atom feed contains a series of entries. Each entry hasa place for a title, last update time, summary, content, authors, and more. It also allows extensions forproprietary fields. Atom inherits all the benefits of XML, but introduces another very important property- it is universally understood. If a user or machine understands Atom, it automatically understands yourapplication to some degree.

JSONJSON stands for JavaScript Object Notation. One of its great advantages is that it is itself JavaScript. Thismeans that it becomes trivial to parse and use JSON inside a JavaScript application - especially whencompared to navigating XML. It is also extremely simple. It does not have the concept of namespaces nordoes it have modeling tools XML schema.

XHTMLOver the recent years Microformats have arise as a very powerful alternative to XML based data.Microformats create a standard XHTML representation for data which allows it to both be parsed reliablyby machines and be used inside a web browser. Consider using a data format whenever possible as itoften allows you to tackle two birds with one stone.

Reliability

An important part of distributed system design is dealing with problems that occur in between the clientand the server it is talking to. Some examples of this include proxies going down or connections beingdropped.

HTTP does not have an inbuilt mechanism for achieving reliable deliveries of messages. Instead, reliabilityis typically achieved through idempotent operations. An idempotent operation is one that can be repeatedover and over and still yield the same result. In the case of HTTP, this means that a message can be sentagain and again until confirmation is received. Even if the message is received twice, the ultimate result,changing the resource state, will be the same.

Let us say that you want to update a resource which represents a customer - maybe they've changedtheir address. In this case you would want to PUT the new representation to this resource which contains

Page 540: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 540

the new address. If a connection drops and an error occurs, you can simply try putting the messageagain as the operation is idempotent.

The same concept can be applied to the DELETE operation. The DELETE request can simply be repeated itsucceeds.

Creating new resources is trickier to do reliably in a RESTful manner. Typically resources are createdwith a POST message. A simple example might go like this: you create a new order by POSTing therepresentation to the "/orders" resource. You would then be redirected to the new resource. Whathappens if the connection drops here though? You are not sure if the new order resource has beencreated. If you simply retry the POST you could end up with two orders, which would be less than idea.The trick is to use a two step process. First, the client must do a POST to the "/orders" resource with nodata. The server will then respond with a Location header which contains a new URL that the order can bePUT to.

TODO: put code example in confluence

Now reliability can be achieved by simply repeating each step until it succeeds. If the POST fails and theclient submits the POST again, the worst that can happen is the creation of a URL that is not used. TheseURLs can either be ignored or they can be expired. If the PUT fails, it can simply be retried.

There is a limitation of the above approach for reliability though - message ordering is not preserved.To preserve message ordering, you will have to develop application specific extensions or move to atechnology like HTTPR or WS-ReliableMessaging.

Security

There are many options to provide security to your application depending on your requirements.

Authentication

HTTP has built in support for authentication. The "basic" and "digest" mechanisms are the mostcommonly used authentication mechanisms. Basic authentication passes a username and passwordin plain text to the server. Because of this, it should only be used over an SSL connection. Digestauthentication sends the username as plain text and an MD5 checksum of the password.

Another option for authentication is to use client side certificates with SSL. If the server has a copy of theclient's public key, it can verify that the messages were in encrypted with that key, and hence from theclient.

Privacy

The most often used mechanism for message privacy is SSL. It is efficient and widely supported. Otheralternatives include the message level security mechanisms mentioned below.

Limitations of SSL

There are two primary limitations of using SSL. First, it does not work well with intermediaries. Imaginea situation where a gateway handles the SSL processing. In this case, your application will receive noneof the SSL information. This means you cannot use SSL certificates to verify who the client/server isand that there may be unsecured routes along the network. Second, there is limited ability for otherauthentication tokens, such as SAML.

Message level security

If you need message level security XML Signature/Encryption is one of your few options. This doesconstrain you to use an XML data format though.

Another option that has been discussed is S/MIME. This has many disadvantages to it though which arediscussed here.

Page 541: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 541

Making Sense of REST

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

Making Sense of REST

[ Advantages of RESTful Architectures and Implementations ] [ Disadvantages of RESTful Architecturesand Implementations ] [ Notes on Building Your Application with WS-* or RESTful HTTP ]

REST is the formalized architecture of HTTP based on the concepts of resources, links, and a uniforminterface. REST can be a somewhat confusing subject. Even the very acronym itself, which stands for"Representation State Transfer", is a little obtuse. Luckily, there are some great resources out there.

One of the best resources out there is RESTful Web Services by Leonard Richardson and Sam Ruby.It explains REST as well as many of the practical issues surrounding the issue of building RESTful webservices in great detail. You can find it at your local bookstore, Amazon, or online at O'Reilly's Safariwebsite.

For a good online (and free) introduction, Stefan Tilkov has written two excellent articles: A BriefIntroduction to REST and Addressing Doubts about REST.

And of course, there is the authoritative, but dense, thesis by Roy T. Fielding

You should familiarize yourself with the concepts of REST before continuing to read this page.

Advantages of RESTful Architectures and Implementations

Following is a discussion of some key benefits of RESTful architectures and implementations. Note thatwhile many of these items are benefits of the REST architectural style, many are related to HTTP, which isa specific implementation of the REST concepts.

REST Is the Architecture of the Web

RESTful applications can be easily integrated in the web to great benefit. Your resources can be linked toand from web pages. You can take advantage of Microformats to handle both UI and data related issues.You can also take advantage of the existing web infrastructure and ecosystem: proxies, caches, browsers/clients, load balancers, web standards, and more.

Increased Scalability

The web is the largest distributed system in the world. This is enabled by the inherent constraints inRESTful architectures. For example, RESTful interactions are stateless. The server does not have to worryabout managing state between requests, as all state is kept on the client. Also, caching semantics arebuilt into the protocol. You can enable caching on any RESTful application without any special knowledgesince all interactions are based on the uniform interface.

Evolvability

All resources are identified by URIs. URIs provide a simple way to deal with the evolution of a systemas they can be used to partition servers and manage versioning. All one needs is a proxy to doredirects based on the URI. Because there is no need to inspect the actual HTTP message payload, theperformance impact of this is negligible.

RESTful systems are based on hypermedia, so they provide links between different resources. Clients areresponsible for navigating the hypertext links. For instance, they browse to an order resource. They maythen browse to different items in the order via a link. If you need to direct a client to a different server ormove a server, simply change the link. Because the client knows the entry point link, it can still navigateto the various items as your system evolves.

Page 542: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 542

Disadvantages of RESTful Architectures and Implementations

This section describes the disadvantages to the REST approach.

Not Applicable to Many Message-oriented Situations

RESTful systems are fundamentally client-server based and are ill-suited to a number of message-oriented scenarios. Publish-subscribe scenarios are one example. As there is no mechanism inside HTTPfor asynchronous responses, you often have to set up a second HTTP server if you want to receiveasynchronous replies.

Performance

HTTP is fundamentally a text-based protocol and is not geared toward performance. While it is not slow,there are other protocols that may be more suitable for situations that are very performance-sensitive.

Transactions

HTTP does not include the concept of transactions. It is possible to model a transaction as an HTTPresource, but it will not be as efficient as protocols such as JMS. It is also not appropriate to usetransactions with HTTP in many cases, as it can potentially consume many resources across multipleservers if transactions are long lived.

Notes on Building Your Application with WS-* or RESTful HTTP

WS-* represents common names for the set of standards that encompass SOAP, WSDL, WS-Addressing,WS-Security, WS-ReliableMessaging, WS-Policy, and many others. One cannot compare WS-* and RESTdirectly, as WS-* is a set of technology standards and REST is an architectural style. However, you cancompare the actual pieces of software that help you build RESTful systems and traditional web services.

Go Beyond XML

SOAP/WSDL web services are XML based. To create messages that encapsulate binary data, you mustuse standards such as MTOM that wrap the XML in a MIME message, which often ends up being extrawork. With HTTP, resources can be any media.

Transport Neutrality

One of the great benefits of SOAP is that it is transport neutral. If this is a requirement for yourapplication, RESTful services are probably not the way to go.

Reliability

The RESTful and WS-* approaches to reliability differ tremendously.The WS-* approach is based on WS-ReliableMessaging (WS-RM). WS-RM implements a TCP-likesystem of acknowledgments: messages are sent from server A to server B, and server B then sendsacknowledgments back. If server A never receives an acknowledgment for a message, it eventuallyresends it. WS-ReliableMessaging implementations (not the protocol) can also ensure messages aredelivered in the correct order.

RESTful systems typically achieve reliability through idempotent operations. See the section on RESTfulreliability for more information.

Security

The RESTful and WS-* approaches to security also differ greatly. WS-* advocates a layered approach. Itcreates WS-Security for encryption and authorization, it uses WS-Trust for token exchange, and it usesWS-SecureConversation to create more efficient security tokens for encrypted communication. These

Page 543: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 543

approaches make sense if you need message-oriented, transport-neutral systems. However, many WS-*systems make use of the underlying transport security (such as SSL) for its simplicity and performance.

RESTful systems can achieve security through both the transport layer (SSL) and a variety of message-level mechanisms. Support for different security scenarios is arguably one of the reasons to choose WS-* instead of REST for some specific (but rare) scenarios. See the section on RESTful security for moreinformation on how to build secure RESTful services.

Page 544: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 544

Using Transformers

This page last changed on Mar 09, 2009 by jackie.wheeler.

Using Transformers

[ Configuring Transformers ] [ Inbound, Outbound, and Response Configurations ] [ ChainingTransformers ] [ Transformation Best Practices ] [ Available Transformers ]

Transformers convert message payloads as they are transported between services. Mule provides manystandard transformers, which you configure using predefined elements and attributes in your Mule XMLconfiguration file. You can also configure custom transformers using the <custom-transformer> element,in which you specify the fully qualified class name of the custom transformer class. For more informationon creating and configuring a custom transformer, see Creating Custom Transformers.

Standard transformers are easier to use than custom transformers. You don't need to know the Javaname of the transformer, and all properties are explicitly declared in a Mule configuration schema.Following is an example of declaring the standard Append String transformer, which appends string textto the original message payload:

<append-string-transformer name="myAppender" message=" ... that's good to know!"/>

If the original message payload was the string "foo", the transformer above would convert the string to"foo ... that's good to know!".

The Available Transformers section of this page describes all the standard transformers providedwith Mule. Additionally, many transports and modules have their own transformers, such as theObjectToJMSMessage transformer for the JMS transport.

Configuring Transformers

You can configure a transformer locally or globally. You configure a local transformer right on theendpoint where you want to apply it, whereas you configure a global transformer before the <model>element in your Mule configuration properties so you can then refer to the transformer in multiple places.

For example, the following code defines two global transformers, which are referenced from two differentservices:

<xm:xml-to-object-transformer name="XMLToExceptionBean" returnClass="org.mule.example.errorhandler.ExceptionBean"/> <custom-transformer name="ExceptionBeanToErrorMessage" class="org.mule.example.errorhandler.ExceptionBeanToErrorMessage" returnClass="org.mule.example.errorhandler.ErrorMessage"/>

...<model name="errorhandler-test"> <service name="Error Manager"> <inbound> <inbound-endpoint address="file://./test-data/in" transformer-refs="XMLToExceptionBean ExceptionBeanToErrorMessage"> <file:filename-wildcard-filter pattern="*.xml" /> </inbound-endpoint> </inbound> ... </service>... <service name="Business Error Manager"> <inbound>

Page 545: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 545

<inbound-endpoint address="jms://exception.queue" transformer-refs="XMLToExceptionBean ExceptionBeanToErrorMessage" /> </inbound> ... </service></model>

This example uses the transformer-refs attribute on the endpoint to specify the transformers to use.This is a fast way of specifying global transformers, but if you want to enter a local transformer or a mixof local and global transformers, you must use the <transformer> element instead. For example, if onlyone of the transformers were defined globally, you would refer to the global transformer and configurethe local transformer as follows:

<service name="Error Manager"> <inbound> <inbound-endpoint address="file://./test-data/in"> <transformer ref="XMLToExceptionBean/> <custom-transformer name="ExceptionBeanToErrorMessage" class="org.mule.example.errorhandler.ExceptionBeanToErrorMessage" returnClass="org.mule.example.errorhandler.ErrorMessage" /> <file:filename-wildcard-filter pattern="*.xml" /> </inbound-endpoint> </inbound> ... </service>

Inbound, Outbound, and Response Configurations

The above examples illustrate configuring inbound transformers, which are applied to the message afterit is received on the inbound endpoint and before it is passed to the service's component. You specifyinbound transformers under the <inbound-endpoint> element.

You can also specify an outbound transformer in exactly the same way but on <outbound> elementrouters, in which case the message is transformed after it has been processed by the service'scomponent but before it has been sent to the outbound endpoint specified by that router. For example:

<outbound> <filtering-router transformer-refs="ErrorMessageToException"> <file:outbound-endpoint path="test-data/exceptions" outputPattern="Exception-[UUID].xml" transformer-refs="ErrorMessageToExceptionBean ExceptionBeanToXML" /> </filtering-router>...</outbound>

Lastly, you can specify a response transformer, which converts response message payloads ontheir way from the service back to the caller. To configure a response transformer, you use theresponseTransformers-refs attribute on the router, or you can use the <response-transformer>element. For example:

<inbound> <vm:inbound-endpoint path="my.inbound.endpoint" responseTransformer-refs="myAppender"/></inbound>

Page 546: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 546

<some-component/>

In this example, the response message from "some-component" is transformed using the "myAppender"transformer before being returned to the caller. For more information on response messages and themessaging styles supported by Mule, see Mule Messaging Styles.

Chaining Transformers

You can chain transformers together so that the output from one transformer becomes the input for thenext. To chain transformers, you create a space-separated list of transformers in the transformer-refsor responseTransformer-refs attributes or by creating multiple <transformer> elements as shownabove.

For example, this chain ultimately converts from a ByteArray to InputStream:

transformer-refs="ByteArrayToString StringToObject ObjectToInputStream"

You could also configure this as follows:

<transformer ref="ByteArrayToString"/><transformer ref="StringToObject"/><transformer ref="ObjectToInputStream"/>

Note that if you specify transformer chains, any default transformers or discoverable transformers are notapplied. If you want to use those transformers, you must specify them explicitly with the other chainedtransformers.

Transformation Best Practices

Mule has an efficient transformation mechanism. Transformers are applied to inbound or outboundendpoints, and the data is transformed just before it is sent from a service or just before it is received byanother service. Transformers can be concatenated, so it is simple to perform multiple transformations ondata in transit.

There is no one standard approach for how and where transformations should occur. Some maintain thatbecause transformation should always be applied on inbound/outbound data, transformations should beavailable as part of the enterprise service bus instead of inside the service components. This approachmatches the concepts of Aspect Oriented Programming (AOP). Others conclude that it is far more efficientto encode the transformation logic into the service components themselves. In the second case, however,there is no distinction between code that is related to a business process and code that is generic enoughto be reused, which contradicts the philosophy of an ESB.

While there is no industry best practice, MuleSource recommends that developers examine theirtransformation logic to see if it will always be used (AOP) or if it is specific to a business process. Ingeneral, if it will always be used, you should use a transformer, and if it is specific to a single businessprocess, it should be part of the service component.

Note the following cases where you should not configure a transformer:

• Default transformers: some transports have default transformers that are called by default, but onlyif you don't configure explicit transformations.

• Discoverable transformers: some transformers can be discovered and used automatically basedon the type of message. You do not configure these transformers explicitly. These include customtransformers that have been defined as discoverable. For more information, see Creating CustomTransformers.

Page 547: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 547

References: http://msdn2.microsoft.com/en-us/library/aa480061.aspx http://blogs.ittoolbox.com/eai/applications/archives/transformation-in-a-soa-12186

Available Transformers

Following are the transformers available with Mule. Some transformers are specific to a transportor module. For more information, see Available Transports and Using Mule Modules. For a completereference to the elements and attributes for the standard Mule transformers, see TransformersConfiguration Reference.

Basic

The basic transformers are in the org.mule.transformer.simple package. They do not require any specialconfiguration. For details on these transformers, see Transformers Configuration Reference.

Transformer Description

BeanBuilderTransformer (As of Mule 2.2) Constructs simple bean objectsby defining the object and then setting a numberof expressions used to populate the beanproperties. For example:

<bean-builder-transformer name="testTransformer3" beanClass="org.mule.test.fruit.Orange"> <bean-property name="brand" evaluator="mule" expression="message.payload" optional="true"/> <bean-property name="segments" evaluator="mule" expression="message.header(SEGMENTS)"/></bean-builder-transformer>

ByteArrayToHexString <->HexStringToByteArray

A pair of transformers that convert between bytearrays and hex strings.

ByteArrayToMuleMessage <->MuleMessageToByteArray

A pair of transformers that convert between bytearrays and Mule messages.

ByteArrayToObject <->ObjectToByteArray

A pair of transformers that convert betweenbyte arrays and objects. If the byte array is notserialized, ByteArrayToObject returns a Stringcreated from the bytes as the returnType on thetransformer.

ByteArrayToSerializable <->SerializableToByteArray

A pair of transformers that serialize anddeserialize objects.

ExpressionTransformer Evaluates one or more expressions on the currentmessage and return the results as an Array. Fordetails, see Using Expressions.

MessagePropertiesTransformer A configurable message transformer that allowsusers to add, overwrite, and delete properties onthe current message.

Page 548: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 548

ObjectArrayToString <->StringToObjectArray

A pair of transformers that convert betweenobject arrays and strings. Use the configurationelements <byte-array-to-string-transformer>and <string-to-byte-array-transformer>.

ObjectToInputStream Converts serializable objects to an input streambut treats java.lang.String differently byconverting to bytes using the String.getBytes()method.

ObjectToOutputHandler Converts a byte array into a String.

ObjectToString Returns human-readable output for various kindsof objects. Useful for debugging.

StringAppendTransformer Appends a string to an existing string.

StringToObjectArray Converts a string to an object array. Use theconfiguration element <string-to-byte-array-transformer>.

XML

The XML transformers are in the org.mule.module.xml.transformer package. They provide the ability totransform between different XML formats, use XSLT, and convert to POJOs from XML. For information, seeXML Module.

Scripting

The Scripting transformer transforms objects using scripting, such as JavaScript or Groovy scripts. Thistransformer is in the org.mule.module.scripting.transformer package.

Encryption

The encryption transformers are in the org.mule.transformer.encryption package.

Transformer Description

Encryption <-> Decryption A pair of transformers that use a configuredEncryptionStrategy implementation to encrypt anddecrypt data.

Compression

The compression transformers are in the org.mule.transformer.compression package. They do not requireany special configuration.

Transformer Description

GZipCompressTransformer <->GZipUncompressTransformer

A pair of transformers that compress anduncompress data.

Encoding

The encoding transformers are in the org.mule.transformer.codec package. They do not require anyspecial configuration.

Page 549: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 549

Transformer Description

Base64Encoder <-> Base64Decoder A pair of transformers that convert to and fromBase 64 encoding.

XMLEntityEncoder <-> XMLEntityDecoder A pair of transformers that convert to and fromXML entity encoding.

Page 550: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 550

Creating Custom Transformers

This page last changed on Mar 04, 2009 by jackie.wheeler.

Creating Custom Transformers

[ Transformer Classes ] [ Registering Source and Return Types ] [ Using Transformer Lifecycle Methods ] [Creating Discoverable Transformers ] [ Registering the Transformer ] [ Examples ]

A custom transformer is a user-defined transformer class that implementsorg.mule.api.transformer.Transformer . Your class can extend AbstractTransformer orAbstractMessageAwareTransformer , depending on your needs. This page describes how to create acustom transformer in more detail.

Mule also provides several standard transformers, including XML transformers (such as XML toObject, XSLT, and DOM to XML), encryption transformers that encrypt and decrypt data, compressiontransformers that compress and decompress data, and more. For a list of the standard transformers inMule, see Using Transformers.

Transformer Classes

AbstractTransformer allows you to access and transform the source payload and to specify the encodingto use (if required). It defines methods for controlling the object types this transformer supports andvalidates the expected return type, leaving you to implement a single doTransform() method.

import org.mule.transform.AbstractTransformer; public class OrderToHtmlTransformer implements AbstractTransformer{ public Object doTransform(Object src, String encoding) throws TransformerException}

If you need to transform the message header and attachments, you can useAbstractMessageAwareTransformer instead to change them directly on the message passed in. In thiscase, you return the transformed message payload by overriding the method transform(MuleMessagemessage, String encoding). You can use message.getProperty(Object key) to retrieve theproperties or message.setProperty(Object key, Object value) to set properties on the transformedmessage.

For example:

import org.mule.transform.AbstractMessageAwareTransformer; public class OrderToHtmlTransformer implements AbstractMessageAwareTransformer{ public Object transform(MuleMessage message, String encoding) throws TransformerException}

Registering Source and Return Types

You can specify which source types a transformer can accept and which type it will return. This allowsMule to validate the incoming message before invoking the transformer and to validate the output beforesending the message on. If you create a discoverable transformer, you must set the source and returntypes.

Page 551: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 551

For example, for the Order bean to HTML transformer, you would specify in the constructor that thetransformer converts only message payloads of type Order:

public class OrderToHtmlTransformer implements AbstractMessageAwareTransformer{ public OrderToHtmlTransformer() { registerSourceType(Order.class); setReturnClass(String.class); setName("OrderToHTML");}

Because the source type is specified, you don't need to do any type checking in your transform()method. However, if you add more than one source type, you do need to check for each type in yourtransform() method.

Notice that the above code sets the name of the transformer. Usually, you set the transformer name inthe XML configuration when the transformer is declared. If no name is set, Mule generates a name basedon the first source type and return class, such as "OrderToString" if the above example did not specify thename.

Using Transformer Lifecycle Methods

All objects in Mule have lifecycles associated with them. For transformers, there are two lifecycle methodsthat are most useful.

By default AbstractMessageAwareTransfromer and AbstractTransformer both implement theorg.mule.api.lifecycle.Initialisable interface. After all bean properties are set on the transformer (if any),the doInitialise() method is called. This is useful for transformers to do any initialization or validationwork. For example, if a transformer requires that an external file be loaded before the transformer canoperate, you would load the file via the doInitialise() method.

If you want your transformer to clear up resources when the transformer is no longer needed, yourtransformer must implement org.mule.api.lifecycle.Disposable and implement the dispose() method.

Creating Discoverable Transformers

Mule can perform automatic transformations. For example, when you call the getPayload() method on aMuleMessage and pass in the required type as follows:

Document doc = (Document)muleMessage.getPayload(org.dom4j.Document.class);

Mule looks at the current payload type and tries to find a transformer that can convert it to anorg.dom4j.Document object. Mule provides several standard transformers for switching between commontypes such as strings, byte[], InputStream, and more. Also, transports usually have transformers forspecific message types such as JMSMessage or HttpRequest. When creating a custom transformer, youcan set its priority higher than the standard transformers so that it takes precedence.

To make a transformer discoverable, it must implement org.mule.api.transformer.DiscoverableTransformer. This interface introduces two methods, getPriorityWeighting() and setPriorityWeighting(intweighting). Weighting resolves conflicts when two or more transformers match the search criteria. Theweighting is a number between 1 and 10, with 10 being the highest priority. As a rule, Mule transformershave a priority of 1 and should always have a lower priority than any custom transformers.

For example, to make the OrderToHtmlTransformer discoverable, you would define it as follows:

public class OrderToHtmlTransformer implements AbstractMessageAwareTransformer , DiscoverableTransformer

Page 552: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 552

{ private int weighting = DiscoverableTransformer. DEFAULT_PRIORITY_WEIGHTING + 1; int getPriorityWeighting() { return weighting; } void setPriorityWeighting(int weighting) { this.weighting = weighting; }}

This transformer converts from an Order object to a String, which the standard ObjectToStringtransformer also does, but ObjectToHtml will be used because it has a higher priority weighting. You couldtest this as follows:

MuleMessage message = new DefaultMuleMessage(new Order(...));String html = (String)muleMessage.getPayload(java.lang.String.class);

Registering the Transformer

After creating a transformer, you must register it so that Mule can discover it at runtime. You canregister the transformer simply by configuring it using the <custom-transformer> element in your Muleconfiguration file.

Alternatively, if you want your transformer to be loaded automatically by Mule when your module (JAR)is on the class path, you add a registry-bootstrap.properties file to your JAR under the /META-INF/services/org/mule/config directory. The contents of registry-bootstrap.properties should looksomething like this:

orderToHtml=com.foo.OrderToHtml

When Mule starts, it will discover this bootstrap file before loading any configuration and will install anyobjects listed in the file into the local registry. For more information, see Bootstrapping the Registry.

Examples

To create an HTML message that includes the transactionId from the message header, you wouldextend AbstractMessageAwareTransformer and write the transform() method as follows:

public Object transform(MuleMessage message, String encoding) throws TransformerException{ Order order = (Order)message.getPayload(); StringBuffer html = new StringBuffer(); html.append(""); html.append(""); html.append(""); html.append("Dear ").append(order.getCustomer().getName()).append(" "); html.append("Thank you for your order. Your transaction reference is: <strong>"); html.append(message.getProperty("transactionId").append("</strong>"); html.append("(""); return html.toString();

Page 553: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 553

}

The Hello World example defines a custom transformer called StdinToNameString, which removes linebreaks and newlines from the string:

package org.mule.example.hello;

import org.mule.api.transformer.TransformerException;import org.mule.transformer.AbstractTransformer;

public class StdinToNameString extends AbstractTransformer{ public StdinToNameString() { super(); this.registerSourceType(String.class); this.setReturnClass(NameString.class); }

public Object doTransform(Object src, String encoding) throws TransformerException { NameString nameString = new NameString(); String name = (String) src; nameString.setName(name.replaceAll("\r", "").replaceAll("\n", "").trim()); return nameString; }}

The transformer is then configured like this:

<custom-transformer name="StdinToNameString" class="org.mule.example.hello.StdinToNameString" /> ...<service name="GreeterUMO"> <inbound> <stdio:inbound-endpoint system="IN" transformer-refs="StdinToNameString" /> </inbound>...

Page 554: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 554

Transformers Configuration Reference

This page last changed on Feb 20, 2009 by jackie.wheeler.

Transformers Configuration Reference

[ Transformer ] [ Auto Transformer ] [ Custom Transformer ] [ Message Properties Transformer ][ No Action Transformer ] [ Base64 Encoder Transformer ] [ Base64 Decoder Transformer ] [ XmlEntity Encoder Transformer ] [ Xml Entity Decoder Transformer ] [ Gzip Compress Transformer ] [Gzip Uncompress Transformer ] [ Byte Array To Hex String Transformer ] [ Hex String To Byte ArrayTransformer ] [ Byte Array To Object Transformer ] [ Object To Byte Array Transformer ] [ ObjectTo String Transformer ] [ Object To Xml Transformer ] [ Byte Array To Serializable Transformer ] [Serializable To Byte Array Transformer ] [ Byte Array To String Transformer ] [ String To Byte ArrayTransformer ] [ Append String Transformer ] [ Encrypt Transformer ] [ Decrypt Transformer ] [ ExpressionTransformer ] [ Xpath Extractor Transformer ]

This page provides details on configuring the standard transformers. Note that many transports andmodules provide their own transformers as well.

Transformer

A reference to a transformer defined elsewhere.

Attributes of <transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies thetransformerso that otherelements canreference it.Required if thetransformer isdefined at theglobal level.

returnClass class name no The class ofthe messagegenerated bythe transformer.This is used iftransformersare auto-selected (whichis somewhatincomplete at themoment).

ignoreBadInput boolean no Many transformersonly acceptcertain classes.Such transformersare never calledwith inappropriateinput (whateverthe value of thisattribute). Ifa transformer

Page 555: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 555

forms part of achain and cannotaccept the currentmessage class,this flag controlswhether theremaining partof the chain isevaluated. Iftrue, the nexttransformer iscalled. If falsethe chain ends,keeping the resultgenerated up tothat point.

ref name (no spaces) no The name of thetransformer touse.

Auto Transformer

A transformer that uses the transform discovery mechanism to convert the message payload. Thistransformer works much better when transforming custom object types rather than Java types, becausethere is less chance for ambiguity.

Attributes of <auto-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies thetransformerso that otherelements canreference it.Required if thetransformer isdefined at theglobal level.

returnClass class name no The class ofthe messagegenerated bythe transformer.This is used iftransformersare auto-selected (whichis somewhatincomplete at themoment).

ignoreBadInput boolean no Many transformersonly acceptcertain classes.Such transformersare never calledwith inappropriateinput (whateverthe value of this

Page 556: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 556

attribute). Ifa transformerforms part of achain and cannotaccept the currentmessage class,this flag controlswhether theremaining partof the chain isevaluated. Iftrue, the nexttransformer iscalled. If falsethe chain ends,keeping the resultgenerated up tothat point.

Custom Transformer

A user-implemented transformer.

Attributes of <custom-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies thetransformerso that otherelements canreference it.Required if thetransformer isdefined at theglobal level.

returnClass class name no The class ofthe messagegenerated bythe transformer.This is used iftransformersare auto-selected (whichis somewhatincomplete at themoment).

ignoreBadInput boolean no Many transformersonly acceptcertain classes.Such transformersare never calledwith inappropriateinput (whateverthe value of thisattribute). Ifa transformerforms part of achain and cannot

Page 557: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 557

accept the currentmessage class,this flag controlswhether theremaining partof the chain isevaluated. Iftrue, the nexttransformer iscalled. If falsethe chain ends,keeping the resultgenerated up tothat point.

class class name no Animplementation ofthe Transformerinterface.

Child Elements of <custom-transformer...>

Name Cardinality Description

spring:property 0..*

Message Properties Transformer

A transformer that can add or delete message properties.

Attributes of <message-properties-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies thetransformerso that otherelements canreference it.Required if thetransformer isdefined at theglobal level.

returnClass class name no The class ofthe messagegenerated bythe transformer.This is used iftransformersare auto-selected (whichis somewhatincomplete at themoment).

ignoreBadInput boolean no Many transformersonly accept

Page 558: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 558

certain classes.Such transformersare never calledwith inappropriateinput (whateverthe value of thisattribute). Ifa transformerforms part of achain and cannotaccept the currentmessage class,this flag controlswhether theremaining partof the chain isevaluated. Iftrue, the nexttransformer iscalled. If falsethe chain ends,keeping the resultgenerated up tothat point.

overwrite boolean no true If false, a propertyis not added ifthe messagealready contains aproperty with thatname.

Child Elements of <message-properties-transformer...>

Name Cardinality Description

delete-message-property 0..* Delete a message property.

add-message-property 0..* Add a message property.

rename-message-property 0..* Rename a message property.

add-message-properties 0..1 Add a set of message properties.

No Action Transformer

A transformer that has no effect.

Attributes of <no-action-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies thetransformerso that otherelements canreference it.Required if the

Page 559: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 559

transformer isdefined at theglobal level.

returnClass class name no The class ofthe messagegenerated bythe transformer.This is used iftransformersare auto-selected (whichis somewhatincomplete at themoment).

ignoreBadInput boolean no Many transformersonly acceptcertain classes.Such transformersare never calledwith inappropriateinput (whateverthe value of thisattribute). Ifa transformerforms part of achain and cannotaccept the currentmessage class,this flag controlswhether theremaining partof the chain isevaluated. Iftrue, the nexttransformer iscalled. If falsethe chain ends,keeping the resultgenerated up tothat point.

Base64 Encoder Transformer

A transformer that base64 encodes a string or byte array message.

Attributes of <base64-encoder-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies thetransformerso that otherelements canreference it.Required if thetransformer isdefined at theglobal level.

Page 560: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 560

returnClass class name no The class ofthe messagegenerated bythe transformer.This is used iftransformersare auto-selected (whichis somewhatincomplete at themoment).

ignoreBadInput boolean no Many transformersonly acceptcertain classes.Such transformersare never calledwith inappropriateinput (whateverthe value of thisattribute). Ifa transformerforms part of achain and cannotaccept the currentmessage class,this flag controlswhether theremaining partof the chain isevaluated. Iftrue, the nexttransformer iscalled. If falsethe chain ends,keeping the resultgenerated up tothat point.

Base64 Decoder Transformer

A transformer that base64 decodes a message to give an array of bytes.

Attributes of <base64-decoder-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies thetransformerso that otherelements canreference it.Required if thetransformer isdefined at theglobal level.

returnClass class name no The class ofthe messagegenerated by

Page 561: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 561

the transformer.This is used iftransformersare auto-selected (whichis somewhatincomplete at themoment).

ignoreBadInput boolean no Many transformersonly acceptcertain classes.Such transformersare never calledwith inappropriateinput (whateverthe value of thisattribute). Ifa transformerforms part of achain and cannotaccept the currentmessage class,this flag controlswhether theremaining partof the chain isevaluated. Iftrue, the nexttransformer iscalled. If falsethe chain ends,keeping the resultgenerated up tothat point.

Xml Entity Encoder Transformer

A transformer that encodes a string using XML entities.

Attributes of <xml-entity-encoder-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies thetransformerso that otherelements canreference it.Required if thetransformer isdefined at theglobal level.

returnClass class name no The class ofthe messagegenerated bythe transformer.This is used iftransformers

Page 562: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 562

are auto-selected (whichis somewhatincomplete at themoment).

ignoreBadInput boolean no Many transformersonly acceptcertain classes.Such transformersare never calledwith inappropriateinput (whateverthe value of thisattribute). Ifa transformerforms part of achain and cannotaccept the currentmessage class,this flag controlswhether theremaining partof the chain isevaluated. Iftrue, the nexttransformer iscalled. If falsethe chain ends,keeping the resultgenerated up tothat point.

Xml Entity Decoder Transformer

A transformer that decodes a string containing XML entities.

Attributes of <xml-entity-decoder-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies thetransformerso that otherelements canreference it.Required if thetransformer isdefined at theglobal level.

returnClass class name no The class ofthe messagegenerated bythe transformer.This is used iftransformersare auto-selected (whichis somewhat

Page 563: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 563

incomplete at themoment).

ignoreBadInput boolean no Many transformersonly acceptcertain classes.Such transformersare never calledwith inappropriateinput (whateverthe value of thisattribute). Ifa transformerforms part of achain and cannotaccept the currentmessage class,this flag controlswhether theremaining partof the chain isevaluated. Iftrue, the nexttransformer iscalled. If falsethe chain ends,keeping the resultgenerated up tothat point.

Gzip Compress Transformer

A transformer that compresses a byte array using gzip.

Attributes of <gzip-compress-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies thetransformerso that otherelements canreference it.Required if thetransformer isdefined at theglobal level.

returnClass class name no The class ofthe messagegenerated bythe transformer.This is used iftransformersare auto-selected (whichis somewhatincomplete at themoment).

Page 564: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 564

ignoreBadInput boolean no Many transformersonly acceptcertain classes.Such transformersare never calledwith inappropriateinput (whateverthe value of thisattribute). Ifa transformerforms part of achain and cannotaccept the currentmessage class,this flag controlswhether theremaining partof the chain isevaluated. Iftrue, the nexttransformer iscalled. If falsethe chain ends,keeping the resultgenerated up tothat point.

Gzip Uncompress Transformer

A transformer that uncompresses a byte array using gzip.

Attributes of <gzip-uncompress-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies thetransformerso that otherelements canreference it.Required if thetransformer isdefined at theglobal level.

returnClass class name no The class ofthe messagegenerated bythe transformer.This is used iftransformersare auto-selected (whichis somewhatincomplete at themoment).

ignoreBadInput boolean no Many transformersonly acceptcertain classes.

Page 565: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 565

Such transformersare never calledwith inappropriateinput (whateverthe value of thisattribute). Ifa transformerforms part of achain and cannotaccept the currentmessage class,this flag controlswhether theremaining partof the chain isevaluated. Iftrue, the nexttransformer iscalled. If falsethe chain ends,keeping the resultgenerated up tothat point.

Byte Array To Hex String Transformer

A transformer that converts a byte array to a string of hexadecimal digits.

Attributes of <byte-array-to-hex-string-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies thetransformerso that otherelements canreference it.Required if thetransformer isdefined at theglobal level.

returnClass class name no The class ofthe messagegenerated bythe transformer.This is used iftransformersare auto-selected (whichis somewhatincomplete at themoment).

ignoreBadInput boolean no Many transformersonly acceptcertain classes.Such transformersare never calledwith inappropriate

Page 566: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 566

input (whateverthe value of thisattribute). Ifa transformerforms part of achain and cannotaccept the currentmessage class,this flag controlswhether theremaining partof the chain isevaluated. Iftrue, the nexttransformer iscalled. If falsethe chain ends,keeping the resultgenerated up tothat point.

Hex String To Byte Array Transformer

A transformer that converts a string of hexadecimal digits to a byte array.

Attributes of <hex-string-to-byte-array-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies thetransformerso that otherelements canreference it.Required if thetransformer isdefined at theglobal level.

returnClass class name no The class ofthe messagegenerated bythe transformer.This is used iftransformersare auto-selected (whichis somewhatincomplete at themoment).

ignoreBadInput boolean no Many transformersonly acceptcertain classes.Such transformersare never calledwith inappropriateinput (whateverthe value of thisattribute). If

Page 567: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 567

a transformerforms part of achain and cannotaccept the currentmessage class,this flag controlswhether theremaining partof the chain isevaluated. Iftrue, the nexttransformer iscalled. If falsethe chain ends,keeping the resultgenerated up tothat point.

Byte Array To Object Transformer

A transformer that converts a byte array to an object (either deserializing or converting to a string).

Attributes of <byte-array-to-object-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies thetransformerso that otherelements canreference it.Required if thetransformer isdefined at theglobal level.

returnClass class name no The class ofthe messagegenerated bythe transformer.This is used iftransformersare auto-selected (whichis somewhatincomplete at themoment).

ignoreBadInput boolean no Many transformersonly acceptcertain classes.Such transformersare never calledwith inappropriateinput (whateverthe value of thisattribute). Ifa transformerforms part of achain and cannot

Page 568: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 568

accept the currentmessage class,this flag controlswhether theremaining partof the chain isevaluated. Iftrue, the nexttransformer iscalled. If falsethe chain ends,keeping the resultgenerated up tothat point.

Object To Byte Array Transformer

A transformer that serializes all objects except strings (which are converted using getBytes()).

Attributes of <object-to-byte-array-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies thetransformerso that otherelements canreference it.Required if thetransformer isdefined at theglobal level.

returnClass class name no The class ofthe messagegenerated bythe transformer.This is used iftransformersare auto-selected (whichis somewhatincomplete at themoment).

ignoreBadInput boolean no Many transformersonly acceptcertain classes.Such transformersare never calledwith inappropriateinput (whateverthe value of thisattribute). Ifa transformerforms part of achain and cannotaccept the currentmessage class,this flag controls

Page 569: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 569

whether theremaining partof the chain isevaluated. Iftrue, the nexttransformer iscalled. If falsethe chain ends,keeping the resultgenerated up tothat point.

Object To String Transformer

A transformer that gives a human-readable description of various types (useful for debugging).

Attributes of <object-to-string-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies thetransformerso that otherelements canreference it.Required if thetransformer isdefined at theglobal level.

returnClass class name no The class ofthe messagegenerated bythe transformer.This is used iftransformersare auto-selected (whichis somewhatincomplete at themoment).

ignoreBadInput boolean no Many transformersonly acceptcertain classes.Such transformersare never calledwith inappropriateinput (whateverthe value of thisattribute). Ifa transformerforms part of achain and cannotaccept the currentmessage class,this flag controlswhether theremaining partof the chain is

Page 570: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 570

evaluated. Iftrue, the nexttransformer iscalled. If falsethe chain ends,keeping the resultgenerated up tothat point.

Object To Xml Transformer

Converts a Java object to an XML representation using XStream.

Attributes of <object-to-xml-transformer...>

Name Type Required Default Description

acceptMuleMessage boolean no false Whether thetransformerwill serializethe payloador the entireMuleMessageincluding not onlyits payload, butalso its properties,correlation ID, etc.

Byte Array To Serializable Transformer

A transformer that converts a byte array to an object (deserializing the object).

Attributes of <byte-array-to-serializable-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies thetransformerso that otherelements canreference it.Required if thetransformer isdefined at theglobal level.

returnClass class name no The class ofthe messagegenerated bythe transformer.This is used iftransformersare auto-selected (whichis somewhatincomplete at themoment).

Page 571: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 571

ignoreBadInput boolean no Many transformersonly acceptcertain classes.Such transformersare never calledwith inappropriateinput (whateverthe value of thisattribute). Ifa transformerforms part of achain and cannotaccept the currentmessage class,this flag controlswhether theremaining partof the chain isevaluated. Iftrue, the nexttransformer iscalled. If falsethe chain ends,keeping the resultgenerated up tothat point.

Serializable To Byte Array Transformer

A transformer that converts an object to a byte array (serializing the object).

Attributes of <serializable-to-byte-array-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies thetransformerso that otherelements canreference it.Required if thetransformer isdefined at theglobal level.

returnClass class name no The class ofthe messagegenerated bythe transformer.This is used iftransformersare auto-selected (whichis somewhatincomplete at themoment).

ignoreBadInput boolean no Many transformersonly acceptcertain classes.

Page 572: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 572

Such transformersare never calledwith inappropriateinput (whateverthe value of thisattribute). Ifa transformerforms part of achain and cannotaccept the currentmessage class,this flag controlswhether theremaining partof the chain isevaluated. Iftrue, the nexttransformer iscalled. If falsethe chain ends,keeping the resultgenerated up tothat point.

Byte Array To String Transformer

A transformer that converts a byte array to a string.

Attributes of <byte-array-to-string-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies thetransformerso that otherelements canreference it.Required if thetransformer isdefined at theglobal level.

returnClass class name no The class ofthe messagegenerated bythe transformer.This is used iftransformersare auto-selected (whichis somewhatincomplete at themoment).

ignoreBadInput boolean no Many transformersonly acceptcertain classes.Such transformersare never calledwith inappropriateinput (whatever

Page 573: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 573

the value of thisattribute). Ifa transformerforms part of achain and cannotaccept the currentmessage class,this flag controlswhether theremaining partof the chain isevaluated. Iftrue, the nexttransformer iscalled. If falsethe chain ends,keeping the resultgenerated up tothat point.

String To Byte Array Transformer

A transformer that converts a string to a byte array.

Attributes of <string-to-byte-array-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies thetransformerso that otherelements canreference it.Required if thetransformer isdefined at theglobal level.

returnClass class name no The class ofthe messagegenerated bythe transformer.This is used iftransformersare auto-selected (whichis somewhatincomplete at themoment).

ignoreBadInput boolean no Many transformersonly acceptcertain classes.Such transformersare never calledwith inappropriateinput (whateverthe value of thisattribute). Ifa transformerforms part of a

Page 574: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 574

chain and cannotaccept the currentmessage class,this flag controlswhether theremaining partof the chain isevaluated. Iftrue, the nexttransformer iscalled. If falsethe chain ends,keeping the resultgenerated up tothat point.

Append String Transformer

A transformer that appends a string to a string payload.

Attributes of <append-string-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies thetransformerso that otherelements canreference it.Required if thetransformer isdefined at theglobal level.

returnClass class name no The class ofthe messagegenerated bythe transformer.This is used iftransformersare auto-selected (whichis somewhatincomplete at themoment).

ignoreBadInput boolean no Many transformersonly acceptcertain classes.Such transformersare never calledwith inappropriateinput (whateverthe value of thisattribute). Ifa transformerforms part of achain and cannotaccept the currentmessage class,this flag controls

Page 575: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 575

whether theremaining partof the chain isevaluated. Iftrue, the nexttransformer iscalled. If falsethe chain ends,keeping the resultgenerated up tothat point.

message string no The string toappend.

Encrypt Transformer

A transformer that encrypts a message.

Attributes of <encrypt-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies thetransformerso that otherelements canreference it.Required if thetransformer isdefined at theglobal level.

returnClass class name no The class ofthe messagegenerated bythe transformer.This is used iftransformersare auto-selected (whichis somewhatincomplete at themoment).

ignoreBadInput boolean no Many transformersonly acceptcertain classes.Such transformersare never calledwith inappropriateinput (whateverthe value of thisattribute). Ifa transformerforms part of achain and cannotaccept the currentmessage class,this flag controls

Page 576: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 576

whether theremaining partof the chain isevaluated. Iftrue, the nexttransformer iscalled. If falsethe chain ends,keeping the resultgenerated up tothat point.

strategy-ref name (no spaces) no The name ofthe encryptionstrategy to use.This should beconfigured usingthe password-encryption-strategy element,inside a security-manager elementat the top level.

Decrypt Transformer

A transformer that decrypts a message.

Attributes of <decrypt-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies thetransformerso that otherelements canreference it.Required if thetransformer isdefined at theglobal level.

returnClass class name no The class ofthe messagegenerated bythe transformer.This is used iftransformersare auto-selected (whichis somewhatincomplete at themoment).

ignoreBadInput boolean no Many transformersonly acceptcertain classes.Such transformersare never calledwith inappropriateinput (whatever

Page 577: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 577

the value of thisattribute). Ifa transformerforms part of achain and cannotaccept the currentmessage class,this flag controlswhether theremaining partof the chain isevaluated. Iftrue, the nexttransformer iscalled. If falsethe chain ends,keeping the resultgenerated up tothat point.

strategy-ref name (no spaces) no The name ofthe encryptionstrategy to use.This should beconfigured usingthe password-encryption-strategy element,inside a security-manager elementat the top level.

Expression Transformer

A transformer that evaluates one or more expressions on the current message. Each expression equatesto a parameter in the return message. The return message for two or more expressions will be anObject[].

Attributes of <expression-transformer...>

Name Type Required Default Description

name name (no spaces) no Identifies thetransformerso that otherelements canreference it.Required if thetransformer isdefined at theglobal level.

returnClass class name no The class ofthe messagegenerated bythe transformer.This is used iftransformersare auto-selected (whichis somewhat

Page 578: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 578

incomplete at themoment).

ignoreBadInput boolean no Many transformersonly acceptcertain classes.Such transformersare never calledwith inappropriateinput (whateverthe value of thisattribute). Ifa transformerforms part of achain and cannotaccept the currentmessage class,this flag controlswhether theremaining partof the chain isevaluated. Iftrue, the nexttransformer iscalled. If falsethe chain ends,keeping the resultgenerated up tothat point.

returnSourceIfNull boolean no If all expressionsreturn null onthis transformer,this flag willcause the sourcepayload to bereturned withoutmodification.

Child Elements of <expression-transformer...>

Name Cardinality Description

return-argument 0..1 A list of expressions, each ofwhich is evaluated and equatesto an element in the resultmessage. If just one 'return-argument' is configured, theresult will be the evaluation ofthat expression rather than anobject array.

Xpath Extractor Transformer

The XPathExtractor is a simple transformer that evaluates an XPath expressionusing the JAXP libraries against the given bean and returns the result.By default, a String of the result will be returned. To return a Node, NodeSet,Boolean or Number result, the resultType attribute can be set.

Page 579: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 579

Attributes of <xpath-extractor-transformer...>

Name Type Required Default Description

expression string no The XPathexpression.

resultType xpathResultType no The XPath resulttype (e.g. STRINGor NODE).

Child Elements of <xpath-extractor-transformer...>

Name Cardinality Description

namespace 0..* A namespace declaration,expressed as prefix and uriattributes. The prefix can thenbe used inside the expression.

Page 580: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 580

XmlPrettyPrinter Transformer

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

Xml Prettyprinter Transformer

Formats an XML string using the Pretty Printer functionality in org.dom4j.io.OutputFormat.

Attributes of <xml-prettyprinter-transformer...>

Name Type Required Default Description

encoding string no The encodingformat to use,such as UTF-8.

expandEmptyElementsboolean no Whether toexpand emptyelements from<tagName> to<tagName></tagName>.

indentEnabled boolean no Whether to enableindenting of theXML code. If true,the indent stringand size are used.

indentString string no The string to useas the indent,usually an emptyspace.

indentSize integer no The number ofindent stringsto use for eachindent, such as"2" if indentStringis set to an emptyspace and youwant to use twoempty spaces foreach indent.

lineSeparator string no The string to usefor new lines,typically "\n".

newLineAfterNTags integer no If the newlinesattribute is true,the number ofclosing tagsafter which anewline separatoris inserted. Forexample, settingthis to "5" willcause a newlineto be insertedafter the output of

Page 581: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 581

five closing tags(including singletags).

newlines boolean no Whether newlinesshould be printed.If false, the XML isprinted all on oneline.

omitEncoding boolean no Whether theXML declarationline includes theencoding of thedocument. Itis common tosuppress this inprotocols such asSOAP.

padText boolean no Whether toensure that textimmediatelypreceded by orfollowed by anelement will be"padded" with asingle space. Thisis useful whenyou set trimTextto true andwant to ensurethat "the quick<b>brown</b> fox" doesnot become "thequick<b>brown</b>fox".

suppressDeclaration boolean no Whether tosuppress the XMLdeclaration line.It is common tosuppress this inprotocols such asSOAP.

trimText boolean no Whether to trimwhite space in theXML.

XHTML boolean no Whether touse the XHTMLstandard, whichis like HTML butpasses an XMLparser with real,closed tags, andoutputs CDATAsections withCDATA delimiters.

Page 582: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 582

Using Web Services

This page last changed on Feb 03, 2009 by jackie.wheeler.

Using Web Services

The following topics describe how to use web services with Mule.

Using Axis with Mule - Links to several topics describing Axis support in Mule.

Building a CXF Web Service - Describes how to build a CXF web service and use it in Mule.

Using the Mule Client - Describes the Mule Client, which can be used as a SOAP client.

Proxying Web Services - Describes how to use Mule as a web service gateway/proxy in various scenarios.

Supported Web Service Standards - Web service standards supported by Mule and CXF.

Web Service Wrapper - Describes how to use the WebServiceWrapperComponent class to send the resultof a web service call to another endpoint.

RESTpack - Provides support for building RESTful services inside Mule. You can also use the REST servicewrapper (a specialized Mule service component) in the HTTP transport to proxy REST-style requests toexternal REST/HTTP services. This wrapper component acts as a REST client and is appropriate if you donot have strict REST requirements.

Echo Example - A simple example of exposing a Mule service as a web service using Axis.

Using .NET Web Services with Mule - Tips for using .NET web services with Mule.

Page 583: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 583

Axis

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

Using Axis with Mule

The following topics describe how to configure Mule and Apache Axis.

• Axis Web Services and Mule - Introduction to exposing Mule services over Axis and invoking SOAPservices.

• Configuring Axis - Controlling WSDL generation, named parameters, Advanced Serviceconfiguration, and more.

• Axis Transport - Basic configuration of the Axis transport.• Axis SOAP Transports - Using Axis over JMS, VM, SMTP, and other Mule transports.• Axis SOAP Styles - Configuring services for Doc/Lit, Message or RPC style invocations.

Page 584: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 584

Axis SOAP Styles

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

Axis SOAP Styles

By default, Mule Axis support uses RPC/Encoded for SOAP messages. However, because of compatibilityissues on other platforms, it has become increasingly popular to use Document/Literal/Wrappedstyle services. This page describes how to use Doc/Lit, Doc/Lit/Wrapped, and Message style servicesusing Axis in Mule. For an overview of the pros and cons of each style/use combination, see http://www-128.ibm.com/developerworks/webservices/library/ws-whichwsdl/.

The client examples below show how to invoke an Axis web service hosted in Tomcat using the Muleclient. The example behaves exactly the same way if the service is hosted in Mule unless explicitly notedotherwise. These tests were run against Tomcat 5.5.12 and Axis 1.3.1. Each test uses the Calculatorservice as used in the Axis User Guide.

Document Literal Wrapped

This is the preferred approach to Document Literal style services. "Wrapped" simply means that theparameters are wrapped in an element whose name is the name of the operation to invoke.

Client Example

This example is very similar to the Doc/Lit example, except that we set the message style to 'wrapped/literal', and there is no need to add any server configuration, as the method name is stored in themessage.

String URL = "axis:http://localhost:8080/axis/Calculator.jws?method=add";MuleClient client = new MuleClient();Map props = new HashMap();props.put("style", "wrapped");props.put("use", "literal");MuleMessage result = client.send(URL, new Object[]{new Integer(3), new Integer(3)}, props);assertEquals(result.getPayload(), new Integer(6));

The SOAP request for this call looks like this:

<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Body> <add xmlns=""> <value0 xsi:type="xsd:int">3</value0> <value1 xsi:type="xsd:int">3</value1> </add> </soapenv:Body></soapenv:Envelope>

In the next example, we can see how to change the namespace of the method as well as naming theparameters. This is very useful when calling services from other platforms.

Page 585: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 585

Doc/Lit/Wrapped with Named Parameters

If you're invoking external services, the Axis-generated names for parameters and namespaces do notwork. You can easily change these in Mule as follows:

Client Example

String URL = "axis:http://localhost:8080/axis/Calculator.jws";MuleClient client = new MuleClient();

SoapMethod method = new SoapMethod(new QName("http://muleumo.org/Calc", "add"));method.addNamedParameter(new QName("Number1"), NamedParameter.XSD_INT, "in");method.addNamedParameter(new QName("Number2"), NamedParameter.XSD_INT, "in");method.setReturnType(NamedParameter.XSD_INT);

Map props = new HashMap();props.put("style", "wrapped");props.put("use", "literal");props.put("method", method);MuleMessage result = client.send(URL, new Object[]{new Integer(3), new Integer(3)}, props);assertEquals(result.getPayload(), new Integer(6));

Note that we do not pass the method name in the query string of the URL. Instead, we create aSoapMethod object and add it to the parameters passed to the client call.

The SOAP request now looks like this:

<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Body> <add xmlns="http://muleumo.org/Calc"> <Number1 xsi:type="xsd:int" xmlns="">3</Number1> <Number2 xsi:type="xsd:int" xmlns="">3</Number2> </add> </soapenv:Body></soapenv:Envelope>

Using the Mule Configuration

Instead of hard-coding the namespaces and parameter names, you can specify them in an endpointconfiguration in the Mule configuration file and reference the endpoint from your Mule client. Theconfiguration file will look like this:

<axis:endpoint name="calculatorAddEndpoint" address="http://localhost:62088/axis/Calculator?method=add" style="WRAPPED" use="LITERAL"> <axis:soap-method method="add"> <axis:soap-parameter parameter="Number1" type="int" mode="IN"/> <axis:soap-parameter parameter="Number2" type="int" mode="IN"/> <axis:soap-return type="int"/> </axis:soap-method></axis:endpoint>

Page 586: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 586

This endpoint configuration can be used by the Mule client or on a component outbound router. The clientcode is now much simpler:

MuleClient client = new MuleClient("org/mule/test/integration/providers/soap/axis/soap-client-endpoint-config.xml");

Muleessage result = client.send("calculatorAddEndpoint", new Object[]{new Integer(3), new Integer(3)}, null);assertEquals(result.getPayload(), new Integer(6));

Notice the URL for the MuleClient call contains the name of the service endpoint, not the physical locationof the resource.

Document Literal

Mule hosted Web services using Axis cannot be invoked using Doc/Lit. Use Doc/Lit/Wrappedinstead. Users can still invoke remote web services using Doc/Lit as shown in the examplebelow.

Client Example

For this example, we must tell the Mule client to use 'document/literal' for the message style, and wepass this information into the call on the Mule client. This requires some configuration on the Axis server.The biggest limitation of Doc/Lit is that operation/method name is not passed with the message.

String URL = "axis:http://localhost:8080/axis/Calculator.jws?method=add";MuleClient client = new MuleClient();Map props = new HashMap();props.put("style", "document");props.put("use", "literal");MuleMessage result = client.send(URL, new Object[]{new Integer(3), new Integer(3)}, props);assertEquals(result.getPayload(), new Integer(6));

The SOAP request for this call looks like this:

<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Body> <value0 xsi:type="xsd:int">3</value0> <value1 xsi:type="xsd:int">3</value1> </soapenv:Body></soapenv:Envelope>

Using Doc/Lit with Axis might appear to work even when you don't add operation info tothe Axis server configuration. This happens when there is a single parameter for the serviceand the parameter name is the same as the operation/method name you want to invoke.For more information, see Axis Operations.

RPC Encoded

Because Axis uses RPC/Encoded by default, there is no need to pass any additional configurationinformation. The client call looks like this:

Page 587: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 587

String URL = "axis:http://localhost:8080/axis/Calculator.jws?method=add";MuleClient client = new MuleClient();MuleMessage result = client.send(URL, new Object[]{new Integer(4), new Integer(3)}, null);assertEquals(result.getPayload(), new Integer(7));

The SOAP request for this call looks like this:

<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Body> <add soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <value0 href="#id0"/> <value1 href="#id1"/> </add> <multiRef id="id0" soapenc:root="0" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="soapenc:int" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">4</multiRef> <multiRef id="id1" soapenc:root="0" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="soapenc:int" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">3</multiRef> </soapenv:Body></soapenv:Envelope>

Page 588: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 588

Axis SOAP Transports

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

Axis SOAP Transports

[ SOAP Over JMS ] [ SOAP Over VM ] [ Binding to a Servlet Container ] [ Using Other Mule Transports ]

Mule transports can deliver SOAP requests between Axis clients and Axis services hosted by Mule. Thismeans you can easily use JMS, VM, SMTP, or even XMPP (Jabber) to send SOAP requests. This pagedescribes how to configure these transports.

SOAP Over JMS

First, if you do not want to use the default JMS connector, configure the connector you do want to use inyour Mule XML configuration:

<jms:activemq-connector name="jmsConnector"/>

Next, create the service. In this example, we will create a service that listens to a queue calledechoComponent. The method parameter specifies the operation to invoke. The SOAPAction propertyspecifies the name of the queue again, which is required if your service name and queue name are notidentical.

<model name="echoSample"> <service name="echoService"> <inbound> <inbound-endpoint address="axis:jms://echoComponent?method=echo&param=hello" SOAPAction="jms://echoComponent"/> </inbound> <echo-component/> </service></model>

You can also add any other JMS endpoint options, such as transactions. See the JMS Transportdocumentation for a full description.

SOAP Over VM

The VM transport also supports SOAP, which can be useful for testing or prototyping. You configure theendpoints the same as JMS SOAP endpoints. For example:

<model name="test"> <service name="mycomponent"> <inbound> <inbound-endpoint address="axis:vm://mycomponent"/> </inbound> <component> <singleton-object class="org.mule.tck.testmodels.services.TestServiceComponent"/> </component> </service>

Page 589: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 589

<service name="mycomponent2"> <inbound> <axis:inbound-endpoint address="vm://mycomponent2"> <axis:soap-service interface="org.mule.api.component.simple.EchoService"/> <axis:soap-service interface="org.mule.tck.testmodels.services.DateService"/> </axis:inbound-endpoint> </inbound> <component> <singleton-object class="org.mule.tck.testmodels.services.TestServiceComponent"/> </component> </service></model>

Binding to a Servlet Container

If you embed Mule in a webapp, you might want to bind Axis services to the servlet container port ratherthan open another port for Mule SOAP services, but you may not be able to do this because of firewallrestrictions. In this scenario, you can use the Servlet Transport and Axis instead of HTTP. To use thistransport, you must add MuleReceiverServlet to your web.xml file:

<servlet> <servlet-name>muleServlet</servlet-name> <servlet-class>org.mule.transport.servlet.MuleReceiverServlet</servlet-class> <load-on-startup/></servlet>

<servlet-mapping> <servlet-name>muleServlet</servlet-name> <url-pattern>/mule/services/*</url-pattern></servlet-mapping>

Next, you add a servlet endpoint to your component:

<servlet:connector name="servlet" servletUrl="http://localhost:62088/services"/> <model name="test"> <service name="mycomponent"> <inbound> <axis:inbound-endpoint address="servlet://mycomponent"/> </inbound> <component class= "org.mule.tck.testmodels.services.TestServiceComponent"/> </service></model>

Note that you set the host, port, and path on the connector, not the endpoint, using the servletUrlproperty.

Using Other Mule Transports

You can send and receive SOAP requests using other transports simply by configuring the endpointaccording to the endpoint scheme and then prepending the axis: scheme. For client endpoints, you alsoset the the method parameter.

//Client

Page 590: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 590

axis:xmpp://mule1:[email protected]/axis?method=echo&param=hello

//Serveraxis:xmpp://mule1:[email protected]/axis

Page 591: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 591

Axis Transport

This page last changed on Feb 20, 2009 by jackie.wheeler.

Axis Transport

The Axis transport allows Mule-managed components to be published as Axis services and allowscomponents to invoke web services using Axis client calls.

The Javadocs for the AxisConnector can be found at org.mule.transport.soap.axis.AxisConnector .

Programmatic Configuration

If you want to programmatically configure your Axis service you can implement theorg.mule.transport.soap.axis.AxisInitialisable interface. This will pass the SOAPService object to yourcomponent where it can be manipulated.

Connector

The Axis connector consumes and provides web services via Axis. It supports all the common connectorattributes and properties as well as the following additional attributes:

Attributes of <connector...>

Name Type Required Default Description

axis-ref string no Bean reference tothe Axis server.

clientConfig string no Configurationfile to use whenbuilding the Axisclient.

clientProvider-ref string no Bean reference tothe client providerto use for creatingthe Axis client.

doAutoTypes boolean no Use this propertyto configurewhether the Axisserver shouldautomaticallymap types. Thisproperty onlytakes effect if youdo not provideyour own Axisserver via theaxis-ref property.

serverConfig string no Configurationfile to use whenbuilding the Axisserver.

Page 592: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 592

serverProvider-ref string no Bean referenceto the serverprovider thatshould be usedto create the Axisserver.

treatMapAsNamedParamsboolean no The Axisconnectortreats a Mapas a containerfor namedparameters andunpacks themfrom the map.If your exposedservice needs totake a Map as aparameter, set thisproperty to falseto prevent theconnector fromunpacking theMap.

Child Elements of <connector...>

Name Cardinality Description

bean-type 0..*

supported-scheme 0..*

Inbound Endpoint

Attributes of <inbound-endpoint...>

Name Type Required Default Description

wsdlFile string no The location of aWSDL documentto use for thisservice if youdo not want theWSDL documentautogenerated.

clientConfig string no

soapAction string no

SOAPAction string no

serviceNamespace string no

style styleType no Specifies theSOAP binding

Page 593: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 593

style: RPC(default),DOCUMENT,MESSAGE, orWRAPPED.

use useType no Specifies theSOAP bindinguse: ENCODED(default) orLITERAL.

For example:

<service name="Calculator"> <inbound> <axis:inbound-endpoint address="http://localhost:62088/axis" style="WRAPPED" use="LITERAL"> <axis:soap-method method="qname{add:http://muleumo.org/Calc}"> <axis:soap-parameter parameter="Number1" type="any" mode="IN" /> <axis:soap-parameter parameter="Number2" type="any" mode="IN" /> <axis:soap-return type="any" /> </axis:soap-method> </axis:inbound-endpoint> </inbound> <component class="org.mule.transport.soap.axis.Calculator" /> </service>

Escape Your Credentials

If you use a URI-style endpoint and you include the user name and password, escape anycharacters that are illegal for URIs, such as the @ character. For example, if the user nameis [email protected], you should enter it as user%40myco.com.

Outbound Endpoint

Attributes of <outbound-endpoint...>

Name Type Required Default Description

clientConfig string no

soapAction string no

SOAPAction string no

serviceNamespace string no

style styleType no Specifies theSOAP bindingstyle: RPC(default),DOCUMENT,MESSAGE, orWRAPPED.

use useType no Specifies theSOAP bindinguse: ENCODED

Page 594: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 594

(default) orLITERAL.

Wrapper Component

The WebServiceWrapperComponent class allows you to send the result of a web service call to anotherendpoint. For example:

<axis:wrapper-component address="http://localhost:65081/services/TestUMO?method=receive" style="WRAPPED" use="LITERAL" />

Attributes of <wrapper-component...>

Name Type Required Default Description

address string no Specifies the URLof the web serviceto call.

addressFromMessageboolean no Specifies that theURL of the webservice will beobtained from themessage itself.

style styleType no Specifies theSOAP bindingstyle: RPC(default),DOCUMENT,MESSAGE, orWRAPPED.

use useType no Specifies theSOAP bindinguse: ENCODED(default) orLITERAL.

Child Elements of <wrapper-component...>

Name Cardinality Description

soap-method 0..* Allows you to specify aSOAP method and optionallyparameters and a return. Theparameter mode can be IN, OUT,or INOUT.

Page 595: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 595

Axis Web Services and Mule

This page last changed on Oct 13, 2008 by [email protected].

Axis Web Services and Mule

[ Exposing Web Services ] [ Invoking Web Services ] [ Axis Without a Servlet Container ] [ Configuringthe Axis Server ] [ SOAP Over Other Transports ]

Exposing Web Services

You can expose service components as Axis services and invoke them from Mule. To expose a servicecomponent as an Axis service, you simply import the Axis namespace and then set the component'sinbound endpoint to an Axis URL. Note that web services expect methods to be exposed throughinterfaces implemented by their respective components. Otherwise, you will receive configuration errorswhen Mule starts.

<service name="echoService"> <inbound> <axis:inbound-endpoint address="http://localhost:81/services"/> </inbound> <echo-component/></service>

When Mule starts, the service will be available on http://localhost:81/services/echoService. The Echocomponent class (org.mule.components.simple.EchoComponent) implements the EchoService interface,which has a single method called echo that accepts a single parameter string.

Note: Mule 2.0 supports Axis 1.4.

Invoking Web Services

You can invoke web services from Mule programmatically using the Mule Client or as part of the eventflow of a Mule service. This section describes these approaches in detail.

Invoking Services Using the Mule Client

To invoke the Echo service using the Mule Client, use the following code:

public static void main(String[] args){ MuleClient client = new MuleClient(); MuleMessage result = client.send ("axis:http://localhost:81/services/echoService?method=echo", "Hello!", null); System.out.println("Message Echoed is: " + result.getPayload()); client.close();}

Invoking Web Services from a Mule Service

To invoke the Echo service from a service, you add an outbound endpoint to your service configuration.The following example shows a service that receives an event on vm://test.component, does some workon the event, and then invokes the Echo service.

Page 596: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 596

<service name="test"> <inbound> <vm:inbound-endpoint path="test.component" synchronous="true"/> </inbound> <component implementation="com.foo.TestComponent"/> <outbound> <outbound-pass-through-router> <axis:outbound-endpoint address="http://localhost:81/services/echoService?method=echo"/> </outbound-pass-through-router> </outbound></service>

The org.foo.TestComponent class looks like this:

public class TestComponent implements Callable{ public Object onCall(MuleEventContext context) throws Exception { Object payload = context.getMessage().getPayload();

//Do some work on the payload and return a string that will be //used by the outbound endpoint to invoke the echo service //...

return payload.toString(); }}

If the Web service you are invoking takes more than one parameter, you can return an array ofparameters in your component.

When an event is published to vm://test.component, the onCall method is called with the current event.After the onCall method executes, Mule invokes the outbound endpoint for TestComponent with what isreturned from onCall.

Note that the vm://test.component endpoint has a parameter synchronous=true. This tells Mule toinvoke requests from that endpoint in a single thread, making it a request/response style request. Thusthe result of invoking the Echo service (by invoking TestComponent) will be returned to the callee whodispatched the event on vm://test.component.

When the TestEchoService is run, you will see the following output:

Message Echoed is: Hello!

Note the following:

• There is no need for a servlet container, because Mule is the container (see below).• You don't need to specify a deployment WSDD for your service. You simply specify an endpoint for

the service, and the rest is done for you.• The MuleClient call will work just as well if the service you are invoking is hosted by an Axis instance

running on Tomcat or any other servlet engine.• The Axis JAR and associated JARs that ship with the Mule distribution must be on your classpath.

Exposing Services

Page 597: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 597

All service operations are exposed through interfaces implemented by your component.Therefore, your component must implement at least one service interface, which isgenerally good practice anyway.

Axis Without a Servlet Container

When you use Axis with Mule, there is no need for a separate servlet container. When you create an Axisendpoint, Mule takes the following actions:

• Creates an Axis component in Mule, which is analogous to the AxisServlet. There is only one Axiscomponent per Mule instance.

• Creates an HTTP connector for the endpoint address and registers it as a receiver for the Axiscomponent.

Cannot resolve external resource into attachment.

Most web services are a lot more complex than the first example, so the following sections will tell youhow to configure the Axis instance and your services in more detail.

Configuring the Axis Server

In the previous example, a default Axis connector is created when the Axis endpoint is processed byMule. The Axis connector uses a default server configuration file called mule-axis-server-config.wsdd.You can override this configuration by setting the serverConfig property on the connector to a differentconfiguration file, which will allow you to add additional handlers, global configuration, and more.

<axis:connector name="axisConnector" serverConfig="./axis/axis-server-config.wsdd"/>

If you use a custom server configuration, you must add the following handlers in the global configuration:

<requestFlow> <handler type="java:org.mule.transport.soap.axis.extensions.MuleSoapHeadersHandler"/></requestFlow><responseFlow> <handler type="java:org.mule.transport.soap.axis.extensions.MuleSoapHeadersHandler"/></responseFlow>

If you are configuring Mule from a container such as Spring, you can set the Axis server as a beanproperty (axisServer) on the connector and the serverConfig property is ignored.

You can list the Axis services in the same way you list services when Axis is hosted in a servlet container.To list services, simply point your browser at the host and port of the axis endpoint:

http://localhost:81/

To view Axis version information, go to:

http://localhost:81/Version?method=getVersion

To view the WSDL for the service, go to:

http://localhost:81/Version?wsdl

Note that the Axis JWS feature is not supported by Mule.

Page 598: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 598

SOAP Over Other Transports

You can configure Axis to send/receive soap requests over other transports such as JMS and SMTP. Formore information, see Axis SOAP Transports.

For more information about customizing Axis behavior, naming parameters, message style options, andmore, see Configuring Axis.

Page 599: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 599

Configuring Axis

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

Configuring Axis

Table of Contents

Click here to expand...

• Configuring Axis• ° Controlling Exposed Methods

° Map as Parameter° Setting SOAP Document Style° Customizing the SOAP Action Format° Setting Named Parameters° Controlling Namespaces° Controlling WSDL Generation° Type Mappings° Service Initialization Callback

Controlling Exposed Methods

To restrict the exposure of a service's methods add additional soap-service elements. These allow youto specify interfaces that the service implements and that should be exposed.

<axis:inbound-endpoint address="http://localhost:38009/mule/services"> <axis:soap-service interface="org.mule.api.component.simple.EchoService"/> <axis:soap-service interface="org.mule.tck.testmodels.services.DateService"/></axis:inbound-endpoint>

You can also specify one or more methods to expose in a comma-separated list, using theallowedMethods attribute.

<service name="myService"> <inbound> <axis:inbound-endpoint address="http://localhost:38009/mule/services" allowedMethods="echo,getDate" /> </inbound> <component class="com.foo.TestComponent" /></service>

Map as Parameter

The AxisConnector treats a Map as container for named parameters, which eventually will be unpacked.This becomes a problem if your exposed service needs to take a Map as a parameter, because the actualMap will never reach the service intact.

To configure the connector not to unpack Maps so that they can be passed as parameters, use thetreatMapAsNamedParams attribute:

Page 600: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 600

<axis:connector name="axisConnector" treatMapAsNamedParams="false"/>

Setting SOAP Document Style

To control the style and use of a service, the style and use properties can be set on Axis endpoints. Forexample, to make your inbound endpoint Document/Literal/Wrapped, do the following:

<axis:inbound-endpoint address="http://localhost:38009/mule/services" style="WRAPPED" use="LITERAL"/>

The style attribute can be 'RPC' (default), 'DOCUMENT', 'MESSAGE', or 'WRAPPED'. The use attribute canbe either 'ENCODED' (default) or 'LITERAL'.

For more information about service styles and Mule, see Axis SOAP Styles. Also see the Axis web site forfurther reference.

Customizing the SOAP Action Format

By default, Mule uses the Axis endpoint as the SOAP Action when making WS calls. This approach worksfor Axis clients but might not work with .NET clients. The SOAP Action can be different for different SOAPimplementations, so you must be able to customize how the SOAP Action is formatted. You can set thesoapAction attribute on the outbound endpoint making the SOAP request:

<axis:outbound-endpoint address="http://localhost:38011/mule/echoService?method=echo" soapAction="http://localhost:38011/${method}" synchronous="true" />

The above example sets the SOAP Action on the request to http://localhost:38011/echo. If you areUsing the Mule Client, you can set the SOAP Action as a property when making the call.

The SOAP Action can be a static value, or you can use template variables such as the method variableused above. The set of variables that can be used are listed below.

Variable Description Example

method The service method name beinginvoked

echo

methodNamespace The service method name beinginvoked

echo

address The full SOAP endpoint http://localhost:38011/mule/echoService?method=echo

scheme The request scheme being used http

host The hostname from the SOAPendpoint

localhost

Page 601: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 601

port The port from the SOAPendpoint

38011

path The path info from the SOAPendpoint

/mule/echoService

hostInfo The scheme, host and portcombined

http://localhost:38011

serviceName The name of the service beinginvoked

echoService

Any other properties on the event or the endpoint can be referenced by name in the soapActionexpression.

Setting Named Parameters

Some web service clients require that all method parameters of a call should be named. You can do thisin Mule in two ways.

In the Mule XML configuration, you can set the SOAP method parameters for a service on the endpointusing the soap-method element.

<axis:outbound-endpoint address="http://localhost:38011/mule/echoService?method=echo" synchronous="true"> <axis:soap-method method="echo"> <axis:soap-parameter parameter="string1" type="string" mode="IN"/> <axis:soap-parameter parameter="string2" type="string" mode="IN"/> <axis:soap-return type="java"/> </axis:soap-method></axis:endpoint>

Within the soap-method element, you can define soap-parameter elements, which control thatparameter's mode, name, and type. The parameter attribute is the name of the parameter. The typeattribute is an XSD string such as int, long, map, etc. The attribute mode can be in, out, or inout. Thereturn type is also an XSD type string. The soap-return element controls the type of the parameter themethod returns.

Controlling Namespaces

Namespaces for elements can be controlled at the method and parameter level. To declare a namespaceon the method with a prefix of 'foo' and a URI of 'http://mycompany.com/foo', you would use thefollowing code:

<axis:outbound-endpoint address="http://localhost:38011/mule/echoService?method=echo" synchronous="true"> <axis:soap-method method="qname{foo:http://mycompany.com/foo}"> <axis:soap-parameter parameter="in0" type="string" mode="IN"/> <axis:soap-parameter parameter="out" type="ns1:Test" mode="OUT"/> <axis:soap-return type="org.mule.tck.external.applications.Test"/> </axis:soap-method></axis:endpoint>

The syntax for the qname is:

qname{[MULE:prefix]:[MULE:localname]:[MULE:namespace]}

Page 602: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 602

You can supply just a localname, a localname and namespace, or a prefix, localname, and namespace.

The qname syntax can be used with <soap-parameter> elements as well. For example:

<axis:soap-parameter parameter="qname{foo1:echo1:http://mycompany.com/foo1}" type="string" mode="OUT"/>

To set the method parameter name using the Mule client, you create a SoapMethod object and set it onthe properties when making the call. The example below shows how to do this.

MuleClient client = new MuleClient();Map props = new HashMap();//create the soap method passing in the method name and return typeSoapMethod soapMethod = new SoapMethod("echo", NamedParameter.XSD_STRING);//add one or more parameterssoapMethod.addNamedParameter("value", NamedParameter.XSD_STRING, ParameterMode.IN);//set the soap method as a property and pass the properties//when making the callprops.put(MuleProperties.MULE_SOAP_METHOD, soapMethod);

MuleMessage result = client.send("axis:http://localhost:38011/mule/echoService?method=echo", "Hello", props);

Note that you can use the qname notation for setting method and parameter names using the Mule client.

Controlling WSDL Generation

The service namespace (also called the target namespace) for your service can be controlled by settingthe serviceNamespace property on the inbound endpoint:

<axis:inbound-endpoint address="http://localhost/services" serviceNamespace="http://foo.namespace"/>

You can also set the wsdlFile property to the location of a WSDL document to use for this service if youdo not want an auto-generated WSDL document.

<axis:inbound-endpoint address="http://localhost/services" wsdlFile="foo.wsdl"/>

Optionally, you can control the values used in Axis WSDL generation by setting WSDL-specific Axisoptions. The options you can set are:

Option Name Description

wsdlPortType Sets the wsdl:portType name attribute. the Axisdefault is $Proxy0

wsdlServiceElement Sets the wsdl:service name attribute. the Axisdefault is $Proxy0Service

Page 603: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 603

wsdlTargetNamespace Sets the wsdl:definitions targetNamespaceattribute. The Axis default is http:// pluspackage name of the service class in reverse.

wsdlServicePort Sets the wsdl:port name attribute of thewsdl:service element. The default is the nameof the Mule component exposed by this serviceendpoint.

wsdlInputSchema

wsdlSoapActionMode

extraClasses

To change the wsdlServiceElement name attribute to MyService in the generated WSDL for a service,use the following:

<axis:inbound-endpoint address="http://localhost:38009/mule/services"> <properties> <spring:entry key="axisOptions"> <spring:map> <spring:entry key="wsdlServiceElement" value="MyService"/> </spring:map> </spring:entry> </properties></axis:inbound-endpoint>

Type Mappings

Note that as of Axis 1.2-RC3, it is no longer necessary to configure type mappings, as bean serializationis handled automatically by Axis. If you are using an older version of Axis, you might need to configuretype mappings.

Mule enables default type mappings for object serialization between SOAP calls. This means thatserialization and deserialization of call parameters and return objects is mostly handled automatically byAxis. This works for most Java types including primitives, Numbers, Strings, Arrays and Collections. Italso works for JavaBeans whose attributes comprise these types. However, it does not work where youhave a bean that has another bean as an attribute; Axis will complain that it doesn't know how to handlethe bean attribute.

Mule handles this by allowing you to specify a list of beanTypes that Axis needs to understand to manageyour service. For example, assume you have a PersonService service that will get a Person object whenpassed the person's name. The Person object contains an Address object. The configuration will look likethis:

<axis:inbound-endpoint address="http://localhost:38009/mule/services"> <property key="beanTypes"> <spring:list> <spring:value>org.foo.Address</spring:value> </spring:list> </property></axis:inbound-endpoint>

Page 604: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 604

It is important to note that only custom types should be listed. If any standard types arepresent, like java.util.ArrayList, Axis may produce serialization errors.

For convenience, the beanTypes property can be set on an Axis connector configuration so that allservices that use the connector will have the types registered in the TypeRegistry for the service.

<axis:connector name="axisConnector"> <spring:property name="beanTypes"> <spring:list> <spring:value>org.foo.Address</spring:value> </spring:list> </spring:property></axis:connector>

By default, an Axis connector is created if one doesn't exist already when the Axis endpoint is processed.For more information about configuring Connectors and Providers, see Configuring Endpoints.

Service Initialization Callback

If you need further control over the Axis service created by Mule, it is possible for your component toimplement AxisInitialisable.

public interface AxisInitialisable{ public void initialise(SOAPService service) throws InitialisationException;}

This gets called when the service is initialized and allows you to customize the service configuration fromyour Mule component.

Page 605: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 605

Proxying Web Services

This page last changed on Mar 17, 2009 by jackie.wheeler.

Proxying Web Services

[ Protocol Bridging ] [ WSProxyService ] [ CXF Proxy Services ] [ Example: Routing Messages Based onSOAPAction Headers with Transformations ]

Mule can act as a web service gateway/proxy. Gateways can perform several useful functions:

• Routing to the appropriate backend service (whether remote or local)• Message transformations, such as converting from old versions of the message format• Protocol bridging, such as HTTP to JMS• Validation• Security enforcement• WS-Policy enforcement

Mule provides several utilities that help you do this:

• Protocol bridging - allows you to forward requests from one endpoint to another. This is generallythe best option for proxying web services.

• WSProxyService - allows you to service WSDLs locally while proxying remote web services.• CXF proxy services - perform WS-Security or WS-Policy actions, route based on information such as

the operation or SOAP Action, and easily work with just the payload by taking advantage of CXF'sweb service capabilities.

The following sections provide more information on these utilities.

Protocol Bridging

The simplest type of web service proxy just involves forwarding a request from one endpoint to anothervia service bridging. You can forward the data streams directly, or you can process and transform theXML. If you are doing content-based routing, this is often the best option, as it will add less overheadthan a full CXF proxy (which is only needed in certain cases).

Following is a simple example that forwards a request from one HTTP endpoint to another:

<service name="HttpWebServiceBridge"> <inbound> <inbound-endpoint address="http://localhost:8080/my/service" synchronous="true"/> </inbound> <outbound> <outbound-pass-through-router> <outbound-endpoint address="http://acme.come/remote/web/service" synchronous="true"/> </outbound-pass-through-router> </outbound></service>

This type of bridge can be combined with filters for easy message routing. For fast XPath routing ofmessages, you can use the SXC Module.

WSProxyService

The WSProxyService allows you to serve WSDLs locally while proxying remote web services. This is handywhen you have an alternate WSDL you want to service, or if you don't want WSDL requests to be routedwith all the other SOAP message requests. Any request that comes in with a "?wsdl" attached to the HTTPURL will be redirected, and the specified WSDL will be served instead.

Page 606: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 606

To configure this for your service, you must first define a WSProxyService bean with your WSDL:

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

<spring:bean name="WSProxyService" class="org.mule.transport.soap.WSProxyService"> <spring:property name="wsdlFile" value="localWsdl.wsdl"/> </spring:bean>....</mule>

Next, define your service bridge to use this component:

<service name="HttpWebServiceBridge"> <inbound> <inbound-endpoint address="http://localhost:8080/my/service" synchronous="true"/> </inbound> <component> <spring-object bean="WSProxyService" /> </component> <outbound> <outbound-pass-through-router> <outbound-endpoint address="http://acme.come/remote/web/service" synchronous="true"/> </outbound-pass-through-router> </outbound></service>

Now any request to "http://localhost:8080/my/service?wsdl" will cause your WSDL to be served.

CXF Proxy Services

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

While many times you can proxy web services without using CXF (see above), there are several caseswhere you might want to use CXF proxies:

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

Note that currently CXF proxies only support working with the SOAP body. They do not send the wholeSOAP message along.

Page 607: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 607

Server-side Proxying

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

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

This will make the SOAP body available in the Mule message payload as an XMLStreamReader. To servicea WSDL using a CXF proxy, you must specify the WSDL namespace as a property:

<cxf:inbound-endpoint address="http://localhost:63081/services/Echo" proxy="true"wsdlLocation="foo.wsdl"serviceName="YOUR_WSDL_SERVICE" synchronous="true"> <property key="namespace" value="YOUR_WSDL_NAMESPACE"/></cxf:inbound-endpoint>

Client-side Proxying

Similarly, you can create an outbound endpoint to send raw XML payloads:

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

Example: Routing Messages Based on SOAPAction Headerswith Transformations

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

<service name="routeBasedOnSoapAction"> <inbound> <cxf:inbound-endpoint address="http://localhost:63081/service" proxy="true" synchronous="true"/> </inbound> <outbound> <filtering-router> <cxf:outbound-endpoint address="http://localhost:63081/services/Echo" proxy="true" synchronous="true"/> <message-property-filter pattern="SOAPAction=http://acme.com/v2/bid"/> </filtering-router> <filtering-router> <cxf:outbound-endpoint address="http://localhost:63081/services/Echo" proxy="true" synchronous="true"> <transformers> <mule-xml:xslt-transformer xsl-file="v1-to-v2.xsl" returnClass="org.mule.module.xml.transformer.DelayedResult"/> </transformers> <response-transformers> <mule-xml:xslt-transformer xsl-file="v2-to-v1.xsl" returnClass="org.mule.module.xml.transformer.DelayedResult"/> </response-transformers> </cxf:outbound-endpoint>

Page 608: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 608

<message-property-filter pattern="SOAPAction=http://acme.com/v1/bid"/> </filtering-router> </outbound></service>

Page 609: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 609

Using .NET Web Services with Mule

This page last changed on Dec 11, 2008 by [email protected].

Using .NET Web Services with Mule

Following are tips for using Mule to communicate with .NET web services.

Authentication and Other Security Features

There are three ways to secure a web service:

• Via an HTTP web server• Via authentication tokens in the SOAP header• Via WS-Security

Via an HTTP Web Server

If you are running Mule on a Web App, you can configure the web server to use security by settingsecurity configuration in web.xml and in the server's configuration file.

Alternatively, to secure a web service running on Mule (where Mule is the server), you can set theHttpBasicAuthenticationFilter on the web service component. Any call made to the web service wouldhave to pass through the filter that delegates the authentication to Acegi.

Another alternative would be to use HTTPS where certificates are used for authentication.

For more information see Configuring Security and Using HTTPS with CXF.

Using Authentication Tokens in SOAP Headers

You can send authentication tokens through SOAP headers as long as there is an authentication providerestablished that is able to understand the headers and perform the authentication.

Using WS-Security

If you are using CXF, you can configure a client and service to use WS-Security. For details, see EnablingWS-Security.

Passing Authentication Information to a Web Service

There are three methods for passing authentication information to a web service configured on Mule:

• Pass them in the URL, such as http://name:password@localhost:8080/MyService• Set the authentication items as properties when using the Mule client• Create headers containing the authentication items and send them as properties when using the

Mule client

Page 610: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 610

Web Service Wrapper

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

Using the Web Service Wrapper

The WebServiceWrapperComponent class allows you to send the result of a web service call to anotherendpoint. The web service call is performed within WebServiceWrapperComponent, providing the followingadvantages:

• You can set any type of router on inbound and outbound.• Unlike the chaining router, it can send more than one HTTP request at a time• The URL for the web service call can be changed at run-time by sending the URL with the message

Configuring the Web Service Wrapper

To use the web service wrapper, you specify the <wrapper-component> configuration element. Thefollowing table describes the attributes you can set for this element. These attributes are described inmore detail in the examples that follow.

Attribute Description Required?

address Specifies the URL of the webservice to call

Yes, unlessaddressFromMessage is set totrue

addressFromMessage (default isfalse)

Specifies that the URL of theweb service will be obtainedfrom the message itself

Not required if address is set

wrapperProperties The SOAP document style,expressed as a map of twoproperties: style, which canbe set to RPC (the default),Document, Message, or Wrapped,and use, which can be Encodedor Literal.

No

<soap-method> A SOAP method to call (seeConfiguring SOAP Methodsbelow)

No

The web service wrapper is generic and can be used with any type of web service stack supported byMule, including Axis and CXF. The examples below show synchronous use cases, but the web servicewrapper can also support an asynchronous use case like the loan broker example.

Example Configuration Using the CXF Transport

Consider the following example. The web service wrapper is configured as a Mule component, acceptingmessages from a VM endpoint. A call must be made to a web service on the URL cxf:http://localhost:65081/services/TestUMO?method=onReceive and the result must be sent to the outboundendpoint vm://testout.

The inbound and outbound endpoints are configured in the usual way. The address is set as an attributeon the component, specifying the web service URL that you want to call.

<cxf:connector name="cxf" defaultFrontend="simple" /><model name="Sample">

Page 611: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 611

<service name="WebServiceSample"> <inbound> <vm:inbound-endpoint path="testin" /> </inbound> <cxf:wrapper-component address="http://localhost:65081/services/TestUMO?method=onReceive"/> <outbound> <outbound-pass-through-router> <outbound-endpoint address="vm://testout"/> </outbound-pass-through-router> </outbound> </service>

Example Configuration Using the addressFromMessage Property

The "address" property is ideal to use when the web service URL for the web service is known atconfiguration time. However, if this URL is either not known or else needs to be changed at run-time,the "address" property can be omitted and the "adddressFromMessage" property can be set to true. Thefollowing example shows this configuration:

<service name = "WebServiceSample2"> <inbound> <vm:inbound-endpoint path = "testin2"/> </inbound> <cxf:wrapper-component addressFromMessage = "true"/> </service>

The URL must be set on the message with the property name "ws.service.url".

Configuring SOAP Methods

CXF endpoints are fairly easy to configure, whereas Axis needs some further configuration to set SOAPmethods. You can set a SOAP method using the <soap-method> element as shown below:

<service name = "WebServiceSample3"> <inbound> <vm:inbound-endpoint path = "queue.in" connector-ref = "VMQueue"/> </inbound> <axis:wrapper-component address = "http://localhost:62088/axis/Calculator?method=add" style = "WRAPPED" use = "LITERAL"> <axis:soap-method method = "qname{add:http://muleumo.org/Calc}"> <axis:soap-parameter parameter = "Number1" type = "int" mode = "IN"/> <axis:soap-parameter parameter = "Number2" type = "int" mode = "IN"/> <axis:soap-return type = "int"/> </axis:soap-method> </axis:wrapper-component> <outbound> <outbound-pass-through-router> <vm:outbound-endpoint path = "queue.out" connector-ref = "VMQueue"/> </outbound-pass-through-router> </outbound> </service>

Page 612: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 612

Working with Services

This page last changed on Jan 27, 2009 by jackie.wheeler.

Working with Services

A service component is a class, web service, or other application that contains the business logic youwant to plug in to the Mule framework. For example, one service component could add information toan invoice from a customer database, and another service component could be the order fulfillmentapplication that processes that invoice. You can use any existing application for a service component, orcreate a new one.

Your service component does not need to contain any Mule-specific code. Instead, you configurea service, which wraps the service component with the Mule-specific configuration. The serviceconfiguration points to the service component, as well as routers, filters, and transformers to use whencarrying messages to and from the service component. It also specifies the endpoint on which this servicewill receive messages and the outbound endpoint where messages will go next. Services are the primaryMule artifact used to implement integration solutions.

To watch a demo of building a simple service, click here.

Service Components

A service component can be a POJO, servlet, web service, and much more. Typically, you create a customservice component, but you can also use one of the several standard components included with Mule. Formore information, see Configuring Components.

Service Configuration

Most configuration happens at the service level. Services can be configured using globally definedendpoints, transformers, and filters, or these can be defined inline. For more information, see Configuringthe Service.

Service Behavior

When a service receives a message on an inbound endpoint, the service model (default is SEDA)determines the service's threading and queuing behavior, while the messaging pattern defines theinbound and outbound message exchange patterns that will be used.

Advanced Configuration

You can further configure the service with security (configured on endpoints), transactions, and errorhandling.

Page 613: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 613

Configuring Components

This page last changed on Feb 03, 2009 by jackie.wheeler.

Configuring Components

[ Simple Components ] [ Java Components ] [ Other Components ] [ Customizing Behavior withInterceptors ]

Service components contain the business logic for working with the messages passed through Mule. Aservice component can be any type of object, including a Spring bean, POJO, script, web service, or RESTcall.

Because they are highly specific to your implementation, you will typically create your own customcomponents, or simply use an existing POJO. Mule also ships with some standard components you canuse or extend as needed. This page describes how to configure the different types of components.

For detailed information on the elements you configure for components, see Component ConfigurationReference.

Simple Components

There are several simple components included with Mule that are useful for testing or bypassingcomponent execution.

Configuration Element Description

<log-component/> Logs component invocations, outputting thereceived message as a string. This componentdoes not return a response.

<echo-component/> Extends the log component to log and echo theincoming message. The message is transformedbefore being returned, so transformations oninbound endpoints will be applied.

<null-component/> Throws an exception when invoked. This isuseful for testing use cases that use a forwardingconsumer inbound router.

<passthrough-component> Similar to the echo component but does notlog. This component is useful when definingservices that consist of inbound and outboundendpoints/routers but don't have a componentimplementation. Note that explicitly configuringthis component has exactly the same result asconfiguring a service with no component.

<bridge-component/> Identical to the pass-through component butpreserves the Mule 1.4 terminology.

<test:component/> Configures the Mule FunctionalTestComponent,which allows more complex testing scenarios tobe created. For more information, see FunctionalTesting.

Page 614: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 614

Java Components

Java components specify a Java class to be used as the service component or configure a reference to animplementation in a container such as Spring. They also configure the way in which Mule should managethe Java service component's life-cycle, invoke it, and (if pooled) manage the pool of instances.

Java components can be configured quickly and easily by simply specifying the service componentimplementation class name on the <component> or <pooled-component> element. The <pooled-component> element allows you to establish a pooling profile for the service (see Tuning Performance).In both cases, the PrototypeObjectFactory will be used by default and a new object instance will becreated for each request or (for pooled components) for each new object in the pool.

<component class="org.my.ServiceComponentImpl"/>...<pooled-component class="org.my.ServiceComponentImpl"/>

Alternatively, you can explicitly specify object factories, such as the SingletonObjectFactory thatcreates a single instance of the object:

<component> <singleton-object class="org.my.ServiceComponentImpl"/></component>

The explicit syntax is required instead of the shortcut <component class> syntax if you add interceptorsto the component. For further configuration options and information on the default settings that areapplied, see Configuring Java Components.

Other Components

These are several other components available that allow you to use different technologies such as webservices for your service components. These components are often included as part of transports ormodules.

Configuration Description

<http:rest-service-component/> Proxies a remote call to a REST-style web service.

<cxf:wrapper-component/> Proxies a remote call to a web service using CXF.

<axis:wrapper-component/> Proxies a remote call to a web service using Axis.

<script:component/> Configures a JSR-223 script for the servicecomponent.

Customizing Behavior with Interceptors

Mule interceptors are useful for attaching behaviors to multiple service components. The interceptorpattern is often referred to as practical AOP (Aspect Oriented Programming), as it allows the developerto intercept processing on an object and potentially alter the processing and outcome. For completeinformation, see Using Interceptors.

Page 615: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 615

Configuring Java Components

This page last changed on Feb 09, 2009 by jackie.wheeler.

Configuring Java Components

[ Object Factories ] [ Entry Point Resolvers ] [ Lifecycle Adapter Factory ] [ Bindings ] [ Configuring aPooled Java Component ]

Java is the default component type in Mule. Mule provides two JavaComponent implementations:DefaultJavaComponent , which you configure with the component element, and PooledJavaComponent ,which adds pooling functionality and which you configure with the pooled-component element. These twoimplementations provide the following functionality and configuration options:

• An ObjectFactory is used to obtain the Java service component implementation.• EntryPointResolvers can be configured to define how Mule services should invoke the component

methods when processing a message.• A custom LifecycleAdaptor can be configured to customize the way in which the component

implementation is initialized and disposed.• Bindings can be configured to bind component interface methods to endpoints. These endpoints are

then invoked synchronously when the method is called.

When you specify the class directly on the component or pooled-component element, thePrototypeObjectFactory is used by default, and a new instance is created for each invocation, or a newpooled component is created in the case of the PooledJavaComponent.

Example:

<component class="org.my.CustomComponent"/>..<pooled-component class="org.my.CustomComponent"/>

Alternatively, you can specify the implementation using an object factory.

Example:

<component> <singleton-object class="org.my.CustomComponent"/></component>...<component> <spring-object bean="myCustomComponentBean"/></component>

All other component configuration elements are configured as children of the component or pooled-component element.

Note: In Mule 2.0, Java component pooling is used only if the <pooled-component> element is used. Inprevious versions of Mule, pooling was the default.

Object Factories

Object factories manage both object creation in the case of a Mule instantiated instance or object look-up from another container such as Spring via a single API. The following object factories are included withMule and can be configured using Mule's core schema.

Page 616: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 616

<prototype-object class=..."/> PrototypeObjectFactory

<singleton-object class=..."/> SingletonObjectFactory

<spring-object bean=..."/> SpringBeanLookup

Object factories also allow you to set properties, which are injected when a new object instance iscreated.

Example:

<component> <singleton-object class="org.my.SingletonObject"> <property key="myKey" value="theValue"/> <property key="myKey2" value="theValue2"/> </singleton-object></component>

For a real-world example of using <spring-object/>, see Using Spring Beans as Service Components.

You can easily implement additional object factories to integrate with other containers or simply to createobject instances in a different way.

Note: Object factories replace ContainerContexts in previous versions of Mule.

Entry Point Resolvers

You can configure entry point resolvers that determine how your component is invoked when a messageis received by the service. See Developing Service Components for a more detailed description of theirfunctionality.

To configure entry point resolvers, you can either configure an entry point resolver set or configure asingle entry point resolver independently. When using an entry point resolver set, the order in which theresolvers are configured is the order of of precedence they are given in run-time.

Example:

<component class="org.my.PrototypeObjectWithMyLifecycle"> <entry-point-resolver-set> <array-entry-point-resolver/> <callable-entry-point-resolver/> </entry-point-resolver-set></component>

<component class="org.my.PrototypeObjectWithMyLifecycle"> <reflection-entry-point-resolver/></component>

You can also configure entry point resolvers (single or sets) on models to apply them to all servicesdefined in that model. You use the same configuration syntax as above but on the <model> elementinstead of <component>.

Page 617: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 617

Lifecycle Adapter Factory

You can configure your Java component to use a custom lifecycle adaptor. If you do not configure acustom implementation, the default implementation will be used, which allows the optional propagation ofMule's lifecycle to your component depending on the Mule lifecycle interfaces that are implemented.

Example:

<component class="org.my.PrototypeObjectWithMyLifecycle"> <custom-lifecycle-adapter-factory class="org.my.MyLifecycleMuleAdapterFactory"/></component>

See Developing Service Components for more information about lifecycles.

Bindings

Components can use bindings to call an external service during execution. The bindings used with a Javacomponent bind a Java interface, or single interface method, to an outbound endpoint. The externalservice to be called should implement the same interface, and the component should encapsulate areference to that interface, which is initialized during the bootstrap stage by the Mule configurationbuilder. The reference will be initialized using a reflective proxy class.

Binding can be used on Java components and script components. For more information see ComponentBindings.

Configuring a Pooled Java Component

A pooled Java component will maintain a pool of object instances that will be reused, with a singleinstance being used by one thread at any one time. The configuration of component pooling isindependent of the object factory, allowing you to use whichever object factory you need.

You configure the pool using the nested pooling-profile element as shown below:

<pooled-component class="org.my.PrototypeObject"> <pooling-profile exhaustedAction="WHEN_EXHAUSTED_FAIL" initialisationPolicy="INITIALISE_ALL" maxActive="1" maxIdle="2" maxWait="3" /></pooled-component>

For more information about pooling and reference documentation for pooling configuration options, seeTuning Performance.

Page 618: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 618

Using Interceptors

This page last changed on Jan 19, 2009 by jackie.wheeler.

Using Interceptors

[ Interceptor Types ] [ Interceptor Event Flow ] [ Writing Interceptors ] [ Configuring Interceptors ] [Interceptor Configuration Reference ]

Mule interceptors are useful for attaching behaviors to multiple service components. The interceptorpattern is often referred to as practical AOP (Aspect Oriented Programming), as it allows the developerto intercept processing on an object and potentially alter the processing and outcome. (See also SpringAOP). Interceptors are very useful for attaching behavior such as profiling and permission and securitychecks to your service components.

Interceptor Types

Mule has two types of interceptors:

• EnvelopeInterceptor : Envelope filter that will execute before and after the component is invoked.Good for logging and profiling.

• Interceptor : Intercepts the message and then forwards it for processing to the next element. Aninterceptor can stop further processing by not forwarding control to the next interceptor, as with apermissions checker interceptor.

Interceptor Event Flow

The following shows an example interceptor stack and the event flow.

Page 619: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 619

Writing Interceptors

If you want to intercept a message flow to a component on the inbound message flow, you shouldimplement the Interceptor interface. It has a single method:

MuleMessage intercept(Invocation invocation) throws MuleException;

The invocation parameter contains the current message and the Service object of the targetcomponent. Developers can extract the current MuleMessage from the message and manipulate it asneeded. The intercept method must return a MuleMessage that will be passed on to the component (orto the next interceptor in the chain).

The EnvelopeInterceptor works in the same way, except that it exposes two methods that get invokedbefore and after the event processing:

MuleMessage before(Invocation invocation) throws MuleException;

MuleMessage after(Invocation invocation) throws MuleException;

Configuring Interceptors

Interceptors can be configured on your components as follows:

<service name="MyService"> <component> <custom-interceptor class="org.my.CustomInterceptor"/> <logging-interceptor/> <interceptor-stack ref="testInterceptorStack"/> <timer-interceptor/> <prototype-object class="org.my.ComponentImpl"/> </component> </service>

When you configure interceptors, you must specify the object factory explicitly (in thisexample, <prototype-object>) instead of using the <component class> shortcut.

You can also define interceptor stacks, which are one or more interceptors that can be referenced using alogical name. To use an interceptor stack, you must first configure it in the global section of the Mule XMLconfiguration file (above the <model> element):

<interceptor-stack name="default"> <custom-interceptor class="org.my.CustomInterceptor"/> <logging-interceptor/></interceptor-stack>

You can configure multiple <interceptor> elements on your components, and you can mix using built-ininterceptors, custom interceptors, and references to interceptor stacks.

Page 620: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 620

Interceptor Configuration Reference

<timer-interceptor ...>

The timer interceptor (ported from 1.x).

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

<logging-interceptor ...>

The logging interceptor (ported from 1.x).

Attributes

Child Elements

Name Type Required Default Description

Name Cardinality Description

<custom-interceptor ...>

A user-implemented interceptor.

Attributes

Name Type Required Default Description

class class name no Animplementationof the Interceptorinterface.

Child Elements

Name Cardinality Description

spring:property 0..*

Page 621: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 621

<interceptor-stack ...>

Attributes

Name Type Required Default Description

name name no The name usedto identify thisinterceptor stack.

Child Elements

Name Cardinality Description

abstract-interceptor 1..1 A placeholder for an interceptorelement.

<interceptor-stack ...>

A reference to a stack of intereceptors defined globally.

Attributes

Name Type Required Default Description

ref name (no spaces) no The name of theinterceptor stackto use.

Child Elements

Name Cardinality Description

Page 622: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 622

Configuring the Service

This page last changed on Jan 27, 2009 by jackie.wheeler.

Configuring the Service

[ Inbound ] [ Component ] [ Outbound ] [ Async Reply ] [ Exception Strategy ] [ Service Bridge ] [Service Model ] [ Service Messaging Style ]

You configure services using a <service> element within a <model> element. Each <service> elementrepresents and configures a Mule service, providing a unique name that identifies it and optionallyan initial state that determines whether the service and its endpoints are started when Mule starts(supported values are started, stopped, or paused).

<mule> <model> <service name="GreeterUMO"> ... </service>

<service name="GreeterUMO2" initialState="stopped" > ... </service> </model></mule>

Each service can be configured with the following optional elements:

• <description>: Describes the service• <inbound>: Configures the inbound routers, their endpoints, and inbound transformers• component: Configures the service component• <outbound>: Configures the outbound routers, their endpoints, and outbound transformers• <async-reply>: Configures an async reply router, which is used for asynchronous request-response

messaging• <exception-strategy>: Configures the exception strategy for the service

If you configure more than one of these elements, note that you must configure them in the order shownabove. For detailed information on the <service> elements and attributes, see Service ConfigurationReference.

Following is a sample service configuration showing these elements:

<service name="GreeterUMO"> <description>Adds some text to the string before passing it on</description> <inbound> <stdio:inbound-endpoint system="IN"> <transformer ref="StdinToNameString"/> </stdio:inbound-endpoint> </inbound> <component class="org.mule.example.hello.Greeter" /> <outbound> <filtering-router> <vm:outbound-endpoint path="chitchatter" /> <payload-type-filter expectedType="org.mule.example.hello.NameString" /> </filtering-router> </outbound> <default-service-exception-strategy> <vm:outbound-endpoint path="systemErrorHandler" /> </default-service-exception-strategy>

Page 623: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 623

</service>

The following sections describe these elements in more detail.

Inbound

This element is used to configure inbound endpoints and inbound routers. Endpoints are used to receiveincoming messages, and inbound routers determine how these messages are routed. Inbound endpointsand routers are configured separately within the <inbound> element.

Inbound Endpoints

Inbound endpoints are used to receive incoming messages. An endpoint is simply a set of instructionsindicating which transport and path/address to receive messages from, as well as any transformers,filters, or security that should be applied when receiving the messages. You can configure multipleinbound endpoints, each receiving message from different transports. For more information, seeConfiguring Endpoints and Available Transports.

Inbound Routers

Inbound routers control and manipulate messages received by a service before passing them to theservice component. Typically, an inbound router is used to filter incoming messages, aggregate a set ofincoming messages, or re-sequence messages when they are received. Inbound routers are also used toregister multiple inbound endpoints for a service. You can chain inbound routers together, so that eachrouter must be matched before the message can be passed to the component. You can also configure acatch-all strategy that is invoked if none of the routers accept the current message.

Inbound routers are different from outbound routers in that the endpoint is already known (as themessage has already been received), so the purpose of the router is to control how messages are givento the component.

If no inbound routers are configured, by default an InboundPassThroughRouter is used to simply pass theincoming message to the component.

Matching Only the First Router

By default, a message must match and be processed by all inbound routers in a service before it ispassed to the service component. If you want to configure the service so that the message is processedonly by the first router whose conditions it matches, you set the matchAll attribute on the <inbound>element to false.

This behavior is new in Mule 2.0. Previously, the message was processed only by the firstmatching router by default.

For more information about the inbound routers that can be used, see Mule Inbound Routers .

Inbound Example

<inbound> <stdio:inbound-endpoint system="IN" /> <catch-all-strategy> <jms:outbound-endpoint queue="failure.queue"/> </catch-all-strategy> <selective-consumer-router> <mulexml:jxpath-filter pattern="(msg/header/resultcode)='success'"/> </selective-consumer-router></inbound>

Page 624: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 624

This example uses a selective consumer router that will accept a message if a 'resultcode' element has avalue of 'success'. If the message matches this filter's criteria, the message is passed to the component.If the message does not match, the catch-all strategy is invoked, which sends the message via itsconfigured endpoint, in this case a JMS queue called 'failure.queue'.

Component

The <component> element configures the service component that will be invoked after the inboundmessage is processed by the inbound routers. If no component is configured, the service acts as a bridgeand simply passes messages through to the outbound router.

There are several standard components you can use, such as <log-component>, which logs componentinvocations, outputting the received message as a string, and <echo-component>, which extends the logcomponent to log and echo the incoming message. Typically, you will create your own component as aplain old Java object (POJO) and configure it using the <component> element.

For more information about component types and their configuration, see Configuring Components. Youcan also implement new component types in your Mule modules and use them within your configuration.In Mule 2.0, it is now easier to implement and use new non-Java component types and configure themwith their own custom component element.

Outbound

The <outbound> element configures outbound routers and their endpoints. Because outbound routersare used to determine which endpoints to use for dispatching messages after the component has finishedprocessing them, outbound endpoints are configured on the outbound routers, not directly on the<outbound> element. Outbound routers allow the developer to define multiple routing constraints for anygiven message. You can specify a catch-all strategy to invoke if none of the routers accept the currentmessage. For more information, see Configuring Endpoints and Available Transports.

Matching All Routers

By default, a message is processed only by the first outbound router whose conditions it matches. Ifyou want the message to be processed by all the outbound routers, you can set the matchAll attributeto true. For example, assume you always want to send a confirmation of a deposit back to the originaldepositor. Also assume that if the deposit was above $100,000, you want to send a notification messageto the 'high net worth client manager' for possible follow-up. In this case, you would set the matchAllattribute on the <outbound> definition as follows:

<outbound matchAll="true"> <filtering-router> <endpoint address="jms://deposit.queue"/> </filtering-router> <filtering-router> <jms:outbound-endpoint queue="large.deposit.queue"/> <mulexml:jxpath-filter expression="deposit/amount >= 100000"/> </filtering-router></outbound>

In this example, the message will always match the first router because there is no filter on it.Additionally, the message will match the second router if the deposit amount is >= $100000, in whichcase both routers will have been invoked.

For more information about the outbound routers you can use, see Mule Outbound Routers .

Outbound Example

<outbound>

Page 625: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 625

<catch-all-strategy> <jms:outbound-endpoint queue="default.queue"/> </catch-all-strategy> <filtering-router> <smtp:outbound-endpoint to="[email protected]" subject="Exception!" from="[email protected]!"> <transformer ref="ExceptionToEmail"/> </smtp:outbound-endpoint> <payload-type-filter expectedType="java.lang.Exception"/> </filtering-router> <filtering-router> <vm:endpoint path="my.component"/> <and-filter> <payload-type-filter expectedType="java.lang.String"/> <regex-filter pattern="the quick brown (.*)"/> </and-filter> </filtering-router></outbound>

Async Reply

This element is used to configure the endpoints and routers that will be used to receive the response inasynchronous request-response scenarios where you must consolidate responses from a remote endpointbefore the current service responds via its inbound endpoint. The classic example of this approach iswhere a request is made and then multiple tasks are executed in parallel. Each task must finish executingand the results processed before a response can be sent back to the requester. For an illustration ofasynchronous request-response, click here. For more information about the available Async Reply routers,see Asynchronous Reply Routers . For information on configuring endpoints, see Configuring Endpoints.

Async Reply routers can be used to join forked tasks in a request-response call. In fact, you wouldonly use an async reply router with services that use synchronous calls (as there is no responsewhen dispatching a message asynchronously). Mule provides aggregator routers that can be used inconjunction with a message splitter or recipient list router to aggregate messages before returning aresponse. For more information on these routers, see Using Message Routers.

<async-reply> <jms:inbound-endpoint queue="bank.quotes"/> <custom-async-reply-router class="org.mule.samples.loanbroker.routers.BankQuotesResponseAggregator"/></async-reply>

The endpoint specifies the address where responses should be sent to be processed. The router isresponsible for aggregating bank quotes into a single quote for the customer. Consider the inboundconfiguration and the async-reply router in the LoanBroker configuration:

<service name="LoanBroker"> <inbound> <vm:inbound-endpoint path="Loan.Requests"/> </inbound> <component class="org.mule.samples.loanbroker.SyncLoanBroker"> <outbound> <static-recipient-list-router> <reply-to address="jms://Loan.Quotes"/> <message-property-filter expression="recipients!=null"/> </static-recipient-list-router> </outbound-router> <async-reply> <jms:inbound-endpoint queue="Loan.Quotes"/>

Page 626: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 626

<custom-async-reply-router class="org.mule.samples.loanbroker.routers.BankQuotesResponseAggregator"/> </async-reply></service>

This configuration specifies that the Loan Broker will receive requests from vm://Loan.Requests and willdispatch multiple requests to different banks via the outbound router. The bank endpoints are definedin a List called 'recipients', which is a property on the outbound message. The important setting onthe outbound router is the <reply-to> endpoint, which tells Mule to route all responses to the jms://Loan.Quotes endpoint, which is the endpoint on which the async-reply router is listening. When allresponses are received, the BankQuotesResponseAggregator selects the cheapest quotes and returns it.Mule then handles returning this to the requester. The <reply-to> endpoint is applied to the next serviceinvoked. For example, if service1 dispatches to service2, and service1 has an outbound router with areply-to endpoint, service2 will send the results of its invocation to the reply-to endpoint.

Response Transformers

If you want to transform a response message without doing any other work on the response, you set thetransformers attribute on the response router without any other routing configuration.

<response-router transformers="OrderConfirmationToXml XmlToWebPage"/>

ReplyTo

All outbound routers can have a reply-to endpoint endpoint that defines where the message should berouted after the recipient of the message has finished processing it. The <reply-to> endpoint is appliedto the next component invoked. For example, if component1 dispatches to component2, and component1has an outbound router with a reply-to endpoint, component2 will send the results of its invocation tothe reply-to endpoint. The <reply-to> endpoint can be any valid Mule endpoint URI and is passed alongwith the message to the next component if the underlying transport supports reply-to messages. Forinformation on which transports support reply-to, see Available Transports.

<outbound> <custom-router class="org.foo.ConcreteMessageSplitter"> <vm:endpoint path="component1"/> <vm:endpoint path="vm://component2"/> <vm:endpoint path="vm://component3"/> <reply-to address="vm://component4"/> </custom-router></outbound>

Time-outs

The Async Reply router timeout determines how long Mule should wait for replies before returning theresult. The default value is determined by the value of the defaultSynchronousEventTimeout attributethat has been configured for the Mule instance. (For more information, see Global Settings ConfigurationReference.) You can also specify an independent timeout value for asynchronous replies for a givenservice using the optional timeout attribute on the async-reply element.

The optional failOnTimeout attribute determines whether to throw an exception if the router times outbefore all expected messages have been received. If set to false (the default), the current messages arereturned for processing.

Page 627: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 627

Exception Strategy

Exception strategies are used to handle exception conditions when an error occurs during the processingof a message. You can configure exception strategies on services. If no exception strategy is configured,the DefaultServiceExceptionStrategy is used.

For more information on exception strategies, see Error Handling.

Service Bridge

Service component configuration is optional in Mule 2.x. The default and implicit component used isPassThroughComponent . This component automatically bridges inbound messages to the outboundphase and simply passes messages to the outbound routers. This approach is useful for bridgingendpoints if you want to pass a message from one transport to another.

As of Mule 2.0, you no longer need to configure an explicit BridgeComponent.

The following example demonstrates reading a file and send its contents onto a JMS topic.

<service name="FileToJmsBridge"> <inbound> <file:inbound-endpoint path="/data/in"> <file:filename-wildcard-filter pattern="*.txt"/> </inbound-endpoint> </inbound> <!-- No need to configure a component here -->

<outbound> <outbound-pass-through-router"> <jms:outbound-endpoint topic="receivedFiles"/> </outbound-pass-through-router> </outbound> </service>

Service Model

By default, Mule uses the staged event-driven architecture (SEDA) model. SEDA is an architecturemodel where applications consist of a network of event-driven stages connected by explicit queues.This architecture allows services to be well-conditioned to load, preventing resources from beingovercommitted when demand exceeds service capacity. As a result, SEDA provides an efficient event-based queuing model that maximizes performance and throughput.

See Models for more information about alternative models and information about how you can implementyour own.

Service Messaging Style

The messaging style determines the message exchange pattern that is to to be used on inboundand outbound endpoints and allows endpoints to be configured as synchronous request/response orasynchronous in-only as well as other patterns.

The messaging style is configured on endpoints, allowing multiple styles to be used with the sameservice. For more information, see Mule Messaging Styles.

Page 628: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 628

MEPs

This page last changed on Feb 26, 2009 by jackie.wheeler.

This document is in progress and forms part of a proposal of how messaging exchanges inMule should work. Not unnecessarily how they work now. See Mule Messaging Styles forinformation on how Mule message exchanges work as of Mule 2.0.

Table of Contents

Click here to expand...

• Message Exchange Patterns in Mule• ° Focus on Services

° WSDL MEPs° Extended MEPs (WSDL 2.0)

• Mule MEPs• ° Notation

° In-Only° - Example Configuration

- Example Code° In-Out° - Example Configuration

- Example Code° In-Out (async)° - Example Configuration

- Example Code° In-Optional-Out° - Example Configuration

- Example Code° In-Only, Out-Only° - Example Configuration

- Example Code° In-Only, Optional-Out° - Example Configuration

- Example Code° In-Out, Out-Only° - Example Configuration

- Example Code° In-Optional-Out, Out-Optional-In° - Example Configuration

- Example Code° In-Out, Out-In° - Example Configuration

- Example Code° In-Optional-Out, Out-Only° - Example Configuration

- Example Code• Advanced Patterns• ° In-Optional-Out, Out-Only (Async Reply Router)

° - Example Configuration- Example Code

° In-Out, Out-Only (Async Reply Router)° - Example Configuration

- Example Code° Orchestration Using Component Bindings° - Example Configuration

- Example Code• What Next?• ° Possible MuleClient Changes

° Simplifying the Client

Page 629: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 629

Message Exchange Patterns in Mule

Message Exchange Patterns (MEPs) as defined as part of the WSDL specifications and provide a set ofwell-defined interaction patterns between client and server. When talking about ESBs or EAI there aretypically a number of services that collaborate and the definition of which service is the client and whichis the server becomes blurred. This document describes a way of describing Mule interactions (messagingstyles) using the well-known MEPs.

Focus on Services

Web Services MEPs talk about client and server. Clients make requests to a server and (may) get a result,whilst the server will receive data from a client (and sometimes may push data to a client). On the otherhand, Mule like other SOA-centric platforms focus on services. This means the world is viewed in terms ofdata coming into and sent out of a service. The service could be viewed as a client or a server dependingon whether data flowing inbound or outbound. Thus, it makes a lot of sense to model service interactionson the inbound and outbound separately.

The way to think about this is that we are defining MEPs between two parties, it doesn't matter if it's aclient or server, a service or legacy application that initiates or is the recipient of a request. And a requestis just an event, something that was triggered by a local or external process. By defining MEPs on theinbound and outbound we can go on to define a set of combined MEPs (in and out) for Mule.

The diagram above shows a party (Application or Mule) that initiates a request. This gets receive by aservice inbound endpoint. Next the component is invoked and the result is routed via the outbound routerto another party (Application or Mule).

WSDL MEPs

Before we go any further lets introduce the MEPs defined in the WSDL 1.1 and WSDL 2.0 specifications.

Pattern Description

In-only This is equivalent to one-way or asynchronous. Astandard one-way messaging exchange where theconsumer sends a message to the provider thatprovides only a status response.

Robust-In-Only This pattern is for guaranteed one-way messageexchanges. The consumer initiates with amessage. The provider can responds with statusor a fault. Note Guaranteed only means that theconsumer knows if the message got delivered.Don't confuse this with reliable.

Page 630: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 630

In-Out This is equivalent to request-response. A standardtwo-way message exchange where the consumerinitiates with a message, the provider respondswith a message or fault.

In-Optional-Out A standard two-way message exchange where theprovider's response is optional.

Extended MEPs (WSDL 2.0)

Pattern Description

Out-Only The provider (server) initiates the message to theclient

Robust-Out-Only The provider initiates the message to the clientand the client must respond with either a statusor a fault.

Out-In The provider initiates a call and the client mustrespond.

Out-Optional-In The provider initiates the call and the client canchoose to respond.

Mule MEPs

The following sections will introduce each exchange pattern in Mule based on the convention definedabove. Each pattern will either have an inbound MEP, outbound MEP or both. It is possible to havemultiple inbound and outbound MEPS for a single service, this will be discussed later on.For the sake of clarity each pattern is described in terms of what interactions will occur for each scenario.For those familiar with Mule, I will provide examples of the equivalent configuration in Mule. The plan forthis document is to come up with a simpler configuration for these MEPs in Mule.

Notation

Each pattern below is presented with a diagram that depicts the message flow for the pattern using thediagram notation above. Each pattern also has a description and further information below it. Then thereis an XML configuration for each. Note that all components are written using Groovy just so that thecomponents are transparent for the user. Finally, there is a code example for each which shows how atest-case is written to test each pattern.

Page 631: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 631

In-Only

Description Receives a message from another party. No resultis expected and any result returned from theservice will be ignored.

Error Handling If an error occurs it is handled by theExceptionStrategy configured on either theservice or the model. An error endpoint can beused to route errors and the party that initiatedthe call can listen on the error endpoint.

Mule Config The Mule service must have an asynchronousinbound endpoint and no outbound routersconfigured.

Example Configuration

Click here to expand...

<description> Receives a message from another party. No result is expected and any result returned from the service will be ignored. </description>

<vm:endpoint path="test.inbound" name="inboundEndpoint" synchronous="false"/>

<model> <service name="In-Only-Service"> <inbound> <vm:inbound-endpoint ref="inboundEndpoint"/> </inbound> <script:component> <script:script engine="groovy"> import org.mule.tck.functional.FunctionalTestNotification

muleContext.fireNotification(new FunctionalTestNotification( src, FunctionalTestNotification.EVENT_RECEIVED)); </script:script> </script:component> </service> </model>

Page 632: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 632

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...

public class InOnlyTestCase extends FunctionalTestCase{ public static final long TIMEOUT = 3000;

protected String getConfigResources() { return "org/mule/test/integration/messaging/meps/pattern_In-Only.xml"; }

public void testExchange() throws Exception { MuleClient client = new MuleClient();

final Latch latch = new Latch(); client.getMuleContext().registerListener(new FunctionalTestNotificationListener() { public void onNotification(ServerNotification notification) { latch.countDown(); } });

client.dispatch("inboundEndpoint", "some data", null); assertTrue(latch.await(TIMEOUT, TimeUnit.MILLISECONDS)); }}

In-Out

Description Receives a message from another party andthe result of the service invocation is returned.If the service returns null a message with aNullPayload payload is returned.

Error Handling A response message is alwayssent back. Clients can check theMuleMessage.getExceptionPayload() property

Page 633: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 633

to get all information about the service error. Ifan exception originates from the callee side, theexception will be thrown and can be caught by thecallee.

Mule Config The Mule service must have an synchronousinbound endpoint and no outbound routersconfigured.

Example Configuration

Click here to expand...

<description> Receives a message from another party and the result of the service invocation is returned. If the service returns null a message with a NullPayload payload is returned. </description>

<http:endpoint name="inboundEndpoint" host="localhost" port="8081" synchronous="true"/> <model> <service name="In-Out-Service"> <inbound> <http:inbound-endpoint ref="inboundEndpoint"/> </inbound> <script:component> <script:script engine="groovy"> if (message.getProperty("foo")) return "foo header received" else return "foo header not received" </script:script> </script:component> </service> </model>

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...

public class InOutTestCase extends FunctionalTestCase{ public static final long TIMEOUT = 3000;

protected String getConfigResources() { return "org/mule/test/integration/messaging/meps/pattern_In-Out.xml"; }

public void testExchange() throws Exception { MuleClient client = new MuleClient();

MuleMessage result = client.send("inboundEndpoint", "some data", null); assertNotNull(result); assertEquals("foo header not received", result.getPayloadAsString());

Page 634: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 634

Map props = new HashMap(); props.put("foo", "bar"); result = client.send("inboundEndpoint", "some data", props); assertNotNull(result); assertEquals("foo header received", result.getPayloadAsString()); }}

In-Out (async)

Description Receives a message from another party and theresult of the service invocation is returned viaa back channel. This measn that an inboundand response communication channel is used.If the service returns null a message with aNullPayload payload is returned.

Error Handling A response message is alwayssent back. Clients can check theMuleMessage.getExceptionPayload() propertyto get all information about the service error. Ifan exception originates from the callee side, theexception will be thrown and can be caught by thecallee.

Mule Config The Mule service must have an asynchronousinbound endpoint and no outbound routersconfigured. Additionally the callee mustconfigure a MULE_REPLY_TO header or a replyto destination understood by the transport beingused i.e. For JMS JMSReplyTo property on thejavax.jms.Message.

Example Configuration

Click here to expand...

<description> A request is made from a party but the result of the request is returned on another channel as specified either as a MULE_REPLY_TO header or a reply to destination understood by the transport beingused (JMSReplyTo). </description>

Page 635: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 635

<jms:activemq-connector name="jmsConnector"/>

<jms:endpoint queue="test.inbound" name="inboundEndpoint" synchronous="true"/>

<model> <service name="In-Out-Async-Service"> <inbound> <inbound-endpoint ref="inboundEndpoint"/> </inbound> <script:component> <script:script engine="groovy"> message.setProperty("foo", "bar"); return "got it!" </script:script> </script:component> <!-- Mule will now read the ReplyTo header on the message and send the response there. --> </service> </model>

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...

public class InOutAsyncTestCase extends FunctionalTestCase{ public static final long TIMEOUT = 3000;

protected String getConfigResources() { return "org/mule/test/integration/messaging/meps/pattern_In-Out-Async.xml"; }

public void testExchange() throws Exception { MuleClient client = new MuleClient(); Map props = new HashMap(); //Almost any endpoint can be used here props.put(MuleProperties.MULE_REPLY_TO_PROPERTY, "jms://client-reply");

MuleMessage result = client.send("inboundEndpoint", "some data", props); assertNotNull(result); assertEquals("got it!", result.getPayloadAsString());

assertNotNull(result.getProperty("foo")); assertEquals("bar", result.getProperty("foo")); }}

Page 636: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 636

In-Optional-Out

Description Receives a message from another party and theresult of the service invocation is returned. If theservice returns null and there was no error whileprocessing the request, nothing is returned to thecallee.

Error Handling If an error occurs while the service isprocessing the request a response messageis always sent back. Clients can check theMuleMessage.getExceptionPayload() propertyto get all information about the service error. Ifan exception originates from the callee side, theexception will be thrown and can be caught by thecallee.

Mule Config The Mule service must have an synchronousinbound endpoint and no outbound routersconfigured.

Example Configuration

Click here to expand...

<description> Receives a message from another party and the result of the service invocation is returned. If theservice returns null and there was no error while processing the request, nothing is returned to the caller. </description>

<http:endpoint name="inboundEndpoint" host="localhost" port="8081" synchronous="true"/>

<model> <service name="In-Optional-Out-Service"> <inbound> <inbound-endpoint ref="inboundEndpoint"/> </inbound> <script:component> <script:script engine="groovy"> if (message.getProperty("foo")) return "foo header received" else return null </script:script>

Page 637: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 637

</script:component> </service> </model>

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...

public class InOptionalOutTestCase extends FunctionalTestCase{ public static final long TIMEOUT = 3000;

protected String getConfigResources() { return "org/mule/test/integration/messaging/meps/pattern_In-Optional-Out.xml"; }

public void testExchange() throws Exception { MuleClient client = new MuleClient();

MuleMessage result = client.send("inboundEndpoint", "some data", null); assertNotNull(result); assertEquals(StringUtils.EMPTY, result.getPayloadAsString());

Map props = new HashMap(); props.put("foo", "bar"); result = client.send("inboundEndpoint", "some data", props); assertNotNull(result); assertEquals("foo header received", result.getPayloadAsString()); }}

In-Only, Out-Only

Description Receives a message from another party but willnot return a result. The service component mustalways return a result.

Page 638: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 638

Error Handling If an error occurs it is handled by theExceptionStrategy configured on either theservice or the model. An error endpoint can beused to route errors and the party that initiatedthe call can listen on the error endpoint.

Mule Config The Mule service must have an asynchronousinbound endpoint and at least one outboundrouters configured.

Example Configuration

Click here to expand...

<description> Receives a message from another party and the result of the service invocation is returned. If theservice returns null, a message with a NullPayload payload is returned.

MEP TODO: If a message does not originate from the service an exception should be thrown. </description>

<vm:connector name="vmConnector" queueEvents="true"/>

<vm:endpoint path="test.inbound" name="inboundEndpoint" synchronous="false"/> <vm:endpoint path="test.header.received" name="receivedEndpoint" synchronous="false"/> <vm:endpoint path="test.header.notreceived" name="notReceivedEndpoint" synchronous="false"/>

<model> <service name="In-Only_Out-Only-Service"> <inbound> <vm:inbound-endpoint ref="inboundEndpoint"/> </inbound> <script:component> <script:script engine="groovy"> if (message.getProperty("foo")!=null) return "foo header received" else

return "foo header not received" </script:script> </script:component> <outbound> <filtering-router> <vm:outbound-endpoint ref="receivedEndpoint"/> <wildcard-filter pattern="* header received"/> </filtering-router> <filtering-router> <vm:outbound-endpoint ref="notReceivedEndpoint"/> <wildcard-filter pattern="* header not received"/> </filtering-router> </outbound> </service> </model>

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...

Page 639: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 639

public class InOnlyOutOnlyTestCase extends FunctionalTestCase{ public static final long TIMEOUT = 3000;

protected String getConfigResources() { return "org/mule/test/integration/messaging/meps/pattern_In-Only_Out-Only.xml"; }

public void testExchange() throws Exception { MuleClient client = new MuleClient();

client.dispatch("inboundEndpoint", "some data", null); Map props = new HashMap(); props.put("foo", "bar"); client.dispatch("inboundEndpoint", "some data", props);

MuleMessage result = client.request("receivedEndpoint", TIMEOUT); assertNotNull(result); assertEquals("foo header received", result.getPayloadAsString());

result = client.request("notReceivedEndpoint", TIMEOUT); assertNotNull(result); assertEquals("foo header not received", result.getPayloadAsString());

}}

In-Only, Optional-Out

Description Receives a message from another party but willnot return a result. If the service component doesreturn a result then a the result will be sent onotherwise nothing further happens.

Error Handling If an error occurs it is handled by theExceptionStrategy configured on either theservice or the model. An error endpoint can beused to route errors and the party that initiatedthe call can listen on the error endpoint.

Page 640: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 640

Mule Config The Mule service must have an asynchronousinbound endpoint and at least one outboundrouters configured.

Example Configuration

Click here to expand...

<description> Receives a message from another party but will not return a result. The service component mustalways return a result. </description>

<vm:connector name="vmConnector" queueEvents="true"/>

<vm:endpoint path="test.inbound" name="inboundEndpoint" synchronous="false"/> <vm:endpoint path="test.header.received" name="receivedEndpoint" synchronous="false"/> <vm:endpoint path="test.header.notreceived" name="notReceivedEndpoint" synchronous="false"/>

<model> <service name="In-Only_Optional-Out--Service"> <inbound> <vm:inbound-endpoint ref="inboundEndpoint"/> </inbound> <script:component> <script:script engine="groovy"> if (message.getProperty("foo")) return "foo header received" else return null </script:script> </script:component> <outbound> <filtering-router> <vm:outbound-endpoint ref="receivedEndpoint"/> <wildcard-filter pattern="* header received"/> </filtering-router> <filtering-router> <vm:outbound-endpoint ref="notReceivedEndpoint"/> <wildcard-filter pattern="* header not received"/> </filtering-router> </outbound> </service> </model>

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...

public class InOnlyOptionalOutTestCase extends FunctionalTestCase{ public static final long TIMEOUT = 3000;

protected String getConfigResources() { return "org/mule/test/integration/messaging/meps/pattern_In-Only_Optional-Out.xml";

Page 641: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 641

}

public void testExchange() throws Exception { MuleClient client = new MuleClient();

client.dispatch("inboundEndpoint", "some data", null); Map props = new HashMap(); props.put("foo", "bar"); client.dispatch("inboundEndpoint", "some data", props);

MuleMessage result = client.request("receivedEndpoint", TIMEOUT); assertNotNull(result); assertEquals("foo header received", result.getPayloadAsString());

result = client.request("notReceivedEndpoint", TIMEOUT); assertNull(result); }}

In-Out, Out-Only

Description Receives a message from another party andreturns a result from the service. Additionallythe same result will be router via the serviceoutbound routers.

Error Handling If an error occurs it is handled by theExceptionStrategy configured on either theservice or the model. An error endpoint can beused to route errors and the party that initiatedthe call can listen on the error endpoint. Theexception and context information will be attachedto the return message, however the message willnot be routed by the outbound endpoint.

Mule Config The Mule service must have a synchronousinbound endpoint and at least one outboundrouters configured.

Example Configuration

Click here to expand...

Page 642: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 642

<description> Receives a message from another party and returns a result from the service. Additionally the sameresult will be routed via the service outbound routers. </description>

<vm:connector name="vmConnector" queueEvents="true"/>

<vm:endpoint path="test.inbound" name="inboundEndpoint" synchronous="true"/> <vm:endpoint path="test.header.received" name="receivedEndpoint" synchronous="false"/> <vm:endpoint path="test.header.notreceived" name="notReceivedEndpoint" synchronous="false"/>

<model> <service name="In-Out_Out-Only-Service"> <inbound> <vm:inbound-endpoint ref="inboundEndpoint"/> </inbound> <script:component> <script:script engine="groovy"> if (message.getProperty("foo")!=null) return "foo header received" else return "foo header not received" </script:script> </script:component> <outbound> <filtering-router> <vm:outbound-endpoint ref="receivedEndpoint"/> <wildcard-filter pattern="* header received"/> </filtering-router> <filtering-router> <vm:outbound-endpoint ref="notReceivedEndpoint"/> <wildcard-filter pattern="* header not received"/> </filtering-router> </outbound> </service> </model>

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...

public class InOutOutOnlyTestCase extends FunctionalTestCase{ public static final long TIMEOUT = 3000;

protected String getConfigResources() { return "org/mule/test/integration/messaging/meps/pattern_In-Out_Out-Only.xml"; }

public void testExchange() throws Exception { MuleClient client = new MuleClient();

MuleMessage result = client.send("inboundEndpoint", "some data", null); assertNotNull(result); assertEquals("foo header not received", result.getPayloadAsString());

Page 643: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 643

Map props = new HashMap(); props.put("foo", "bar"); result = client.send("inboundEndpoint", "some data", props); assertNotNull(result); assertEquals("foo header received", result.getPayloadAsString());

result = client.request("receivedEndpoint", TIMEOUT); assertNotNull(result); assertEquals("foo header received", result.getPayloadAsString());

result = client.request("notReceivedEndpoint", TIMEOUT); assertNotNull(result); assertEquals("foo header not received", result.getPayloadAsString());

}}

In-Optional-Out, Out-Optional-In

Description Receives a message from another party. Theservice processes the message and then it getsrouted via the outbound router. The outboundrouter will wait for a result from the call and willreturn the result to the originating party if oneis received. This pattern is analogous to usingRemote Sync on a Mule endpoint. If no result isreturned from the outbound call, null is returned.

Error Handling If an error occurs it is handled by theExceptionStrategy configured on either theservice or the model. An error endpoint can beused to route errors and the party that initiatedthe call can listen on the error endpoint. Theexception and context information will be attachedto the return message. If there was no result aNullPayload message will be returned with theexception information attached.

Mule Config The Mule service must have a synchronousinbound endpoint and an outbound routerconfigured.

Example Configuration

Page 644: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 644

Click here to expand...

<description> Receives a message from another party. The service processes the message and then it gets routedvia the outbound router. The outbound router will wait for a result from the call and will return theresult to the originating party if one is received. If no result is returned from the outbound call, nullis returned. </description>

<jms:activemq-connector name="amq"/>

<vm:connector name="vmConnector" queueEvents="true"/>

<vm:endpoint path="test.inbound" name="inboundEndpoint" synchronous="true"/>

<jms:endpoint queue="external.app" name="ExternalEndpoint" synchronous="true" responseTimeout="3000"/>

<model> <service name="In-Optional-Out_Out-Optional-In-Service"> <inbound> <vm:inbound-endpoint ref="inboundEndpoint"/> </inbound> <script:component> <script:script engine="groovy"> if (message.getProperty("foo") != null) { message.setProperty("bar", "baz") return message } else return message </script:script> </script:component> <outbound> <pass-through-router> <outbound-endpoint ref="ExternalEndpoint"/> <!-- Mule will automatically listen on this destination when synchronous is true. If this is not set, a temprary destination is set up --> <!--<reply-to address="jms://reply"/>--> </pass-through-router> </outbound> </service>

<service name="Mock-External-App"> <inbound> <inbound-endpoint ref="ExternalEndpoint"/> </inbound> <script:component> <script:script engine="groovy"> message.setProperty("externalApp", "Received") if (message.getProperty("bar") != null) return "bar header received" else return null </script:script> </script:component> </service> </model>

Page 645: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 645

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...

public class InOptionalOutOutOptionalInTestCase extends FunctionalTestCase{ public static final long TIMEOUT = 3000;

protected String getConfigResources() { return "org/mule/test/integration/messaging/meps/pattern_In-Optional-Out_Out-Optional-In.xml"; }

public void testExchange() throws Exception { MuleClient client = new MuleClient();

MuleMessage result = client.send("inboundEndpoint", "some data", null); assertNotNull(result); assertEquals(NullPayload.getInstance(), result.getPayload()); assertEquals("Received", result.getProperty("externalApp"));

Map props = new HashMap(); props.put("foo", "bar"); result = client.send("inboundEndpoint", "some data", props); assertNotNull(result); assertEquals("bar header received", result.getPayload()); assertEquals("Received", result.getProperty("externalApp")); }}

In-Out, Out-In

Description Receives a message from another party. Theservice processes the message and then it getsrouted via the outbound router. The outboundrouter will wait for a result from the call and willreturn the result to the originating party if oneis received. This pattern is analogous to usingRemote Sync on a Mule endpoint. If a result is not

Page 646: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 646

returned from the outbound call an error will bethrown.

Error Handling If an error occurs it is handled by theExceptionStrategy configured on either theservice or the model. An error endpoint can beused to route errors and the party that initiatedthe call can listen on the error endpoint. Theexception and context information will be attachedto the return message if there is a result.

Mule Config The Mule service must have a synchronousinbound endpoint and an outbound routerconfigured.

Example Configuration

Click here to expand...

<description> Receives a message from another party. The service processes the message and then it gets routedvia the outbound router. The outbound router will wait for a result from the call and will return theresult to the originating party if one is received. If a result is not returned from the outbound call anerror will be thrown. </description>

<jms:activemq-connector name="amq"/>

<vm:connector name="vmConnector" queueEvents="true"/>

<vm:endpoint path="test.inbound" name="inboundEndpoint" synchronous="true"/>

<jms:endpoint queue="external.app" name="ExternalEndpoint" synchronous="true" responseTimeout="3000"/>

<model> <service name="In-Out_Out-In-Service"> <inbound> <vm:inbound-endpoint ref="inboundEndpoint"/> </inbound> <script:component> <script:script engine="groovy"> message.setProperty("bar", "baz") return message </script:script> </script:component> <outbound> <pass-through-router> <outbound-endpoint ref="ExternalEndpoint"/> <!-- Mule will automatically listen n this destination when synchronous is true. If this is not set, a temporary destination is set up. --> <!--<reply-to address="jms://reply"/>--> </pass-through-router> </outbound> </service>

<service name="Mock-External-App"> <inbound> <inbound-endpoint ref="ExternalEndpoint"/> </inbound> <script:component> <script:script engine="groovy"> message.setProperty("externalApp", "Received")

Page 647: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 647

if (message.getProperty("bar") != null) return "bar header received" </script:script> </script:component> </service> </model>

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...

public class InOutOutInTestCase extends FunctionalTestCase{ public static final long TIMEOUT = 3000;

protected String getConfigResources() { return "org/mule/test/integration/messaging/meps/pattern_In-Out_Out-In.xml"; }

public void testExchange() throws Exception { MuleClient client = new MuleClient();

Map props = new HashMap(); props.put("foo", "bar"); MuleMessage result = client.send("inboundEndpoint", "some data", props); assertNotNull(result); assertEquals("bar header received", result.getPayload()); }}

In-Optional-Out, Out-Only

Description Receives a message from another party. Theservice processes the message and then it getsrouted via the outbound router. If a result isreturned from the component it is returned backto the calling party.

Page 648: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 648

Error Handling If an error occurs it is handled by theExceptionStrategy configured on either theservice or the model. An error endpoint can beused to route errors and the party that initiatedthe call can listen on the error endpoint. Theexception and context information will be attachedto the return message if there is a result.

Mule Config The Mule service must have a synchronousinbound endpoint and an outbound routerconfigured with an endpoint.

Example Configuration

Click here to expand...

<description> Receives a message from another party. The service processes the message and then it gets routedvia the outbound router. If a result is returned from the component it is returned back to the callingparty. </description>

<vm:connector name="vmConnector" queueEvents="true"/>

<vm:endpoint path="test.inbound" name="inboundEndpoint" synchronous="true"/> <vm:endpoint path="test.header.received" name="receivedEndpoint" synchronous="false"/> <vm:endpoint path="test.header.notreceived" name="notReceivedEndpoint" synchronous="false"/>

<model> <service name="In-Optional-Out_Out-Only-Service"> <inbound> <vm:inbound-endpoint ref="inboundEndpoint"/> </inbound> <script:component> <script:script engine="groovy"> if (message.getProperty("foo") != null) return "foo header received" else return null </script:script> </script:component> <outbound> <pass-through-router> <outbound-endpoint ref="receivedEndpoint"/> </pass-through-router> </outbound> </service> </model>

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...

public class InOptionalOutOutOnlyTestCase extends FunctionalTestCase{ public static final long TIMEOUT = 3000;

Page 649: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 649

protected String getConfigResources() { return "org/mule/test/integration/messaging/meps/pattern_In-Optional-Out_Out-Only.xml"; }

public void testExchange() throws Exception { MuleClient client = new MuleClient();

MuleMessage result = client.send("inboundEndpoint", "some data", null); assertNotNull(result); assertEquals(NullPayload.getInstance(), result.getPayload());

Map props = new HashMap(); props.put("foo", "bar"); result = client.send("inboundEndpoint", "some data", props); assertNotNull(result); assertEquals("foo header received", result.getPayload()); }}

Advanced Patterns

In-Optional-Out, Out-Only (Async Reply Router)

Description Receives a message from another party andprocesses the message. Then the message is sentto another service (or application) for processing.A Reply-To endpoint is attached to the messageand this is used by the second service to returna result. Note that if the external service is not aMule instance the protocol being used will ahveto ahve the notion of a back channel or reply-todestination, i.e. JMS, WS-Addressing, Socket-bsedprotocols.Since the response is optional, the <async-reply>router timeout should be reduced since, it willblock for the whole time if no reply is given.

Page 650: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 650

This MEP combination should ONLY be used inlow message volume scenarios. In high volumescenarios the pattern MEPs#In-Out, Out-Only(Async Reply Router) should be used and aresponse always returned, even if it is an emptyor acknowledgment message.

Error Handling A response message is always sent backif an error occurs. Clients can check theMuleMessage.getExceptionPayload() propertyto get all information about the service error. Ifan exception originates from the callee side, theexception will be thrown and can be caught by thecallee.

Mule Config The Mule service must have an synchronousinbound endpoint, at least outbound routersconfigured with a reply-to endpoint and anAsync Reply router to listen on the reply toendpoint. Only the inbound endpoint needs to besynchronous al others can be asynchronous.

Example Configuration

Click here to expand...

<description> Receives a message from another party and processes the message. The message is then sent toanother service (or application) for processing. A Reply-To endpoint is attached to the message and thisis used by the second service to return a result. Note that if the external service is not a Mule instancethe protocol being used will have to have the notion of a back channel or reply-to destination, i.e. JMS,WS-Addressing, Socket-based protocols. Since the response is optional, the <async-reply> routertimeout should be reduced, since it will block for the whole time if no reply is given.

This MEP combination should *ONLY* be used in low message volume scenarios. In high volume scenarios thepattern In-Out, Out-Only (async) should be used and a response always returned, even if it is an emptyacknowledgment message.

Note: this fails with ActiveMQ because of an outstanding issue on the part of ActiveMQ for handlingtemporary destinations. </description>

<vm:connector name="vmConnector" queueEvents="true"/>

<vm:endpoint path="test.inbound" name="inboundEndpoint" synchronous="true"/> <vm:endpoint path="test.external.app" name="externalEndpoint" synchronous="false"/> <vm:endpoint path="test.reply" name="replyEndpoint" synchronous="false"/>

<model> <service name="In-Out_Out-Only-Async-Service"> <inbound> <inbound-endpoint ref="inboundEndpoint"/> </inbound> <script:component> <script:script engine="groovy"> if (message.getProperty("foo") != null) return message else { //This shouldn't be needed but null does not stop the async-reply... eventContext.setStopFurtherProcessing(true) return null }

Page 651: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 651

</script:script> </script:component>

<outbound> <filtering-router> <outbound-endpoint ref="externalEndpoint"/> <reply-to ref="replyEndpoint"/> </filtering-router> </outbound>

<async-reply failOnTimeout="false" timeout="2000"> <inbound-endpoint ref="replyEndpoint"/> <single-async-reply-router/> </async-reply>

</service>

<service name="ExternalApp"> <inbound> <inbound-endpoint ref="externalEndpoint"/> </inbound> <test:component> <test:return-data>got it!</test:return-data> </test:component> </service> </model>

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...

public class InOptionalOutOutOnlyAsyncRouterTestCase extends FunctionalTestCase{ public static final long TIMEOUT = 3000;

protected String getConfigResources() { return "org/mule/test/integration/messaging/meps/pattern_In-Optional-Out_Out-Only-Async-Router.xml"; }

public void testExchange() throws Exception { MuleClient client = new MuleClient();

MuleMessage result = client.send("inboundEndpoint", "some data", null); assertNotNull(result); assertEquals(NullPayload.getInstance(), result.getPayload()); assertNull(result.getExceptionPayload());

Map props = new HashMap(); props.put("foo", "bar"); result = client.send("inboundEndpoint", "some data", props); assertNotNull(result); assertEquals("got it!", result.getPayloadAsString());

assertNotNull(result.getProperty("foo")); assertEquals("bar", result.getProperty("foo")); }

Page 652: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 652

}

In-Out, Out-Only (Async Reply Router)

Description Receives a message from another party andprocesses the message. Then the message is sentto another service (or application) for processing.A Reply-To endpoint is attached to the messageand this is used by the second service to returna result. Note that if the external service is not aMule instance the protocol being used will needto have the notion of a back channel or reply-to destination, i.e. JMS, WS-Addressing, Socket-based protocols.

Error Handling A response message is alwayssent back. Clients can check theMuleMessage.getExceptionPayload() propertyto get all information about the service error. Ifan exception originates from the callee side, theexception will be thrown and can be caught by thecallee.

Mule Config The Mule service must have an synchronousinbound endpoint, at least outbound routersconfigured with a reply-to endpoint and anAsync Reply router to listen on the reply toendpoint. Only the inbound endpoint needs to besynchronous al others can be asynchronous.

Example Configuration

Click here to expand...

<description> Receives a message from another party and processes the message. Then the message is sent toanother service (or application) for processing. A Reply-To endpoint is attached to the message and thisis used by the second service to return a result. Note that if the external service is not a Mule instance

Page 653: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 653

the protocol being used will need to have the notion of a back channel or reply-to destination, i.e. JMS,WS-Addressing, Socket-based protocols. </description>

<jms:activemq-connector name="jmsConnector"/>

<vm:endpoint path="test.inbound" name="inboundEndpoint" synchronous="true"/> <jms:endpoint queue="test.external.app" name="externalEndpoint" synchronous="false"/> <jms:endpoint queue="test.reply" name="replyEndpoint" synchronous="false"/>

<model> <service name="In-Out_Out-Only-Async-Service"> <inbound> <inbound-endpoint ref="inboundEndpoint"/> </inbound> <script:component> <script:script engine="groovy"> message.setProperty("foo", "bar") return message </script:script> </script:component>

<outbound> <filtering-router> <outbound-endpoint ref="externalEndpoint"/> <reply-to ref="replyEndpoint"/> </filtering-router> </outbound>

<async-reply failOnTimeout="true" timeout="4000"> <inbound-endpoint ref="replyEndpoint"/> <single-async-reply-router/> </async-reply>

</service>

<service name="ExternalApp"> <inbound> <inbound-endpoint ref="externalEndpoint"/> </inbound> <test:component> <test:return-data>got it!</test:return-data> </test:component> </service> </model>

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...

public class InOutOutOnlyAsyncRouterTestCase extends FunctionalTestCase{ public static final long TIMEOUT = 3000;

protected String getConfigResources() { return "org/mule/test/integration/messaging/meps/pattern_In-Out_Out-Only-Async-Router.xml"; }

public void testExchange() throws Exception

Page 654: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 654

{ MuleClient client = new MuleClient();

MuleMessage result = client.send("inboundEndpoint", "some data", null); assertNotNull(result); assertEquals("got it!", result.getPayloadAsString());

assertNotNull(result.getProperty("foo")); assertEquals("bar", result.getProperty("foo")); }}

Orchestration Using Component Bindings

TODO

Example Configuration

Click here to expand...

<description> Receives a message from another party but will not return a result. The service component willcall out to another service before sending the result out on the the outbound router. Bindings provide away to orchestrate flows between services. </description>

<vm:connector name="vmConnector" queueEvents="true"/>

<vm:endpoint path="test.inbound" name="inboundEndpoint" synchronous="false"/> <vm:endpoint path="addition.service" name="additionEndpoint" synchronous="true"/> <vm:endpoint path="test.received" name="receivedEndpoint" synchronous="false"/>

<model>

Page 655: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 655

<service name="In-Only_In-Out_Out-Only-Service"> <inbound> <vm:inbound-endpoint ref="inboundEndpoint"/> </inbound> <script:component> <script:script engine="groovy"> return "Total: " + AdditionService.add(payload) </script:script> <script:java-interface-binding interface="org.mule.tck.services.AdditionService" method="add"> <outbound-endpoint ref="additionEndpoint"/> </script:java-interface-binding> </script:component> <outbound> <filtering-router> <vm:outbound-endpoint ref="receivedEndpoint"/> </filtering-router> </outbound> </service>

<service name="Addition-Service"> <inbound> <vm:inbound-endpoint ref="additionEndpoint"/> </inbound> <component class="org.mule.tck.services.SimpleMathsComponent"/> </service> </model>

Example Code

The following example shows how to test the above configuration using a FunctionalTestCase.

Click here to expand...

public class BindingInOnlyInOutOutOnlyTestCase extends FunctionalTestCase{ public static final long TIMEOUT = 3000;

protected String getConfigResources() { return "org/mule/test/integration/messaging/meps/pattern_binding-In-Only_In-Out_Out-Only.xml"; }

public void testExchange() throws Exception { MuleClient client = new MuleClient();

client.dispatch("inboundEndpoint", new int[]{1,2,3,4,5}, null);

MuleMessage result = client.request("receivedEndpoint", TIMEOUT); assertNotNull(result); assertEquals("Total: 15", result.getPayloadAsString()); }}

What Next?

Mule can model every MEP combination that makes sense. What is difficult in Mule right now it to knowhow to do this. The logical next step would be to change the way endpoints are configured. Instead, of

Page 656: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 656

having the synchronous attribute on the endpoint, users could set an exchange attribute that woulddefine one of the options above. There are some obvious benefits:

• This method removes the complexity of the current configuration options• Using well defined exchange patterns explicitly will have readability of Mule configurations• Mule can provide much better validation over the correct MEP combinations that can be used with

different transports.

For example, depending on the transport being used developers could define endpoints such as:

<jms:inbound-endpoint queue="my.queue" exchange="In-Only"/>

<http:inbound-endpoint host="localhost" port="8080" path="/mule" exchange="In-Out"/>

Obviously, there would be a similar method for defining outbound endpoints:

<jms:outbound-endpoint queue="my.queue" exchange="Out-Only"/>

<http:inbound-endpoint host="localhost" port="8080" path="/mule" exchange="Out-In"/>

Possible MuleClient Changes

The Mule client is a common way for users to interact with Mule services. The MuleClient provides anumber of interfaces for sending or requesting information from an endpoint. These methods such asMuleClient.send, MuleClient.dispatch, MuleClient.request determine how the request is made.For example, using the send() methods causes a synchronous request and returns a result. Whiledispatch() causes an asynchronous request and does not return a result. So right now the MuleClient ispartly responsible (from the client-side) for how a MEP works in Mule.

Simplifying the Client

If Mule can have a MEP defined on the inbound and outbound, it become redundant to have theseadditional methods on the MuleClient. Instead, we could have a single exchange interface that will honorthe request based on the MEPs configured on the endpoints involved.

The Mule client code may look something like this:

MuleClient2 client = new MuleClient2();MuleExchange exchange = client.invoke("jms://topic:in", "some data", null);

MuleMessage result = exchange.getNextResultMessage();assertNotNull(result);assertEquals("some data received", result.getPayload());assertEquals(1, exchange.getresultsSize());//Get message historyassertEquals("some data", exchange.getSourceMessage().getPayload());

The MuleExchange object here provides an interface for all messages generated from the invocation.

If we wanted to configure the MuleExchange we might do the following:

MuleClient2 client = new MuleClient2();MuleExchange exchange = client.createExchange();exchange.setEnableHistory(false);

Page 657: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 657

client.invoke(exchange, "jms://topic:in", "some data", null);

MuleMessage result = exchange.getNextResultMessage();assertNotNull(result);assertEquals("some data received", result.getPayload());assertEquals(1, exchange.getresultsSize());//Message History disabledassertNull(exchange.getSourceMessage());

Page 658: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 658

Mule Messaging Styles

This page last changed on Mar 19, 2009 by jackie.wheeler.

Mule Messaging Styles

[ Overview ] [ Asynchronous ] [ Request Response ] [ Synchronous ] [ Async Request Response ]

Overview

Mule can send messages asynchronously (each stage of the message is on a different thread) orsynchronously (after the message is received by the component, it uses a single thread throughout therest of its lifecycle and supports request-response). You can set the synchronous property on the model,on the endpoint, and implicitly within the transport.

By default, Mule uses SEDA, which uses asynchronous staged queues. One thread is used for the inboundmessage, another thread is used for processing the message in the service component, and anotherthread is used for the outbound message. You can configure the message so that the inbound messageis on one thread and the remaining stages are on a second thread, or so that all stages are on a singlethread.

Mule also supports the request-response messaging style. In this case, there is no outbound router, sothe message is sent back to the same endpoint as the inbound endpoint, providing a reply back to thesender.

You can use a mix of synchronous and asynchronous messaging styles throughout Mule. You can alsouse a mix of styles for a single service component. For example, a service component can have multipleoutbound routers that route to different endpoints depending on filter criteria, and you might want themessage to be sent synchronously in some cases and asynchronously in others.

The rest of this page describes the various messaging styles in more detail and how to configure them. Itincludes reference to the message exchange patterns (MEPs) that each message style supports. For moreinformation on MEPs and Mule, see MEPs.

Asynchronous

Description Receives a message and puts it on a SEDA queue.The callee thread returns and the message isprocessed by the SEDA thread pool. Nothing getsreturned from the result of the call.

Error Handling If an error occurs it is handled by the Mule server.An error endpoint can be used to route errors andthe client that initiated the call can listen on theerror queue in a separate thread, other have aspecific error handling client.

Page 659: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 659

Mule Config The Mule service must have an asynchronousinbound endpoint.

Equivalent MEPs In-only

Discussion Points We have no way of supporting Robust In-only MEPoutside of web services (where in Mule you woulduse Request/Response) and define the MEP in theservice contract.

Example Configuration

Click here to expand...

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

<model name="Asynchronous_Message_Pattern"> <service name="AsynchronousService"> <inbound> <jms:inbound-endpoint queue="test.in" synchronous="false"/> </inbound> <test:component/> </service> </model></mule>

Request Response

Description Receives a message and the component returns amessage. If the component call returns null, thena MuleMessage with a NullPayload is returned.

Page 660: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 660

If the call method is void the request message isreturned.

Mule Config The Mule service must have a synchronousinbound endpoint and no outbound endpointconfigured. You set an endpoint as synchronoususing synchronous="true". HTTP/S, SSL, TCP,and Servlet endpoints are synchronous by defaultand do not require this setting.

Error Handling A response message is alwayssent back. Clients can check theMuleMessage.getExceptionPayload() to getall information about the server-side error. Ifan exception originates from the client call, theexception will be thrown.

Equivalent MEPs In-Out, In-Optional-Out

Discussion Points In-Optional-Out returns the request message ifthere is no result from the call. This is confusing.

Example Configuration

Click here to expand...

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

<model name="Request-Response_Message_Pattern"> <service name="SynchronousService"> <inbound> <http:inbound-endpoint host="localhost" port="8080" path="/mule/services" synchronous="true"/> </inbound> <test:component/> </service> </model></mule>

Page 661: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 661

Synchronous

Description Receives a message and the component processesbefore sending it out on another endpoint. Therequest happens in the same thread. Mule blockson the outbound endpoint to wait for a responsefrom the remote application (if applicable) untilthe responseTimeout threshold is reached. Ifno response is received, it returns null. Thesynchronous call must be used if transactionsare being used on the inbound endpoint. Asynchronous call always returns a result, even ifthere is an outbound endpoint.

Mule Config The Mule service must have a synchronousinbound endpoint and an outbound endpointconfigured. You set an endpoint as synchronoususing synchronous="true". HTTP/S, SSL, TCP,and Servlet endpoints are synchronous by defaultand do not require this setting.

Error Handling A response message is alwayssent back. Clients can check theMuleMessage.getExceptionPayload() to getall information about the server-side error. Ifan exception originates from the client call, theexception will be thrown.

Equivalent MEPs In-Only, In-Optional-Out, In-Out

Discussion Points Mule always returns the result from thecomponent back to the caller, as well as sending itout via the outbound endpoint.

Example Configuration

Click here to expand...

<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mule="http://www.mulesource.org/schema/mule/core/2.2" xmlns:jms="http://www.mulesource.org/schema/mule/jms/2.2" xmlns:test="http://www.mulesource.org/schema/mule/test/2.2" xmlns:spring="http://www.springframework.org/schema/beans" xsi:schemaLocation=" http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd

Page 662: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 662

http://www.mulesource.org/schema/mule/test/2.2 http://www.mulesource.org/schema/mule/test/2.2/mule-test.xsd http://www.mulesource.org/schema/mule/jms/2.2 http://www.mulesource.org/schema/mule/jms/2.2/mule-jms.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<model name="Synchronous_Message_Pattern"> <service name="SynchronousService"> <inbound> <jms:inbound-endpoint queue="test.in" synchronous="true"/> </inbound>

<test:component/>

<outbound> <pass-through-router> <jms:outbound-endpoint queue="test.out"/> </pass-through-router> </outbound> </service> </model></mule>

Async Request Response

Description This pattern enables Request Response messagingand allows the back-end process to be forked toinvoke other services and return a result basedon the results of multiple service invocations. TheAsync Reply Router is used to listen on a Reply Toendpoint for results.

Mule Config A <async-reply> element can be used to listenon a reply endpoint. There must also be at leastone outbound endpoint and the inbound endpointmust be synchronous. You set an endpoint assynchronous using synchronous="true". HTTP/S,SSL, TCP, and Servlet endpoints are synchronousby default and do not require this setting.

Error Handling A response message is alwayssent back. Clients can check theMuleMessage.getExceptionPayload() to get

Page 663: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 663

all information about the server-side error. Ifan exception originates from the client call, theexception will be thrown.

Equivalent MEPs In-Out, In-Optional-Out

Discussion Points None

Example Configuration

Click here to expand...

<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mule="http://www.mulesource.org/schema/mule/core/2.2" xmlns:http="http://www.mulesource.org/schema/mule/http/2.2" xmlns:jms="http://www.mulesource.org/schema/mule/jms/2.2" xmlns:test="http://www.mulesource.org/schema/mule/test/2.2" xmlns:scripting="http://www.mulesource.org/schema/mule/scripting/2.2" xmlns:spring="http://www.springframework.org/schema/beans" xsi:schemaLocation=" http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/test/2.2 http://www.mulesource.org/schema/mule/test/2.2/mule-test.xsd http://www.mulesource.org/schema/mule/http/2.2 http://www.mulesource.org/schema/mule/http/2.2/mule-http.xsd http://www.mulesource.org/schema/mule/jms/2.2 http://www.mulesource.org/schema/mule/jms/2.2/mule-jms.xsd http://www.mulesource.org/schema/mule/scripting/2.2 http://www.mulesource.org/schema/mule/scripting/2.2/mule-scripting.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<model name="Async_Request-Response_Message_Pattern"> <service name="AsyncRequestResponseService"> <inbound> <http:inbound-endpoint host="localhost" port="8080" path="/mule/services" synchronous="true"/> </inbound>

<test:component/>

<async-reply timeout="5000"> <collection-async-reply-router/> <jms:inbound-endpoint queue="reply.queue"/> </async-reply>

<outbound> <multicasting-router> <reply-to address="jms://reply.queue"/> <jms:outbound-endpoint queue="service1" synchronous="false"/> <jms:outbound-endpoint queue="service2" synchronous="false"/> </multicasting-router> </outbound> </service> </model></mule>

Page 664: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 664

Using Message Routers

This page last changed on Mar 05, 2009 by jackie.wheeler.

Using Message Routers

[ Quick Reference ] [ Mule Inbound Routers ] [ Mule Outbound Routers ] [ Asynchronous Reply Routers ][ Catch-all Strategies ] [ Filters ]

Message routers are used to control how messages are sent and received by components in the system.Mule defines inbound routers that apply to messages as they are received, and outbound routers that areinvoked when a message is being dispatched.

Mule provides flexible message routing support for your components. Routing features are based on theenterprise routing requirements described in EIP.

For information on how your Java or Script components can orchestrate messages, see ComponentBindings.

Quick Reference

Inbound Routers Outbound Routers Async-Reply Routers Catch All Strategies

No Router Pass-through Single Forwarding

Selective Consumer Filtering Collection Custom Fowarding

Idempotent Receiver Recipient List Routers Custom Logging

Idempotent SecureHash Receiver

Multicasting Custom

Collection Aggregator Chaining

Message ChunkingAggregator

List Message Splitter

Custom CorrelationAggregator

Filtering XML MessageSplitter

CorrelationResequencer

Expression SplitterRouter

Forwarding Message ChunkingRouter

WireTap Exception Based Router

Custom Template Endpoint

Round Robin XMLSplitter

Custom

Page 665: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 665

Mule Inbound Routers

When a message is received via an endpoint, the inbound router controls how and if this message getsrouted into the service. The following sections describe the Mule inbound routers and how to configurethem. For more detailed information on inbound router configuration elements and attributes, see theInbound Router Configuration Reference.

All inbound routers are configured on a service within the <inbound> element.

No Router

If no router is defined on the inbound, all messages received via the endpoints will be processed by theservice component.

<inbound> <jms:inbound-endpoint queue="foo.bar"/> <vm:inbound-endpoint path="foo.bar.local"/></inbound>

Selective Consumer

A selective consumer is an inbound router that can apply one or more filters to the incoming message. Ifthe filters match, the message is forwarded to the component. Otherwise, the message is forwarded tothe catch-all strategy on the router. If no catch-all is configured, the message is ignored and a warning islogged.

Configuration for this router is as follows:

<inbound> <selective-consumer-router> <mulexml:jxpath-filter expression="msg/header/resultcode = 'success'"/> </selective-consumer-router> <forwarding-catch-all-strategy> <jms:endpoint topic="error.topic"/> </forwarding-catch-all-strategy></inbound>

For information on using filters with this router, see Using Filters. Note that by default the filter is appliedto the message after the inbound transformers are applied. If you need to execute filters on the messagewithout applying any transformation, you can set the transformFirst property on this router to controlwhether transformations are applied.

<inbound> <forwarding-catch-all-strategy> <jms:endpoint topic="error.topic"/> </forwarding-catch-all-strategy> <selective-consumer-router transformFirst="false"> <mulexml:jxpath-filter expression="msg/header/resultcode = 'success'"/> </selective-consumer-router></inbound>

Page 666: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 666

Idempotent Receiver

An idempotent receiver ensures that only unique messages are received by a service by checking theunique message ID of the incoming message. The ID can be generated from the message using anexpression defined in the idExpression attribute. By default, the expression used is #[message:id],which means the underlying endpoint must support unique message IDs for this to work. Otherwise, aUniqueIdNotSupportedException is thrown.

There is a simple idempotent receiver implementation provided atorg.mule.routers.inbound.IdempotentReceiver . The default implementation uses a simple file-basedmechanism for storing message IDs, but you can extend this class to store the IDs in a database insteadby implementing the ObjectStore interface.

Configuration for this router is as follows:

<inbound> <idempotent-receiver-router idExpression="#[message:id]-#[header:foo]"> <simple-text-file-store directory="./idempotent"/> </idempotent-receiver-router></inbound>

The optional idExpression attribute determines what should be used as the unique message ID. If thisattribute is not used, #[message:id] is used by default.

The nested element shown above configures the location where the received message IDs are stored.In this example, they are stored to disk so that the router can remember state between restarts. If thedirectory attribute is not specified, the default value used is ${mule.working.dir}/objectstore wheremule.working.dir is the working directory configured for the Mule instance.

If no store is configured, the InMemoryObjectStore is used by default.

Idempotent Secure Hash Receiver

This router ensures that only unique messages are received by a service by calculating the hash of themessage itself using a message digest algorithm. This approach provides a value with an infinitesimallysmall chance of a collision and can be used to filter message duplicates. Note that the hash is calculatedover the entire byte array representing the message, so any leading or trailing spaces or extraneousbytes (like padding) can produce different hash values for the same semantic message content.Therefore, you should ensure that messages do not contain extraneous bytes. This router is useful whenthe message does not support unique identifiers.

Configuration for this router is as follows:

<inbound> <secure-hash-idempotent-receiver-router messageDigestAlgorithm="SHA26"> <simple-text-file-store directory="./idempotent"/> </secure-hash-idempotent-receiver-router></inbound>

Idempotent Secure Hash Receiver also uses object stores, which are configured the same way as theIdempotent Receiver. The optional messageDigestAlgorithm attribute determines the hashing algorithmthat will be used. If this attribute is not specified, the default algorithm SHA-256 is used.

Collection Aggregator

The Collection Aggregator groups incoming messages that have matching group IDs before forwardingthem. The group ID can come from the correlation ID or another property that links messages together.

Page 667: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 667

You can specify the timeout attribute to determine how long the router waits in milliseconds formessages to complete the group. By default, if the expected messages are not received by the timeouttime, an exception is thrown and the messages are not forwarded. As of Mule 2.2, you can set thefailOnTimeout attribute to false to prevent the exception from being thrown and simply forwardwhatever messages have been received so far.

The aggregator is based on the Selective Consumer, so you can also apply filters to the messages.Configuration for this router is as follows:

<inbound> <collection-aggregator-router timeout="6000" failOnTimeout="false"> <payload-type-filter expectedType="org.foo.some.Object"/> </collection-aggregator-router></inbound>

Message Chunking Aggregator

After an outbound router such as the Recipient List or List Message Splitter splits a message into parts,the message chunking aggregator router reassembles those parts back into a single message. Theaggregator uses the correlation ID, which is set by the outbound router, to identify which parts belong tothe same message. This aggregator is based on the Selective Consumer, so filters can also be applied tomessages.

Configuration for this router is as follows:

<inbound> <message-chunking-aggregator-router> <expression-message-info-mapping correlationIdExpression="#[header:correlation]"/> <payload-type-filter expectedType="org.foo.some.Object"/> </message-chunking-aggregator-router></inbound>

The optional expression-message-info-mapping element allows you to identify the correlation ID inthe message using an expression. If this element is not specified, MuleMessage.getCorrelationId() isused.

The Message Chunking aggregator also accepts the timeout and (as of Mule 2.2) failOnTimeoutattributes as described under Collection Aggregator.

Custom Correlation Aggregator

This router is used to configure a custom message aggregator. Mule provides an abstract implementationthat has a template method that performs the message aggregation. A common use of the aggregatorrouter is to combine the results of multiple requests such as "ask this set of vendors for the best price ofX".

The aggregator is based on the Selective Consumer, so you can also apply filters to messages. It alsoaccepts the timeout and (as of Mule 2.2) failOnTimeout attributes as described under CollectionAggregator.

Configuration for this router is as follows:

<inbound> <custom-correlation-aggregator-router class="org.mule.CustomAgregator"> <payload-type-filter expectedType="org.foo.some.Object"/> </custom-correlation-aggregator-router>

Page 668: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 668

</inbound>

There is an AbstractEventAggregator that provides a thread-safe implementation for custom aggregators,which you can can use to write a custom aggregator router. For example, the Loan Broker examplesincluded in the Mule distribution use a custom BankQuotesInboundAggregator router to aggregate bankquotes.

Correlation Resequencer

The Correlation Resequencer Router will hold back a group of messages and resequence them usingthe messages correlation sequence property. A java.util.Comparator is used to sort the messages.This router is based on the Selective Consumer, which means that filters can be applied to the incomingmessages. It also accepts the timeout and (as of Mule 2.2) failOnTimeout attributes as described underCollection Aggregator.

<inbound> <correlation-resequencer-router> <mulexml:jxpath-filter expression="msg/header/resultcode = 'success'"/> </correlation-resequencer-router></inbound>

Forwarding Router

This router allows messages to be forwarded to an outbound router without first being processed by acomponent. It essentially acts as a bridge between an inbound and an outbound endpoint. This is usefulin situations where the developer does not need to execute any logic on the inbound message but doesneed to forward it on to a component residing on another destination (such as a remote Mule node orapplication) over the network.

Configuration for this router is as follows:

<service name="FileReader"> <inbound> <file:inbound-endpoint path="/temp/myfiles/in"/> <forwarding-router/> </inbound> <echo-component/> <outbound> <tcp:outbound-endpoint host="192.168.0.6" port="12345"> <object-to-byte-array-transformer/> </tcp:outbound-endpoint> </outbound></service>

When a file becomes available on the local file system, an event is triggered that creates themessage, which is then automatically forwarded via TCP to 192.168.0.6. Notice that there is anoutboundTransformer configured. This will be used to transform the message's payload before it isdispatched over TCP. There is an echo component configured, but when the forwarding consumer is used,the component invocation is skipped, and the message is forwarded directly the the outbound router(s).

Configuring the service as a bridge is recommended for most forwarding scenarios. However, if you needto selectively forward only some events while others are processed by the component, you will need touse this router.

The Forwarding router extends the Selective Consumer, so you can configure filters on this router.

Page 669: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 669

Wiretap Router

See Using the WireTap Inbound Router.

Custom Inbound Router

You can configure custom inbound routers by specifying the custom router class on the <custom-inbound-router> element and by using Spring properties. Optionally, you can also configure anoutbound endpoint in case this is needed for implementing a custom wiretap router for example.

Configuration for this router is as follows:

<inbound> <custom-inbound-router class="org.my.CustomInboundRouter"> <mulexml:jxpath-filter expression="msg/header/resultcode = 'success'"/> <spring:properties> <spring:property key="key1" value="value1"/> <spring:property key="key2" value="value2"/> </spring:properties> <vm:outbound-endpoint path="out"/> </custom-inbound-router></inbound>

Mule Outbound Routers

After a message has been processed by a component, you use outbound routers to determine where tosend the message next. The following sections describe each Mule outbound router and how to configurethem. Outbound routers can be more complex to configure, as they allow different routing paths thatcan be selected depending on the logic defined in one or more filters. For more detailed informationon outbound router configuration elements and attributes, see the Outbound Router ConfigurationReference.

Pass-through Router

This router always matches and simply sends or dispatches message via the one endpoint it hasconfigured.

Configuration for this router is as follows:

2.0:

<outbound> <outbound-pass-through-router> <smtp:outbound-endpoint to="[email protected]"/> </outbound-pass-through-router></outbound>

2.1 and later:

<outbound> <pass-through-router> <smtp:outbound-endpoint to="[email protected]"/> </pass-through-router>

Page 670: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 670

</outbound>

Filtering Router

This router uses filters to determine whether this router will be used (see Filters below). The filteringrouter specifies only one endpoint to which messages are routed if the filter conditions are met. If youneed to specify more than one endpoint in a router, use a different outbound router and set filters on itsindividual endpoints.

Configuration for this router is as follows:

<outbound> <forwarding-catch-all-strategy> <jms:outbound-endpoint queue="error.queue"/> </forwarding-catch-all-strategy> <filtering-router> <smtp:outbound-endpoint to="[email protected]"/> <payload-type-filter expectedType="java.lang.Exception"/> </filtering-router> <filtering-router> <jms:outbound-endpoint queue="string.queue"/> <and-filter> <payload-type-filter expectedType="java.lang.String"/> <regex-filter pattern="the quick brown (.*)"/> </and-filter> </filtering-router></outbound>

The filter is applied to the message first, and then the transformers are applied. If you need to transformthe message before the filter is applied, you can set a transformer on this router that will be applied tothe message before the filter is applied.

<outbound> <filtering-router> <smtp:outbound-endpoint to="[email protected]"/> <payload-type-filter expectedType="java.lang.Exception"/> <transformer ref="aTransformer"/> </filtering-router></outbound>

Recipient List Routers

The recipient list routers can be used to send the same message to multiple endpoints over a singleendpoint, or to implement routing-slip behavior where the next destination for the message is determinedfrom message properties or the payload. Mule provides an abstract recipient list implementationorg.mule.routing.outbound.AbstractRecipientList , which provides a thread-safe base for specializedimplementations.

Mule provides a static recipient list router that takes a configured list of endpoints from the currentmessage or from a statically declared list on the endpoint.

Configuration for this router is as follows:

<outbound>

Page 671: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 671

<static-recipient-list-router> <payload-type-filter expectedType="javax.jms.Message"/> <recipients> <spring:value>jms://orders.queue</spring:value> <spring:value>jms://tracking.queue</spring:value> </recipients> </static-recipient-list-router></outbound>

Mule also provides an expression recipient list router, which allows you to create a static list as well asuse an expression to determine the list.

<outbound> <expression-recipient-list-router evaluator="headers-list" expression="recipient1,recipient2,recipient3"/></outbound>

Multicasting Router

The Multicasting router can be used to send the same message over multiple endpoints. When usingthis router, be sure to configure the correct transformers on the endpoints to handle the message sourcetype.

Configuration for this router is as follows:

<outbound> <multicasting-router> <jms:endpoint queue="test.queue" transformer-refs="StringToJmsMessage"/> <http:endpoint host="10.192.111.11" transformer-refs="StringToHttpClientRequest"/> <tcp:endpoint host="10.192.111.12" transformer-refs="StringToByteArray"/> <payload-type-filter expectedType="java.lang.String"/> </multicasting-router></outbound>

Chaining Router

The Chaining router can be used to send the message through multiple endpoints using the result of thefirst invocation as the input for the next. For example, this can be useful where you want to send theresults of a synchronous request-response invocation such as a Web service call to a JMS queue. Endpointtransformers can be used to transform the message to the format the next endpoint requires.

Configuration for this router is as follows:

<outbound> <chaining-router> <axis:outbound-endpoint address="http://localhost:8081/services/xyz?method=getSomething"/> <jms:outbound-endpoint queue="something.queue"> <transformer ref="SomethingToJmsMessage"/> </jms:outbound-endpoint> </chaining-router></outbound>

Page 672: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 672

List Message Splitter

A message splitter can be used to break down an outgoing message into parts and dispatch those partsover different endpoints configured on the router. The List Message Splitter accepts a list of objects thatwill be routed to different endpoints. The actual endpoint used for each object in the list is determined bya filter configured on the endpoint itself. If the endpoint's filter accepts the object, the endpoint will beused to route the object.

By default the AbstractMessageSplitter sets a correlation ID and correlation sequence on the outboundmessages so that inbound routers such as the Collection Aggregator or Correlation Resequencer are ableto resequence or combine the split messages.

The router configuration below expects the message payload to be a java.util.List and will routeobjects in the list that are of type com.foo.Order, com.foo.Item, and com.foo.Customer. The router willallow any number and combination of these objects.

Configuration for this router is as follows:

<outbound> <list-message-splitter-router"> <jms:outbound-endpoint queue="order.queue"> <payload-type-filter expectedType="com.foo.Order"/> </jms:outbound-endpoint> <jms:outbound-endpoint queue="item.queue"> <payload-type-filter expectedType="com.foo.Item"/> </jms:outbound-endpoint> <jms:outbound-endpoint queue="customer.queue"> <payload-type-filter expectedType="com.foo.Customer"/> </jms:outbound-endpoint> <payload-type-filter expectedType="java.util.List"/> </list-message-splitter-router></outbound>

Note that there is also a filter on the router itself that ensures that the message payload received isof type java.util.List. If there are objects in the list that do not match any of the endpoint filters,a warning is written to the log and processing continues. To route any non-matching object types toanother endpoint, add the endpoint at the end of the list without a filter.

Filtering XML Message Splitter

This router is similar to the List Message Splitter but operates on XML documents. Supported payloadtypes are:

• org.dom4j.Document objects• byte[]• java.lang.String

If no match is found, it is ignored and logged at the WARN level.

The router splits the payload into nodes based on the splitExpression property. The actual endpointused for each object in the list is determined by a filter configured on the endpoint itself. If the endpoint'sfilter accepts the object, the endpoint will be used to route the object. Each part returned is actuallyreturned as a new DOM4J document.

The router can optionally perform a validation against an external XML schema document. To perform thevalidation, set externalSchemaLocation to the XSD file in your classpath. Setting this property overrideswhatever schema document you declare in the XML header.

By default, the router fails if none of the endpoint filters match the payload. To prevent the router fromfailing in this case, you can set the failIfNoMatch attribute to false.

Page 673: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 673

Configuration for this router is as follows:

<outbound> <mulexml:filter-based-splitter splitExpression="root/nodes" validateSchema="true" externalSchemaLocation="/com/example/TheSchema.xsd"> <vm:outbound-endpoint path="order"> <payload-type-filter expectedType="com.foo.Order"/> </vm:outbound-endpoint> <vm:outbound-endpoint path="item"> <payload-type-filter expectedType="com.foo.Item"/> </vm:outbound-endpoint> <vm:outbound-endpoint path="customer"> <payload-type-filter expectedType="com.foo.Customer"/> </vm:outbound-endpoint> <payload-type-filter expectedType="org.dom4j.Document"/> </mulexml:filter-based-splitter></outbound>

Expression Splitter Router

This router is similar to the list message splitter router, but it splits the message based on an expression.The expression must return one or more message parts to be effective.

<outbound> <expression-splitter-router evaluator="xpath" expression="/mule:mule/mule:model/mule:service" disableRoundRobin="true" failIfNoMatch="false"> <outbound-endpoint ref="service1"> <expression-filter evaluator="xpath" expression="/mule:service/@name = 'service splitter'"/> </outbound-endpoint> <outbound-endpoint ref="service2"> <expression-filter evaluator="xpath" expression="/mule:service/@name = 'round robin deterministic'"/> </outbound-endpoint> </expression-splitter-router></outbound>

Round Robin Message Splitter

The round robin message splitter will split a DOM4J document into nodes based on the splitExpressionproperty. It will then send these document fragments to the list of endpoints specified in a round-robin fashion. Optionally, you can specify a namespaces property map that contain prefix/namespacemappings.

For instance, the following fragment will route the "/a:orders/a:order" nodes inside the document to therobin1 and robin2 endpoints.

<outbound> <mxml:round-robin-splitter splitExpression="/a:orders/a:order" deterministic="false"> <outbound-endpoint ref="robin1"/> <outbound-endpoint ref="robin2"/> <mxml:namespace prefix="a" uri="http://acme.com"/> </mxml:round-robin-splitter></outbound>

Page 674: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 674

The router can optionally perform a validation against an external XML schema document. To perform thevalidation, set externalSchemaLocation to the XSD file in your classpath. Setting this property overrideswhatever schema document you declare in the XML header.

<outbound> <mxml:round-robin-splitter splitExpression="/a:orders/a:order" deterministic="false" externalSchemaLocation="mySchema.xsd" validateSchema="true"> <outbound-endpoint ref="robin1"/> <outbound-endpoint ref="robin2"/> <mxml:namespace prefix="a" uri="http://acme.com"/> </mxml:round-robin-splitter></outbound>

Message Chunking Outbound Router

This routing pattern allows you to split a single message into a number of fixed-length messages thatwill all be routed to the same endpoint. It will split the message up into a number of smaller chunksaccording to the messageSize attribute that you configure for the router. If you do not configure amessageSize, or if it has a value of zero, the message will not be split up and the entire message will berouted to the destination endpoint as is. The router splits up the message by first converting it to a bytearray and then splitting this array into chunks. If the message cannot be converted into a byte array, aRoutingException is raised.

A message chunking router is useful if you have bandwidth problems (or size limitations) when usinga particular transport. If you want to be able to route different segments of the original message todifferent endpoints, consider using the List Message Splitter or Filtering XML Message Splitter routerinstead.

To put the chunked items back together again, you can use the Message Chunking Aggregator as theinbound router on the next service.

Sample Configuration

<service name="chunkingService"> <inbound> <vm:inbound-endpoint path="fromClient"/> </inbound> <outbound> <message-chunking-router messageSize="4"> <vm:outbound-endpoint path="toClient"/> </message-chunking-router> </outbound></service>

In the example above, any data received on the vm fromClient endpoint is chunked into messages fourbytes long before being sent along the vm toClient endpoint. If we sent "The quick brown fox jumpedover the lazy dog" to this service, anything listening on the vm toClient endpoint would receive thefollowing messages (the spaces have been replaced with underscores for better legibility):

Message # Contents

1 The_

2 quic

3 k_br

Page 675: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 675

4 own_

5 fox_

6 jump

7 ed_o

8 ver_

9 the_

10 lazy

11 _dog

Exception Based Router

The Exception Based router can be used to send a message over an endpoint by selecting the firstendpoint that can connect to the transport. This can be useful for setting up retries. When the firstendpoint fails, the second will be invoked, and if that fails, it will try the next endpoint. Note that thisrouter overrides the endpoint mode to synchronous while looking for a successful send and will resort tousing the endpoint's mode for the last item in the list.

Configuration for this router is as follows:

<outbound> <exception-based-router> <tcp:endpoint host="10.192.111.10" port="10001" /> <tcp:endpoint host="10.192.111.11" port="10001" /> <tcp:endpoint host="10.192.111.12" port="10001" /> </exception-based-router></outbound>

Template Endpoint Router

The template endpoint router allows endpoints to be altered at runtime based on properties set on thecurrent message or fallback values set on the endpoint properties. Templated values are expressed usingsquare brackets around a property name, such as:

axis:http://localhost:8082/MyService?method=[SOAP_METHOD]

Configuration for this router is as follows:

<outbound> <template-endpoint-router> <outbound-endpoint address="foobar://server:1234/path/path/path?param1=[header1]&param2=[header2]"/> </template-endpoint-router></outbound>

Page 676: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 676

The header1 and header2 parameters are substituted with the actual values from the current message.The parameters can be used only in the query string, as the square brackets are not valid characters forthe authority and path URI components.

Custom Outbound Router

You can configure custom outbound routers by specifying the custom router class on the <custom-outbound-router> element and by using Spring properties.

Configuration for this router is as follows:

<outbound> <custom-outbound-router class="org.my.CustomOutboundRouter" transformers-ref="Transformer1"> <tcp:endpoint host="10.192.111.10" port="10001" /> <tcp:endpoint host="10.192.111.11" port="10001" /> <mulexml:jxpath-filter expression="msg/header/resultcode = 'success'"/> <spring:properties> <spring:property key="key1" value="value1"/> <spring:property key="key2" value="value2"/> </spring:properties> </custom-outbound-router></outbound>

Asynchronous Reply Routers

Asynchronous reply routers are used in request/response scenarios where message traffic is triggeredby a request and the traffic needs to be consolidated before a response is given. The classic example ofthis is where a request is made and tasks are executed in parallel. Each task must finish executing andthe results processed before a response can be sent back. For detailed information on the elements youconfigure for asynchronous reply routers, see Asynchronous Reply Router Configuration Reference.

Asynchronous reply routers are configured as follows:

<async-reply failOnTimeout="false" timeout="2000"> <inbound-endpoint ref="replyEndpoint"/> <collection-async-reply-router/></async-reply>

The timeout attribute determines how long to wait for replies to be received. By default, if not allmessages are received before the timeout, an exception is thrown and no messages are sent. If you wantto have the router send whatever messages it has received so far and not throw an exception, set thefailOnTimeout attribute to false.

Single Asynchronous Reply

The Single Asynchronous Reply router configures a single response router. This router returns the firstmessage it receives on a reply endpoint and discards the rest.

<single-async-reply-router/>

Page 677: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 677

Collection Asynchronous Reply

The Collection Asynchronous Reply router configures a collection response router. This router returns aMuleMessageCollection message type that contains all messages received for the current correlation.

<collection-async-reply-router/>

Custom Asynchronous Reply

The Custom Asynchronous Reply router allows you to configure a custom asynchronous reply router. Toconfigure the custom router, set the class attribute to the custom router class.

<custom-async-reply-router class="org.mule.CustomAsyncReplyRouter"/>

Catch-all Strategies

You can configure a catch-all strategy that will be invoked if no routing path can be found for the currentmessage. An inbound or outbound endpoint can be associated with a catch-all strategy so that anyorphaned messages can be caught and routed to a common location. For detailed information on theelements you configure for catch-all strategies, see Catch All Strategy Configuration Reference.

For example:

<service name="dataService"> <inbound> <inbound-endpoint address="vm://in2" connector-ref="vmQueue"> <string-to-byte-array-transformer/> </inbound-endpoint>

<selective-consumer-router> <payload-type-filter expectedType="java.lang.Integer"/> </selective-consumer-router>

<custom-forwarding-catch-all-strategy class="org.mule.test.usecases.routing.InboundTransformingForwardingCatchAllStrategy"> <outbound-endpoint address="vm://catchall" connector-ref="vmQueue"> <string-to-byte-array-transformer/> </outbound-endpoint> </custom-forwarding-catch-all-strategy> </inbound> ... <outbound> <filtering-router transformer-refs="TestCompressionTransformer"> <outbound-endpoint address="test://appleQ2" name="TestApple-Out" /> <payload-type-filter expectedType="java.lang.String" /> </filtering-router> <custom-catch-all-strategy class="org.mule.tck.testmodels.mule.TestCatchAllStrategy" /> </outbound> ...</service>

Following are descriptions of the different catch-all strategies you can use.

Page 678: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 678

Forwarding

This catch-all strategy is used to forward the message to an endpoint that is configured if no outboundrouters match.

<forwarding-catch-all-strategy> <jms:outbound-endpoint queue="error.queue"/></forwarding-catch-all-strategy>

Custom Forwarding

This catch-all strategy is the same as the default forwarding catch-all strategy, but it allows you to specifya custom implementation to use by configuring the class attribute. You can also configure additionaloptional properties.

<custom-forwarding-catch-all-strategy class="org.my.CustomForwardingCatchAllStrategy"> <jms:outbound-endpoint queue="error.queue"/> <spring:property key="myProperty" value="myValue"/></forwarding-catch-all-strategy>

Logging

This catch-all strategy does nothing with the message and simply logs a warning indicating that themessage was not dispatched because there was no routing path defined.

<logging-catch-all-strategy/>

Custom

This catch-all strategy allows you to use a custom class to perform whatever behavior you require. Toimplement a custom catch-all strategy that forwards the message to an endpoint, you should used thecustom forwarding catch-all strategy instead.

<custom-catch-all-strategy/>

Filters

Filters provide the logic used to invoke a particular router. Filters can be combined using the logic filtersAndFilter, OrFilter, and NotFilter. Not all routers need to use filters, but all routers support them. SeeUsing Filters for complete information.

Page 679: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 679

Component Bindings

This page last changed on Mar 23, 2009 by jwheeler.

Component Bindings

[ Java Component Binding Configuration ] [ Script Component Bindings ]

Components can use bindings to call an external service during execution. The bindings used with a Javacomponent bind a Java interface, or single interface method, to an outbound endpoint. The externalservice to be called should implement the same interface, and the component should encapsulate areference to that interface, which is initialized during the bootstrap stage by the Mule configurationbuilder. The reference will be initialized using a reflective proxy class.

Cannot resolve external resource into attachment.

With component bindings, you can configure multiple interfaces or a single interface with an endpointbound to one or more Mule endpoints.

Mule currently supports component bindings for Java components (the default components in Mule) andscript components, such as Groovy or JRuby. This page describes how to configure each.

Java Component Binding Configuration

Bindings can be used by components to call out to an external service. The bound interface is added tothe component as a field with the usual bean getter and setter methods. In the binding configuration forthe component, you can bind this interface along with a method in the interface to a Mule endpoint. Whenthat method is called, the call parameters are sent over the Mule endpoint to another service, whichmay be local or remote. A result may be returned from the service and passed back to the componentusing the return argument of the method. This model is very similar to traditional RPC calls. Here is anexample:

public class InvokerComponent{ private HelloInterface hello;

public String invoke(String s) { return "Received: " + hello.sayHello(s, "English"); } public void setHello(HelloInterface hello) { this.hello = hello; } public HelloInterface getHello() { return hello; }}

In this example, the component InvokerComponent has a field hello, which is of type HelloInterface,with getter and setter methods for the field. The invoke method will be called on the service and calls thehello.sayHello() method. This call will result in another service call.

The HelloInterface is very simple with a single method sayHello.

public interface HelloInterface{ public String sayHello(String to, String language);

Page 680: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 680

}

Now, you simply configure your component to bind the sayHello method to the endpoint that will invokeanother service.

<service name="InvokerComponent"> <inbound> <jms:inbound-endpoint queue="Invoker.in"/> </inbound> <component class="org.mule.examples.bindings.InvokerComponent"> <binding interface="org.mule.examples.bindings.HelloInterface" method="sayHello"> <axis:outbound-endpoint use="LITERAL" style="WRAPPED" address="http://myhost.com:81/services/HelloWeb?method=helloMethod" synchronous="true"/> </binding> </component> <outbound> <pass-through-router> <jms:outbound-endpoint queue="Invoker.out"/> </pass-through-router> </outbound></service>

The call to the external web service is synchronous, because you want a result returned and need toblock until the call is finished.

Note that component bindings will not work with Java Proxy objects, unless the proxy explicitly handlesthe binding interface method. If using Spring components, ensure that you use CGLib proxies. Formore information on the Spring-AOP proxying behavior, see http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-proxying. If you're using the annotation-processors, such as fortransactions, you would specify the following:

<tx:annotation-driven proxy-target-class="true"/>

Handling Data Types

One powerful feature is that you can handle data conversion when making a call and receiving a resultusing the normal transformer configuration on the endpoint. In the above example, assume the webservice was expecting an org.mule.examples.bindings.WebHelloRequest object and returned anorg.mule.examples.bindings.WebHelloResponse object. You don't want your component to know aboutthese external data types, so you can configure transformers to do the conversion when the call is made:

<component class="org.mule.examples.bindings.InvokerComponent"> <binding interface="org.mule.examples.bindings.HelloInterface" method="sayHello"> <axis:outbound-endpoint use="LITERAL" style="WRAPPED" address="http://myhost.com:81/services/HelloWeb?method=helloMethod" synchronous="true"> <transformers> <custom-transformer class="org.mule.examples.bindings.StringsToWebRequest"/> </transformers> <response-transformers> <custom-transformer class="org.mule.examples.bindings.WebResponseToString"/> </response-transformers> </axis:outbound-endpoint> </binding>

Page 681: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 681

</component>

Exceptions

If the remote service call triggers an exception of fault, this exception will get serialized back to the localservice call and thrown. If your service wants to handle this exception, you must add the exception (orjava.lang.Exception) to the bound method signature and use a try catch block as usual.

Script Component Bindings

Similar to the Java component bindings, script bindings enable the same behavior for your scriptingcomponents. When using a scripting component, the binding is bound to the scripting context and isaccessible by using the binding interface class name.

<service name="ScriptService"> <inbound> <vm:inbound-endpoint ref="inboundEndpoint"/> </inbound> <script:component> <script:script engine="groovy"> return "Total: " + AdditionService.add(1,2) </script:script> <script:java-interface-binding interface="org.mule.tck.services.AdditionService" method="add"> <vm:outbound-endpoint path="addition.service" synchronous="true"/> </script:java-interface-binding> </script:component> <outbound> <pass-through-router> <vm:outbound-endpoint ref="receivedEndpoint"/> </pass-through-router> </outbound></service>

The implementation for the component is contained within the <script:script> element:

return "Total: " + AdditionService.add(1,2)

We refer to the binding interface using the short class name AdditionService and invoke the addmethod, which will call a local addition service.

Page 682: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 682

Using the WireTap Inbound Router

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

Using the WireTap Inbound Router

The WireTap inbound router allows you to route certain messages to a different endpoint as well as to thecomponent.

To copy all messages to a specific component, you configure an outbound endpoint on the WireTaprouter:

<inbound> <vm:inbound endpoint path="FromUser"/> <wire-tap-router> <vm:outbound-endpoint path="tapped.channel"/> </wire-tap-router></inbound>

In the following scenario, no component is specified, so all data from the inbound VM channel is copiedto the outbound endpoint using implicit bridging. However, let's assume you want to forward some ofthe data to another component called WireTapReceiver based on a filter. For the sake of illustration, thiscomponent simply prepends the message with "INTERCEPTED:" before sending it to the FromTapper VMchannel. The code for the WireTapReceiver component is as follows:

public class WireTapReceiver {

public String handleInterceptedData (String aMessage) { //Just Prepend the message with a label return "\nINTERCEPTED: "+aMessage; }}

Following is the configuration of the Mule services:

<model name="default"> <service name="StdComp"> <inbound> <vm:inbound-endpoint path="In"/> <wire-tap-router> <vm:outbound-endpoint path="ToTapper"/> </wire-tap-router> </inbound> <outbound> <outbound-pass-through-router> <vm:outbound-endpoint path="ToClient"/> </outbound-pass-through-router>

Page 683: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 683

</outbound> </service> <service name="wiretapper"> <inbound> <vm:inbound-endpoint path="ToTapper"/> </inbound> <component class="org.myclass.WireTapReceiver"/> <outbound> <outbound-pass-through-router> <vm:outbound-endpoint path="FromTapper"/> </outbound-pass-through-router> </outbound> </service></model>

Note: Mule uses a separate dispatcher thread for the wiretap endpoint.

Using Filters

The WireTap router is useful both with and without filtering. If filtered, it can be used to record ortake note of particular messages or to copy messages that require additional processing to a differentcomponent. If filters aren't used, you can make a backup copy of all messages received by a component.The behavior here is similar to that of an interceptor, but interceptors can alter the message flow bypreventing the message from reaching the component. WireTap routers cannot alter message flow butjust copy on demand.

In the previous example, the StdComp service receives messages from the In endpoint, and the routerpasses the message to the component and copies it to the vm://ToTapper endpoint. The WireTappercomponent listens on this channel and forwards the message, after processing, to the FromTapperendpoint.

The WireTap router is based on the SelectiveConsumer router, so it can take any filters supported bySelectiveConsumer. In this example, only messages that match the filter expression are copied to thevm://ToTapper endpoint.

<wire-tap-router> <wildcard-filter pattern="the quick brown*"/> <vm:outbound-endpoint path="tapped.channel"/></wire-tap-router>

Multiple WireTapping

You can have multiple WireTap routers for the same service:

<inbound> <endpoint address="vm://In"/> <wire-tap-router> <wildcard-filter pattern="the quick brown*"/> <vm:outbound-endpoint path="ToTapper"/> </wire-tap-router> <wire-tap-router> <wildcard-filter pattern="the slow green*"/> <vm:outbound-endpoint path="ToOtherTapper"/> </wire-tap-router></inbound>

Page 684: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 684

In this example, input is passed to the component and also copied to one of two destinations dependingon the filter.

Method Invocation

You can invoke your service with a specific method. For example, if your inbound endpoint is not vm://In but axis\:http://localhost\:8080/services, or if your component StdComp is a customizedcomponent with a method foo(), you can invoke the web service and its method foo() via the followingendpoint:

http\://localhost\:8080/services/StdComp?method=foo&param=bar

When this message is wire-tapped to the receiving component, Mule might fail with an exception if thereceiving component does not have the method foo(). To avoid this problem and to ensure that thedesired method is invoked, you overwrite the method of the message by specifying ?method=methodName,or by specifying ?method= so that the onCall() will be called instead. For example:

<wire-tap-router> <outbound-endpoint addres="vm://inboundEndpoint3?connector=vm2"/></wire-tap-router>...<service name="serviceComponent3"> <inbound> <inbound-endpoint address="vm://inboundEndpoint3?connector=vm2&amp;method=" synchronous="false"/> </inbound> <component class="org.mule.components.simple.LogComponent"/></service>

Additional Features

The WireTap router supports the following additional features:

• Transactions are supported, so the forwarding of messages can either start or join a transactionprovided that the endpoint supports transactions.

• Reply-To can be used to route replies from this endpoint.

Page 685: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 685

XML Configuration

This page last changed on Feb 24, 2009 by jackie.wheeler.

XML Configuration

[ XML Schema ] [ Namespaces ] [ Spring ] [ Property Placeholders ] [ Global Configuration Settings ]

As explained in the overview, the most common way to configure Mule is via Spring XML files that usecustom Mule namespaces.

XML Schema

The configuration files are based on XML schemas, which are specified in the header:

<?xml version="1.0" encoding="UTF-8"?><mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:jms="http://www.mulesource.org/schema/mule/jms/2.2" xmlns:file="http://www.mulesource.org/schema/mule/file/2.2" xsi:schemaLocation=" http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/jms/2.2 http://www.mulesource.org/schema/mule/jms/2.2/mule-jms.xsd http://www.mulesource.org/schema/mule/file/2.2 http://www.mulesource.org/schema/mule/file/2.2/mule-file.xsd">

Be sure to specify all the necessary schema files. This can be time-consuming when setting up theconfiguration file, but importing schemas provides the following time-saving benefits:

• Auto-completion and context-specific help in your favorite IDE• Design-time configuration validation• Typed properties

Namespaces

Each Mule module or transport has its own XML schema. When you import a schema, it has its ownnamespace. For example, the following lines from the above header:

xmlns:jms="http://www.mulesource.org/schema/mule/jms/2.2"xsi:schemaLocation="http://www.mulesource.org/schema/mule/jms/2.2 http://www.mulesource.org/schema/mule/jms/2.2/mule-jms.xsd"

will bind the mule-jms.xsd schema to the jms namespace. Therefore, any XML element starting with<jms: will assume the element comes from the mule-jms.xsd schema.

Default Namespace

Typically, you set the Mule core schema as the default namespace for your configuration file. This meansthat any XML element without a prefix will come from the Mule core schema (mule.xsd). To set thedefault namespace schema, specify xmlns immediately followed by the URL of the Mule schema, withoutthe colon and namespace prefix you set in the previous example (e.g., xmlns instead of xmlns:jms):

Page 686: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 686

<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xsi:schemaLocation="http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd"> ...config...</mule>

Spring

Although your configuration files appear to be Mule-specific, they are really just Spring configuration fileswith Mule-specific extensionsThis approach allows you to use anything Spring offers within your Mule configuration, such as beans,factory beans, resource loaders, EJBs, JNDI, AOP, even integration with other software such as Hivemind,jBPM, Gigaspaces, JBoss Rules, etc.

To use the standard Spring elements, you import the standard Spring namespaces:

xmlns:spring="http://www.springframework.org/schema/beans"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"... <spring:bean id="myBean" class="com.acme.CoolBean"> <spring:property name="sessionFactory"> <spring:ref local="mySessionFactory" /> </spring:property> <spring:property name="configuration"> <spring:value>my-config.xml</spring:value> </spring:property> </spring:bean>

For complete information on Spring configuration, see the Spring Framework reference documentation.

Property Placeholders

You can use Ant-style property placeholders in your Mule configuration. For example:

<smtp:outbound-endpoint user="${smtp.username}" password="${smtp.password}"/>

The values for these placeholders can be made available in a variety of ways, as described in this section.

Global Properties

You can use the <global-property> element to set a placeholder value from within your Muleconfiguration, such as from within another Mule configuration file:

<global-property name="smtp.username" value="JSmith"/><global-property name="smtp.password" value="ChangeMe"/>

Properties Files

To load properties from a file, you can use the standard Spring element

Page 687: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 687

<context:property-placeholder>:

xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd" <context:property-placeholder location="smtp.properties" placeholderPrefix="${"/>

where the contents of smtp.properties is:

smtp.username=JSmithsmtp.password=ChangeMe

The placeholderPrefix value can be anything other than "#[", which is what Mule uses to parse itsmessage properties in expressions. We recommend you set the value to "${". Note that you do nothave to change anything in your Spring configuration or properties file to match this value; it simplydifferentiates Spring properties from Mule properties.

To load multiple properties files, separate them with commas:

<context:property-placeholder location="email.properties,http.properties,system.properties" placeholderPrefix="${"/>

Message Properties

You can use placeholders to perform logic on message properties such as the header. For example,if you wanted to evaluate the content-type portion of the message header, you would specify it as#[header:Content-Type]. Typically, you message property placeholders with expressions. For moreinformation, see Using Expressions.

System Properties

The placeholder value can come from a JDK system property. If you start Mule from the command line,you would specify the properties as follows:

mule -M-Dsmtp.username=JSmith -M-Dsmtp.password=ChangeMe -config my-config.xml

or edit the system properties in conf/wrapper.conf.

If you start Mule programmatically, you would specify the properties as follows:

System.getProperties().put("smtp.username", "JSmith");System.getProperties().put("smtp.password", "ChangeMe");MuleContext muleContext = new DefaultMuleContextFactory().createMuleContext(new SpringXmlConfigurationBuilder("my-config.xml"));muleContext.start();

Page 688: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 688

Environment Variables

There is no standard way in Java to access environment variables. However, this link has some optionsyou might find useful.

Global Configuration Settings

You can configure global configuration settings such as the default transaction timeout and defaultthreading profile in the <configuration> element. For example:

<mule>... <configuration defaultTransactionTimeout="31337"> <default-component-threading-profile poolExhaustedAction="RUN"/>... </configuration>

For a list of the available global configuration settings, see Global Settings Configuration Reference.

Page 689: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 689

ActiveMQ Integration

This page last changed on Feb 23, 2009 by jackie.wheeler.

ActiveMQ Integration

You can integrate Mule with Apache ActiveMQ. To configure a default embedded broker, you use the<activemq-connector> or <activemq-xa-connector> (for transaction support) element in your Muleconfiguration. These connectors take all the same attributes and elements as the JMS connector with theadditional attribute brokerURL.

<?xml version="1.0" encoding="UTF-8" ?> <mule xmlns="http://www.mulesource.org/schema/mule/core/2.2"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mule="http://www.mulesource.org/schema/mule/core/2.2" xmlns:jms="http://www.mulesource.org/schema/mule/jms/2.2" xmlns:test="http://www.mulesource.org/schema/mule/test/2.2" xsi:schemaLocation="http://www.mulesource.org/schema/mule/test/2.2 http://www.mulesource.org/schema/mule/test/2.2/mule-test.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/jms/2.2 http://www.mulesource.org/schema/mule/jms/2.2/mule-jms.xsd">

<jms:activemq-connector name="jmsConnector" specification="1.1" brokerURL="vm://localhost" connectionFactory-ref="activeMqConnectionFactory"/>

<--! or use the XA connector to support transactions --> <jms:activemq-xa-connector name="xaConnector" maxRedelivery="1"> <dispatcher-threading-profile doThreading="false" /> </jms:activemq-xa-connector>...

The specification attribute tells Mule to use the JMS 1.1 specification, which is the specificationActiveMQ supports. The connectionFactory-ref attribute specifies a set of connection factory propertiesyou define in your Spring configuration.

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="activeMqConnectionFactory" class="org.activemq.ActiveMQConnectionFactory"> <property name="brokerXmlConfig" value="classpath:/org/mule/test/activemq-config.xml"/> <!-- More properties you want set on ActiveMQConnectionFactory --> </bean></beans>

Your ActiveMQ configuration file uses standard settings. For example, to use in-JVM messaging withoutpersistent queues (very useful for testing), the file might look like this:

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//ACTIVEMQ//DTD//EN" "http://activemq.org/dtd/activemq.dtd">

Page 690: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 690

<beans> <broker> <connector> <serverTransport uri="vm://localhost"/> </connector>

<persistence> <vmPersistence/> </persistence> </broker></beans>

Page 691: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 691

Example Archetype

This page last changed on Feb 23, 2009 by jackie.wheeler.

Example Archetype

[ Configuring Maven ] [ Using the Archetype ] [ The Questions Explained ] [ Example Console Output ] [Command Line Options ]

Mule provides Maven archetypes that you can use as code templates for your Mule projects. Thesetemplates include a set of implementation notes and "todo" pointers that help you get started quickly.The Mule example archetype will help you generate a tailored boilerplate example project in seconds. Formore information on using Maven, see Using Maven.

Follow the instructions below to create template files for a new Mule example, including all the necessaryJava boilerplate and detailed implementation instructions in comments.

Configuring Maven

Add the following to the file settings.xml (usually in your Maven conf or $HOME/.m2 directory) so thatMaven will allow you to execute Mule plug-ins.

<settings> <pluginGroups> <pluginGroup>org.mule.tools</pluginGroup> </pluginGroups> ...</settings>

Using the Archetype

First, open a command shell and change to the directory where you want to create your example project.

> cd yourDir

Next, you will execute the archetype and generate the code. If this is your first time running thiscommand, Maven will download the archetype for you.

> mvn mule-example-archetype:create -DartifactId=xxx -DmuleVersion=2.2.0

At minimum, you pass in two system parameters:

• artifactId: The short name for the project (such as 'myExample'). This must be a single word inlower case with no spaces, periods, hyphens, etc.

• muleVersion: The version of the Mule project archetype you want to use. This will also be thedefault Mule version used for the generated artifact.

artifactId

As of Mule 2.2 the artifactId can contain characters such as underscore or hyphen.However, the plug-in will convert the name into a usable form suitable for Java. Forexample, if the argument is specified as -DartifactId=My#Awesome-Mule_Project,the project will be created in a directory of that name, but the project name will beMyAwesomeMuleProject and the package name will be .myawesomemuleproject

The plug-in will ask various questions (described below) and then generate the files. You can also usethis plug-in without user prompts by entering all the arguments at the command line. For a full list ofarguments that can be passed in, see the Command Line Options.

Page 692: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 692

After you have answered all the questions, the archetype creates a directory using the example projectname you specified that includes a POM file for building with Maven, a Mule configuration file (conf\mule-config.xml) that includes the namespaces for the transports and modules you specified andhas placeholder elements for creating your first service, and a package.html file under src\main\java using the package path you specified. It also creates files in the dist folder that you need todistribute to users, including a readme file and a batch file for running the example. Lastly, it createssome template files under src\test to help you get started creating a unit test for the example. A newMULE-README.txt file will be created in the root of your project explaining what files were created.

The Questions Explained

The plug-in prompts you to answer several questions about the example you are creating. These mayvary according to the options you select. An example of the output is shown below.

Provide a description of what the example does:

You should provide an accurate description of the example with any high-level details of what you can orcannot do with it. This text will be used where a description of the example is required.

Which version of Mule is this example targeted at?

The version of Mule you want to use for your example. This will default to the archetype version passed inon the command line.

Will this project be hosted on MuleForge?

If the example will be hosted on MuleForge, additional information will be added to your example forlinking to its issue tracker, web site, build server, and deployment information.

Which Mule transports do you want to include in this project?

A comma-separated list of the transports you plan to use in this example (such as HTTP and VM). Thiswill add the namespaces for those transports to the configuration file.

Which Mule modules do you want to include in this project?

A comma-separated list of the modules you plan to use in this example (such as XML and Scripting). Thiswill add the namespaces for those modules to the configuration file.

Example Console Output

[INFO] description:********************************************************************************

Provide a description of what the example does:

[default:]********************************************************************************

[INFO] muleVersion:********************************************************************************

Which version of Mule is this example targeted at?

[default: 2.2.0]********************************************************************************

[INFO] forgeProject:********************************************************************************

Will This project be hosted on MuleForge? [y] or [n]

Page 693: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 693

[default: y]********************************************************************************

[INFO] transports:********************************************************************************

Which Mule transports do you want to include in this project?(options: axis,cxf,ejb,file,ftp,http,https,imap,imaps,jbpm,jdbc, jetty,jms,multicast,pop3,pop3s,quartz,rmi,servlet,smtp, smtps,servlet,ssl,tls,stdio,tcp,udp,vm,xmpp):

[default: cxf,file,http,jdbc,jms,stdio,vm]

********************************************************************************

[INFO] modules:********************************************************************************

Which Mule modules do you want to include in this project?

(options: bulders,client,jaas,jbossts,management,ognl,pgp,scripting, spring-extras,sxc,xml):

[default: client,management,scripting,sxc,xml]

********************************************************************************

Command Line Options

By default, this plug-in runs in interactive mode, but it's possible to run it in 'silent' mode by using thefollowing option:

-Dinteractive=false

The following options can be passed in:

Name Example Default Value

groupId -DgroupId=org.mule.examplexxx

org.mule.example.<artifactId>

forgeProject -DforgeProject=n y

packagePath -DpackagePath=org/mule/example

none

transports -Dtransports=http,vm cxf,file,http,jdbc,jms,stdio,vm

muleVersion -DmuleVersion2.2.0 none

packageName -DpackageName=myPkg none

description -Ddescription="some text" none

modules -Dmodules=xml,scripting client,management,scripting,sxc,xml

basedir -Dbasedir=/projects/mule/tools <current dir>

Page 694: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 694

package -Dpackage=org/mule/example/myPkg

none

artifactId -DartifactId=myMuleExample mule-application-<artifactId>

version -Dversion=2.2-SNAPSHOT <muleVersion>

Page 695: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 695

Fiorano Integration

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

Configuring the JMS Connector for FioranoMQ2007

FioranoMQ is a High Performance Enterprise Communication Backbone.

<jms:connector name="FioranoJMSConnector" connectionFactoryJndiName="PrimaryCF" jndiInitialFactory="fiorano.jms.runtime.naming.FioranoInitialContextFactory" specification="1.1" jndiProviderUrl="http://localhost:1856" username="anonymous" password="anonymous">

<!-- A few optional values for the factory --> <spring:property key="connectionFactoryProperties"> <spring:map> <spring:entry key="clientID" value="sampleClientID"/> <spring:entry key="ConnectURL" value="http://localhost:1856"/> <spring:entry key="BackupConnectURLs" value="http://localhost:1956"/> </spring:map> </spring:property></jms:connector>

You will need the following jars on your classpath:

• FioranoMQ2007/fmq/lib/client/all/fmq-client.jar• FioranoMQ2007/framework/lib/all/fiorano-framework.jar

Sample Usage

The following steps illustrate modifying the "Echo" sample shipped with Mule. Instead of usingSystem.out in the outbound router, we will write the output onto a Topic in FioranoMQ using the aboveconfiguration.

Modify the outbound router in the echo-config.xml under examples\echo\conf to use a Topic:

<jms:outbound-endpoint topic="muleTopic"/>

Start the durable connection sample available in FioranoMQ from a command prompt in fmq/samples/PubSub/DurableSubscribers as shown below:

runClient DurableSubscriber -clientid sampleClientID -topicName muleTopic

Now on starting Mule with the above echo-config.xml file we can push messages onto the topic andconsequently to the subscriber.The durable connection property can also be tested by killing the subscriber, pumping in more messagesand then again starting the subscriber.

Page 696: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 696

Integrating SwiftMQ with Mule

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

Integrating SwiftMQ with Mule

This page describes how to use SwiftMQ with Mule.

Configuring a Mule JMS Connector

The best approach for integrating SwiftMQ is via JNDI. You will specify the following attributes:

Attribute Description Recommended Value

jndiInitialFactory InitialContext factory com.swiftmq.jndi.InitialContextFactoryImpl

jndiProviderUrl JNDI Provider URL smqp://localhost:4001/timeout=10000

jndiDestinations JNDI lookup of queues/topics true

forceJndiDestinations Forces a JNDI exception if adestination was not found inJNDI

true

specification Version of the JMS specification 1.1

connectionFactoryJndiName Name of the JMS connectionfactory to use

ConnectionFactory

Example:

<jms:connector name="jmsConnector" connectionFactoryJndiName="ConnectionFactory" jndiDestinations="true" forceJndiDestinations="true" jndiInitialFactory="com.swiftmq.jndi.InitialContextFactoryImpl" jndiProviderUrl="smqp://localhost:4001/timeout=10000" specification="1.1"/>

After you have configured the connector, copy swiftmq.jar into the Mule lib/user directory and startthe SwiftMQ Router. You can now use SwiftMQ from Mule.

Configuring the Loan Broker ESB Example with SwiftMQ

The following example shows you how to modify the Loan Broker ESB example to use SwiftMQ. The onlychange necessary is to modify the JMS connector in both example configuration files. With a SwiftMQRouter running on the local host, the connector would look like this:

<jms:connector name="jmsConnector" connectionFactoryJndiName="ConnectionFactory" jndiDestinations="true" forceJndiDestinations="true" jndiInitialFactory="com.swiftmq.jndi.InitialContextFactoryImpl" jndiProviderUrl="smqp://localhost:4001/timeout=10000"

Page 697: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 697

specification="1.1"/>

The Loan Broker ESB example uses the following JMS queues (Mule syntax):

jms://esb.loan.quotesjms://esb.credit.agencyjms://esb.lender.servicejms://esb.banks

SwiftMQ does not allow dots '.' in queue names. Instead, use underscores '_' in SwiftMQ'srouterconfig.xml:

<swiftlet name="sys$queuemanager"> <queue-controllers> <queue-controller name="01" persistence-mode="non_persistent" predicate="tmp$%"/> <queue-controller name="02" predicate="sys$%"/> <queue-controller name="03" predicate="swiftmq%"/> <queue-controller name="04" predicate="rt$%"/> <queue-controller name="05" predicate="unroutable"/> <queue-controller name="06" predicate="%$%"/> <queue-controller name="07" predicate="%"/> </queue-controllers> <queues> <queue name="esb_banks"/> <queue name="esb_credit_agency"/> <queue name="esb_lender_service"/> <queue name="esb_loan_quotes"/> </queues></swiftlet>

To match with the Loan Broker ESB example's JMS queue names, define JNDI aliases in SwiftMQ'srouterconfig.xml:

<swiftlet name="sys$jndi"> <aliases> <alias name="esb.banks" map-to="esb_banks@router1"/> <alias name="esb.credit.agency" map-to="esb_credit_agency@router1"/> <alias name="esb.lender.service" map-to="esb_lender_service@router1"/> <alias name="esb.loan.quotes" map-to="esb_loan_quotes@router1"/> </aliases> <jndi-replications/> <remote-queues/></swiftlet>

You now rebuild the Loan Broker ESB example with Ant or Maven so that the configuration changes cantake effect, then start the SwiftMQ Router and the Loan Broker ESB example.

Note that the @ sign can be escaped with %40 in the Mule URI, so for an alternate configuration you canuse the following:

<endpoint name="LoanBrokerRequestsREST" address="jetty:rest://localhost:8080/loanbroker"/> <vm:endpoint name="LoanBrokerRequests" path="loan.broker.requests"/> <jms:endpoint name="LoanQuotes" address="jms://esb_loan_quotes%40router1"/> <jms:endpoint name="CreditAgencyGateway" address="jms://esb_credit_agency%40router1"/> <!-- here we're telling Mule to invoke a remote Ejb directly (not host a

Page 698: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 698

proxy service for the remote object as with the other example in mule-config-with-ejb-container.xml example) --> <ejb:endpoint name="CreditAgency" host="localhost" port="1099" object="local/CreditAgency" method="getCreditProfile" /> <!-- endpoint name="CreditAgency" address="ejb://localhost:1099/local/CreditAgency?method=getCreditProfile" / --> <endpoint name="LenderGateway" address="jms://esb.lender.service" /> <endpoint name="LenderService" address="vm://lender.service" /> <endpoint name="BankingGateway" address="jms://esb.banks%40router1" /> <endpoint name="Bank1" address="axis:http://localhost:10080/mule/TheBank1?method=getLoanQuote" synchronous="true" /> <endpoint name="Bank2" address="axis:http://localhost:20080/mule/TheBank2?method=getLoanQuote" synchronous="true" /> <endpoint name="Bank3" address="axis:http://localhost:30080/mule/TheBank3?method=getLoanQuote" synchronous="true" /> <endpoint name="Bank4" address="axis:http://localhost:40080/mule/TheBank4?method=getLoanQuote" synchronous="true" /> <endpoint name="Bank5" address="axis:http://localhost:50080/mule/TheBank5?method=getLoanQuote" synchronous="true" />

Keep in mind that a SwiftMQ JNDI alias also decouples a queue from its physical location. You can movea queue to another router without affecting clients. So it's always best practice to avoid physical queuenames.

Page 699: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 699

Jaas Security

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

Jaas Security

[ Using the Jaas Configuration File ] [ Passing the Credentials Directly to the Provider ] [ Passing a Non-default Login Module ] [ Configuring the Security Filter on an Endpoint ]

The JaasSimpleAuthenticationProvider is a security provider that provides a way to interact with the JaasAuthentication Service.

The security provider for Jaas can be configured in a couple of different ways. It allows you to configureJaas either by passing to the provider a Jaas configuration file or by passing the required attributesdirectly to the JaasSimpleAuthenticationProvider. These two configuration methods are describedbelow.

Using the Jaas Configuration File

Usually, JAAS authentication is performed in a pluggable fashion, so applications can remain independentfrom underlying authentication technologies.

jaasTest{ org.mule.module.jaas.loginmodule.DefaultLoginModule required credentials="anon:anon;Marie.Rizzo:dragon;"};

The above example was saved in a file called jaas.conf. This file contains just one entry calledcom.ss.jaasTest, which is where the application we want to protect can be found. The entry specifiesthe login module that will be used to authenticate the user. As a login module, you can either use Mule'sDefaultLoginModule, one of the login modules that come with Sun, or else create your own. In thiscase, we have opted for Mule's DefaultLoginModule.

The required flag that follows the login module specifies that the login module must succeed for theauthentication to be considered successful. Additional flags are:

Required - The login module is required to succeed. If it succeeds or fails, authentication still continuesto proceed down the login module list.

Requisite - The login module is required to succeed. If it succeeds, authentication continues down thelogin module list. If it fails, control immediately returns to the application.

Sufficient - The login module is not required to succeed. If it does succeed, control immediately returnsto the application (authentication does not proceed down the login module list). If it fails, authenticationcontinues down the login module list.

Optional - The login module is not required to succeed. If it succeeds or fails, authentication stillcontinues to proceed down the login module list.

The entry also specifies the credentials, in which we put a string of authorized users together with theirpasswords. The credentials are put here only when the DefaultLoginModule is going to be used, as themethod in which the user names and passwords are obtained may vary from one login module to another.

The format of the credentials string must adhere to the following format if the DefaultLoginModule isgoing to be used:

<username>:<password>;

Page 700: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 700

Configuring the Provider in the Mule Configuration File

<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaas="http://www.mulesource.org/schema/mule/jaas/2.2" ...cut...

<jaas:security-manager> <jaas:security-provider name="jaasSecurityProvider" loginContextName="jaasTest" loginConfig="jaas.conf"/> </jaas:security-manager>

Note that in the above, the loginContextName contains the same name of the entry as in the Jaasconfiguration file. This name will be used for creating the login context as well as to find the completeURL of the jaas.conf file.

Passing the Credentials Directly to the Provider

The second option for the configuration of the JaasSimpleAuthenticationProvider is to pass theconfiguration details that would otherwise be found in the Jaas configuration file directly to the provider.

<jaas:security-manager> <jaas:security-provider name="jaasSecurityProvider" loginContextName="jaasTest" credentials="anon:anon;Marie.Rizzo:dragon;"/></jaas:security-manager>

In the above configuration, note that we removed the property loginConfig and don't need to pass anyJaas configuration file. Instead, we simply pass the credentials to the provider (using the same format asspecified above). Since no login module is specified, the DefaultLoginModule is used.

Passing a Non-default Login Module

The third option is to enter your own login module.

<jaas:security-manager> <jaas:security-provider name="jaasSecurityProvider" loginContextName="jaasTest" loginModule="com.sun.security.auth.module.NTLoginModule"/></jaas:security-manager>

In the above configuration, we have added the loginModule property, which allows you to specify thelogin module you want to use to authenticate the user. Since the NTLoginModule does not require you toinput a list of accepted usernames and passwords, the property for the credentials was removed.

Configuring the Security Filter on an Endpoint

You can use JaasSecurityFilter as a security filter, as follows:

<inbound> <inbound-endpoint address="vm://test"> <jaas:jaas-security-filter/> </inbound-endpoint>

Page 701: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 701

</inbound>

Page 702: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 702

JBoss Jms Integration

This page last changed on Feb 26, 2009 by jackie.wheeler.

JBoss JMS Integration

You configure a JBoss JMS connector for Mule as follows:

<?xml version="1.0" encoding="UTF-8"?><mule xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans" xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:jms="http://www.mulesource.org/schema/mule/jms/2.2"... xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.mulesource.org/schema/mule/jms/2.2 http://www.mulesource.org/schema/mule/jms/2.2/mule-jms.xsd...>

<jms:connector name="jmsConnector" connectionFactoryJndiName="java:/ConnectionFactory" jndiInitialFactory="org.jnp.interfaces.NamingContextFactory" jndiProviderUrl="jnp://localhost:1099" jndiDestinations="true" forceJndiDestinations="true" specification="1.1"/>

The JNDI provider and JBoss properties are specified in Spring.

If you use user credentials to connect to JBoss MQ, make sure that the user has the 'guest'role assigned to it. This will ensure that there are no issues if temporary topics or queuesare used.

Page 703: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 703

Module Archetype

This page last changed on Feb 24, 2009 by jackie.wheeler.

Module Archetype

[ Configuring Maven ] [ Using the Archetype ] [ The Questions Explained ] [ Example Console Output ] [Updating an Existing Module ] [ Command Line Options ]

Mule provides Maven archetypes that you can use as code templates for your Mule modules that youwant to host on MuleForge or include with the Mule distribution. These templates include a set ofimplementation notes and "todo" pointers that help you get started quickly. The Mule module archetypewill help you generate a tailored boilerplate module in seconds. For more information on using Maven, seeUsing Maven.

Updating Existing Modules and Transports

The Module archetype allows developers to create new Mule modules or upgrade existing Mule modulesadding support for schemas and registry bootstrapping. See Updating an Existing Module for moreinformation.

Follow the instructions below to create template files for a new Mule module, including all the necessaryJava boilerplate and detailed implementation instructions in comments.

Configuring Maven

Add the following to the file settings.xml (usually in your Maven conf or $HOME/.m2 directory) so thatMaven will allow you to execute Mule plug-ins.

<settings> <pluginGroups> <pluginGroup>org.mule.tools</pluginGroup> </pluginGroups> ...</settings>

Using the Archetype

First, open a command shell and change to the directory where you want to create your module.

> cd yourDir

Next, you will execute the archetype and generate the code. If this is your first time running thiscommand, Maven will download the archetype for you.

> mvn mule-module-archetype:create -DartifactId=xxx -DmuleVersion=2.2.0 -DarchetypeArtifactId=mule-module-archetype

At minimum, you pass in these system parameters:

• artifactId: The short name for the project (such as 'myApp'). This must be a single word in lowercase with no spaces, periods, hyphens, etc.

• muleVersion: The version of the Mule project archetype you want to use. This will also be thedefault Mule version used for the generated artifact.

• archetypeArtifactId: Enter mule-module-archetype when running the module archetype.

artifactId

Page 704: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 704

As of Mule 2.2 the artifactId can contain characters such as underscore or hyphen.However, the plug-in will convert the name into a usable form suitable for Java. Forexample, if the argument is specified as -DartifactId=My#Awesome-Mule_Project,the project will be created in a directory of that name, but the project name will beMyAwesomeMuleProject and the package name will be .myawesomemuleproject

The plug-in will ask various questions (described below) and then generate the files. You can also usethis plug-in without user prompts by entering all the arguments at the command line. For a full list ofarguments that can be passed in, see the Command Line Options.

After you have answered all the questions, the archetype creates a directory using the module name youspecified that includes a POM file for building with Maven, a Mule configuration file (src\main\resources\mule-config.xml) that includes the namespaces for the transports and modules you specified and hasplaceholder elements for creating your first service, and a package.html file under src\main\java usingthe package path you specified. Lastly, it creates some template files under src\test to help you getstarted creating a unit test for the module. A new MULE-README.txt file will be created in the root of yourproject explaining what files were created.

The Questions Explained

The plug-in prompts you to answer several questions about the project you are writing. These may varyaccording to the options you select. An example of the output is shown below.

Are you creating a new module (rather than updating an existing one)?

If you are creating an brand new Mule module, chose yes here. The wizard will then ask you whatresources you want to create. If you are updating an existing module, choose no, and see Updatingan Existing Module for more information. The following questions get asked if you are creating a newmodule.

Provide a description of what the project does:

You should provide an accurate description of the module with any high-level details of what you can orcannot do with it. This text will be used where a description of the module is required.

Which version of Mule is this project targeted at?

The version of Mule you want to use for your module. This will default to the archetype version passed inon the command line.

Will this project be hosted on MuleForge?

If the transport is going to be hosted on MuleForge, additional information will be added to your projectfor linking to its issue tracker, web site, build server and deployment information.

Which Mule transports do you want to include in this project?

A comma-separated list of the transports you plan to use in this module (such as HTTP and VM). This willadd the namespaces for those transports to the configuration file.

Which Mule modules to you want to include in this project?

A comma-separated list of the modules you are extending with this module (such as XML and Scripting).This will add the namespaces for those modules to the configuration file.

Will this transport have a custom schema for configuring the transport in Xml?

All new transports targeted for Mule 2.x should define an XML schema that defines how the transportis configured. If you do not use this option, users will have to use generic configuration to use yourtransport.

Page 705: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 705

Will this module 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 madeavailable in the Mule Registry as soon as the module is loaded. This is useful for registering customtransformers or expression evaluators.

Example Console Output

********************************************************************************

Are you creating a new module (rather than updating an existing one)? [y] or [n] [default: y]********************************************************************************y[INFO] description: ********************************************************************************

Provide a description of what the module does: [default: ]********************************************************************************foo Bar[INFO] muleVersion: ********************************************************************************

Which version of Mule is this module targeted at? [default: 2.2.0]********************************************************************************

[INFO] forgeProject: ********************************************************************************

Will this module be hosted on MuleForge? [y] or [n] [default: y]********************************************************************************

[INFO] transports: ********************************************************************************

Which Mule transports do you want to include in this module?

(options: axis, cxf, ejb, file, ftp, http, https, imap, imaps, jbpm, jdbc, jetty, jetty-ssl, jms, jnp, multicast, pop3, pop3s, quartz, rmi, servlet, smtp, smtps, servlet, ssl, tls, stdio, tcp, udp, vm, xmpp): [default: vm]********************************************************************************

[INFO] modules: ********************************************************************************

Which Mule modules do you want to include in this module?

(options: bulders, client, jaas, jbossts, management, ognl, pgp, scripting,spring-extras, sxc, xml): [default: client]********************************************************************************

[INFO] hasCustomSchema: ********************************************************************************

Will this module have a custom schema for configuring the module in Xml? [y] or [n] [default: y]********************************************************************************

[INFO] hasBootstrap:

Page 706: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 706

********************************************************************************

Will this module make objects available in the Registry as soon as it's loaded? [y] or [n] [default: n]********************************************************************************

Updating an Existing Module

The module archetype can be used for updating existing modules and transports. It allows developers toadd template code for schema configurations and boostrap the registry. It will leave your existing codeuntouched.

For example, if your existing Module or transport is located under /projects/foo, you update the projectby running the following commands:

cd /project/foomvn mule-module-archetype:create -DartifactId=foo -DmuleVersion=2.2.0 -DarchetypeArtifactId=mule-module-archetype

Notice that the artifactId must be set to the name of your project. This ensures that any new classeswill be created with the same naming scheme.

When you run this command, you will be prompted with three questions. The first question will ask youwhether this is a new project. Make sure you select 'n' so that the wizard will upgrade your existingmodule or transport. It then asks you the last two questions about the custom schema and registrybootstrap. After you answer the questions, the code will be created and a new MULE-UPDATE-README.txtfile will be created in the root of your project explaining what files were created.

Command Line Options

By default, this plug-in runs in interactive mode, but it's possible to run it in 'silent' mode by using thefollowing option:

-Dinteractive=false

The following options can be passed in:

Name Example Default Value

groupId -DgroupId=org.mule.applicationxxx

org.mule.application.<artifactId>

packagePath -DpackagePath=org/mule/application

none

transports -Dtransports=http,vm cxf,file,http,jdbc,jms,stdio,vm

muleVersion -DmuleVersion2.2.0 none

packageName -DpackageName=myPkg none

description -Ddescription="some text" none

modules -Dmodules=xml,scripting client,management,scripting,sxc,xml

Page 707: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 707

basedir -Dbasedir=/projects/mule/tools <current dir>

package -Dpackage=org/mule/application/myPkg

none

artifactId -DartifactId=myMuleProject mule-application-<artifactId>

version -Dversion=1.0-SNAPSHOT <muleVersion>

Page 708: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 708

OpenJms Integration

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

OpenJMS Integration

The following example configuration describes how to configure a Mule JMS connector for OpenJMS.You will probably need to change the connectionFactoryJndiName to one that is configured from yourOpenJMS configuration.

<jms:connector name="jmsConnector" jndiInitialFactory="org.exolab.jms.jndi.InitialContextFactory" jndiProviderUrl="tcp://localhost:3035" connectionFactoryJndiName="QueueConnectionFactory"/>

Page 709: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 709

PGP Security

This page last changed on Feb 20, 2009 by jackie.wheeler.

PGP Security

[ Requirements ] [ Configuring the PGP Filter ] [ Configuration Reference ]

This extension adds PGP security on endpoint communication. With PGP you can achieve end-to-endsecurity communication with signed and encrypted messages between parties.

Requirements

Libraries

You must add these libraries to your Mule classpath:

• Cryptix OpenPGP• Cryptix JCE

Policy Files

If you are running JDK 1.4+ that comes with the Sun JCE by default, you must install the UnlimitedStrength Jurisdiction Policy files, which can be downloaded from the following URL (note that they arelisted entirely at the bottom of the page, in the Other Downloads section):

JDK 1.4JDK 5JDK 6

These files must be installed in $JAVA_HOME$/jre/lib/security

According to Sun, the default distribution of the JCE allows "strong, but limited strength cryptography."This means that you cannot use RSA keys bigger than 2048 bits and no symmetric ciphers that use morethan 128 bits. ElGamal is not allowed at all, thus DH/DSS cannot be used for encryption.

Useful PGP Links

How PGP works (intro documentation)GnuPG (freeware implementation)enigmail (extension for Thunderbird)

Configuring the PGP Filter

Using a Spring context, you define a manager for accessing public and private keys.

<mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:pgp="http://www.mulesource.org/schema/mule/pgp/2.2" ...cut...

<spring:bean id="pgpKeyManager" class="org.mule.module.pgp.PGPKeyRingImpl" init-method="initialise"> <spring:property name="publicKeyRingFileName" value="serverPublic.gpg"/> <spring:property name="secretKeyRingFileName" value="serverPrivate.gpg"/> <spring:property name="secretAliasId" value="0x6168F39C"/> <spring:property name="secretPassphrase" value="TestingPassphrase"/> </spring:bean>

Page 710: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 710

<spring:bean id="fakeCredentialAccessor" class="org.mule.module.pgp.FakeCredentialAccessor"/>

You must also specify a class that identifies the sender of a message. For this example, we simply fakethe sender using the FakeCredentialAccessor (available in the test classes of mule-module-pgp), whichreturns a fixed user name.

PGP stores keys in files called keyringsThere is a public keyring storing public keys of your trusted parties and a private keyringstoring your secret key. In a keyring, keys are referenced by an alias ID (also named keyId). Your secret keyring is encrypted on your disk using a passphrase.

In this example, we define a sample echo application that reads signed (and encrypted) files froma directory (/temp/signedAndEncryptedFiles/in) and write the decrypted content into /temp/decryptedFiles/out. The configuration looks like this:

<pgp:security-manager> <pgp:security-provider name="pgpSecurityProvider" keyManager-ref="pgpKeyManager"/> <pgp:keybased-encryption-strategy name="keyBasedEncryptionStrategy" keyManager-ref="pgpKeyManager"/> </pgp:security-manager>

<model name="test"> <service name="echo"> <inbound> <inbound-endpoint address="file:///temp/signedAndEncryptedFiles/in"> <pgp:security-filter strategyName="keyBasedEncryptionStrategy" signRequired="true" credentialsAccessor-ref="fakeCredentialAccessor" keyManager-ref="pgpKeyManager"/> </inbound-endpoint> </inbound> <component class="org.mule.module.pgp.EchoMsg"/> <outbound> <pass-through-router> <outbound-endpoint address="file:///temp/decryptedFiles/out"> <pgp:security-filter strategyName="keyBasedEncryptionStrategy" credentialsAccessor-ref="fakeCredentialAccessor" keyManager-ref="pgpKeyManager"/> </outbound-endpoint> </pass-through-router> </outbound> </service> </model></mule>

The property signRequired in the inbound security filter controls whether to accept unsigned messages.

Configuration Reference

Security Manager

Child Elements of <security-manager...>

Name Cardinality Description

security-provider 0..1 Security provider for PGP-related functionality.

Page 711: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 711

keybased-encryption-strategy 0..1 The key-based PGP encryptionstrategy to use.

Security Provider

Security provider for PGP-related functionality.

Attributes of <security-provider...>

Name Type Required Default Description

keyManager-ref name (no spaces) no Reference to thekey manager touse.

Keybased Encryption Strategy

The key-based PGP encryption strategy to use.

Attributes of <keybased-encryption-strategy...>

Name Type Required Default Description

keyManager-ref name (no spaces) no Reference to thekey manager touse.

credentialsAccessor-ref

name (no spaces) no Reference tothe credentialsaccessor to use.

Security Filter

Filters messages based on PGP encryption.

Attributes of <security-filter...>

Name Type Required Default Description

strategyName string no The name of thePGP encryptionstrategy to use.

signRequired string no Whether signing isrequired.

keyManager-ref name (no spaces) no Reference to thekey manager touse.

credentialsAccessor-ref

name (no spaces) no Reference tothe credentialsaccessor to use.

Page 712: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 712

Project Archetype

This page last changed on Feb 24, 2009 by jackie.wheeler.

Project Archetype

[ Configuring Maven ] [ Using the Archetype ] [ The Questions Explained ] [ Example Console Output ] [Command Line Options ]

Mule provides Maven archetypes that you can use as code templates for your Mule projects. Thesetemplates include a set of implementation notes and "todo" pointers that help you get started quickly.The Mule project archetype will help you generate a tailored boilerplate project in seconds. For moreinformation on using Maven, see Using Maven.

Follow the instructions below to create template files for a new project, including all the necessary Javaboilerplate and detailed implementation instructions.

Configuring Maven

Add the following to the file settings.xml (usually in your Maven conf or $HOME/.m2 directory) so thatMaven will allow you to execute Mule plug-ins.

<settings> <pluginGroups> <pluginGroup>org.mule.tools</pluginGroup> </pluginGroups> ...</settings>

Using the Archetype

First, open a command shell and change to the directory where you want to create your project.

> cd yourDir

Next, you will execute the archetype and generate the code. If this is your first time running thiscommand, Maven will download the archetype for you.

> mvn mule-project-archetype:create -DartifactId=xxx -DmuleVersion=2.2.0

At minimum, you pass in two system parameters:

• artifactId: The short name for the project (such as 'myApp'). This must be a single word in lowercase with no spaces, periods, hyphens, etc.

• muleVersion: The version of the Mule project archetype you want to use. This will also be thedefault Mule version used for the generated artifact.

artifactId

As of Mule 2.2 the artifactId can contain characters such as underscore or hyphen.However, the plug-in will convert the name into a usable form suitable for Java. Forexample, if the argument is specified as -DartifactId=My#Awesome-Mule_Project,the project will be created in a directory of that name, but the project name will beMyAwesomeMuleProject and the package name will be .myawesomemuleproject

The plug-in will ask various questions (described below) and then generate the files. You can also usethis plug-in without user prompts by entering all the arguments at the command line. For a full list ofarguments that can be passed in, see the Command Line Options.

Page 713: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 713

After you have answered all the questions, the archetype creates a directory using the project name youspecified that includes a POM file for building with Maven, a Mule configuration file (src\main\resources\mule-config.xml) that includes the namespaces for the transports and modules you specified and hasplaceholder elements for creating your first service, and a package.html file under src\main\java usingthe package path you specified. Lastly, it creates some template files under src\test to help you getstarted creating a unit test for the project. A new MULE-README.txt file will be created in the root of yourproject explaining what files were created.

The Questions Explained

The plug-in prompts you to answer several questions about the project you are writing. These may varyaccording to the options you select. An example of the output is shown below.

Provide a description of what the project does:

You should provide an accurate description of the project with any high-level details of what you can orcannot do with it. This text will be used where a description of the project is required.

Which version of Mule is this project targeted at?

The version of Mule you want to use for your project. This will default to the archetype version passed inon the command line.

What is the base Java package path for this project?

This should be a Java package path for you project, such as com/mycompany/project. Note that you mustuse slashes for separators, not periods.

Which Mule transports do you want to include in this project?

A comma-separated list of the transports you plan to use in this project (such as HTTP and VM). This willadd the namespaces for those transports to the configuration file.

Which Mule modules to you want to include in this project?

A comma-separated list of the modules you plan to use in this project (such as XML and Scripting). Thiswill add the namespaces for those modules to the configuration file.

Example Console Output

[INFO] description:********************************************************************************

Provide a description of what the project does:

[default:]********************************************************************************

[INFO] muleVersion:********************************************************************************

Which version of Mule is this module targeted at?

[default: 2.2.0]********************************************************************************

[INFO] package:********************************************************************************

What is the base Java package path for this project? (i.e. com/mycompany/project):

Page 714: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 714

[default:]********************************************************************************

[INFO] transports:********************************************************************************

Which Mule transports do you want to include in this project?

(options: axis,cxf,ejb,file,ftp,http,https,imap,imaps,jbpm,jdbc, jetty,jms,multicast,pop3,pop3s,quartz,rmi,servlet,smtp, smtps,servlet,ssl,tls,stdio,tcp,udp,vm,xmpp):

[default: cxf,file,http,jdbc,jms,stdio,vm]

********************************************************************************

[INFO] modules:********************************************************************************

Which Mule modules do you want to include in this project?

(options: bulders,client,jaas,jbossts,management,ognl,pgp,scripting, spring-extras,sxc,xml):

[default: client,management,scripting,sxc,xml]

********************************************************************************

Command Line Options

By default, this plug-in runs in interactive mode, but it's possible to run it in 'silent' mode by using thefollowing option:

-Dinteractive=false

The following options can be passed in:

Name Example Default Value

groupId -DgroupId=org.mule.applicationxxx

org.mule.application.<artifactId>

packagePath -DpackagePath=org/mule/application

none

transports -Dtransports=http,vm cxf,file,http,jdbc,jms,stdio,vm

muleVersion -DmuleVersion2.2.0 none

packageName -DpackageName=myPkg none

description -Ddescription="some text" none

modules -Dmodules=xml,scripting client,management,scripting,sxc,xml

basedir -Dbasedir=/projects/mule/tools <current dir>

Page 715: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 715

package -Dpackage=org/mule/application/myPkg

none

artifactId -DartifactId=myMuleProject <artifactId>

version -Dversion=1.0-SNAPSHOT <muleVersion>

Page 716: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 716

SeeBeyond JMS Server Integration

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

SeeBeyond JMS Server Integration

The following configuration is for the SeeBeyond ICAN IQManager JMS Server. Note the values in [ ](square brackets), which should be replaced by values relevant to your installation. Port 18006 is thedefault, which you can change in the SeeBeyond designer.

<jms:connector name="jmsConnector" jndiInitialFactory="com.stc.is.naming.NamingContextFactory" jndiProviderUrl="[ServerName]:18006" connectionFactoryJndiName="/jms/connectionfactory/queue/[LogicalHostName]_[JMS iqManager Name]"/></jms:connector>

For a topic, the connectionFactoryJndiName would be /jms/connectionfactory/topic/[LogicalHostName]_[JMS iqManager Name].

You will need the following files from the Java API Kit on your classpath:

• com.stc.jmsis.jar• fscontext.jar• providerutil.jar• jms.jar• jta.jar• log4j.jar• log4j.properties

Page 717: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 717

SonicMQ Integration

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

SonicMQ Integration

The following configuration was tested with versions 6.1 and 7.0 of SonicMQ.

<jms:connector name="jmsSonicMQConnector" jndiInitialFactory="com.sonicsw.jndi.mfcontext.MFContextFactory" specification="1.1" connectionFactoryJndiName="sonic-cf" jndiProviderUrl="tcp://localhost:2506" username="Administrator" password="Administrator">

<spring:property key="connectionFactoryProperties"> <spring:map> <spring:entry key="clientID" value="clientIDString"/> <spring:entry key="connectID" value="connectIDString"/> <spring:entry key="connectionURLs" value="somURLStrings here"/> <spring:entry key="defaultUser" value="userString"/> <spring:entry key="defaultPassword" value="passwordString"/> <spring:entry key="prefetchCount" value="10"/> <spring:entry key="prefetchThreshold" value="10"/> <spring:entry key="faultTolerant" value="true"/> <spring:entry key="persistentDelivery" value="true"/> <spring:entry key="loadBalancing" value="true"/> <spring:entry key="sequential" value="false"/> </spring:map> </spring:property>

<spring:property key="jndiProviderProperties"> <spring:map> <spring:entry key="com.sonicsw.jndi.mfcontext.domain" value="Domain1"/> <spring:entry key="java.naming.security.principal" value="Administrator"/> <spring:entry key="java.naming.security.credentials" value="Administrator"/> <!-- optional, default is 30sec --> <spring:entry key="com.sonicsw.jndi.mfcontext.idleTimeout" value="5000"/> </spring:map> </spring:property>

</jms:connector>

Page 718: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 718

Sun JMS Grid Integration

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

Sun JMS Grid Integration

The following configuration demonstrates how to configure Mule to use the Sun JMS Grid server.

<jms:connector name="jmsConnector" specification="1.1" connectionFactoryJndiName="QueueConnectionFactory" jndiInitialFactory="com.spirit.directory.SpiritVMDirectoryContextFactory" <spring:property name="jndiProviderProperties"> <spring:map> <spring:entry key="driverName" value="WMSEmbedded"/> </spring:map> </spring:property></jms:connector>

Page 719: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 719

Tibco EMS Integration

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

TIBCO EMS Integration

This page demonstrates how to configure Mule to use the TIBCO Enterprise Message Server (EMS) withauthentication in place.

<jms:connector name="jmsConnector" jndiProviderUrl="tibjmsnaming://host:port" connectionFactoryJndiName="QueueConnectionFactory" username="username" password="password" jndiDestinations="true" forceJndiDestinations="true" jndiInitialFactory="com.tibco.tibjms.naming.TibjmsInitialContextFactory" specification="1.1"> <spring:property name="jndiProviderProperties"> <spring:map> <spring:entry key="java.naming.security.principal" value="jndiUsername"/> <spring:entry key="java.naming.security.credentials" value="jndiPassword"/> </spring:map> </spring:property> </jms:connector>

Note that when you use tibjmsnaming as the protocol in your jndiProviderUrl, you can also specifyTCP or SSL with the JNDI property com.tibco.tibjms.naming.security_protocol.

For XA transactions, you must create an XA Connection Factory from the TIBCO administration-tool(tibemsadmin) as follows:

> create factory XAQueueConnectionFactory xaqueue url=tcp://7222

Page 720: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 720

Using Expressions

This page last changed on Feb 24, 2009 by jackie.wheeler.

Using Expressions

[ Using Expressions with Transformers ] [ Using Expression Filters ] [ Using Expression Routers ]

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

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

This page describes how to use expressions. For more details on how to configure expressions, seeExpressions Configuration Reference.

Using Expressions with Transformers

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

Expression Transformer

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

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

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

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

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

<expression-transformer>

Page 721: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 721

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

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

Message Properties Transformer

The <message-properties-transformer> allows you to add, remove, or rename properties dynamicallyor statically on the current message. For example:

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

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

XSLT Transformer

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

<mulexml:xslt-transformer name="xslt" xslFile="./conf/xsl/cd-listing.xsl"> <mulexml:context-property key="title" value="#[header:ListTitle]"/> <mulexml:context-property key="rating" value="#[header:ListRating]"/></mulexml:xslt-transformer>

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

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

Using Expression Filters

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

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

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

Page 722: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 722

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

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

For more information on filters, see Using Filters.

Using Expression Routers

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

Expression Recipient List Router

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

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

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

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

Best Practice

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

Page 723: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 723

Expression Message Splitter Router

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

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

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

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

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

To read more about configuring expressions, see Expressions Configuration Reference.

Page 724: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 724

Creating Expression Evaluators

This page last changed on Feb 27, 2009 by ross.

Creating Expression Evaluators

In addition to the standard expression evaluators provided with Mule, you can create your ownevaluators. This page describes how to create a custom evaluator, as well as how to add expressionsupport to a custom module.

Creating the Custom Evaluator

To create a custom evaluator, the first step is to implement the ExpressionEvaluator interface. This is asimple strategy interface:

public interface ExpressionEvaluator extends NamedObject{ Object evaluate(String expression, MuleMessage message);}

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

The arguments on the evaluate method are self-explanatory. The expression argument is theexpression to evaluate on the current message being passed in.

Lets take the header expression evaluator as a concrete example. It will assume that the expression willcontain a name of a header to return.

public class MessageHeaderExpressionEvaluator implements ExpressionEvaluator{ public static final String NAME = "header";

public Object evaluate(String expression, MuleMessage message) { Object result = null; boolean required; //Is the header optional? the '*' denotes optional if (expression.endsWith("*")) { expression = expression.substring(expression.length() - 1); required = false; } else { required = true; } //Look up the property on the message result = message.getProperty(expression);

if (result == null && required) { throw new RequiredValueException(CoreMessages.expressionEvaluatorReturnedNull(NAME, expression)); } return result;

Page 725: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 725

}

public String getName() { return NAME; }

public void setName(String name) { throw new UnsupportedOperationException("setName"); }}

Note that the name of the expression evaluator is fixed as "header" so the setName method throws anUnsupportedOperationException.

Registering the Custom Evaluator

After creating your custom expression evaluator, you must register it with Mule. There are two ways ofdoing this, depending on how you are configuring your Mule instance.

Configuring the Evaluator as a Bean

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

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

Bootstrapping the Evaluator

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

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

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

object.1=org.mule.expression.MessageHeaderExpressionEvaluator

When Mule starts, it will discover this bootstrap file before loading any configuration and will install anyobjects listed in the file into the local registry. For more information, see Bootstrapping the Registry.

Using the Custom Evaluator

To use the custom evaluator, you use the customEvaluator attribute as follows:

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

Page 726: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 726

</expression-transformer>

When embedding the expression, you can use normal syntax:

#[myEval:foo]

Adding Expression Support to Custom Modules

The ExpressionManager is responsible for maintaining a list of supported Expression Evaluators andresolving expressions at run-time. If you are adding support for expressions in your custom Muleextensions, you will need access to this object. This is currently a static class so all methods can be calledstatically, for example:

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

As of Mule 2.2, you can get the ExpressionManager using:

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

Note that the muleContext is available by implementing MuleContextAware . If you are extending a MuleAPI abstract class (i.e. AbstractConnector) then always check that the base class doesn't already providethe MuleContext.

Page 727: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 727

Expressions Configuration Reference

This page last changed on Mar 24, 2009 by jwheeler.

Expressions Configuration Reference

[ Expression Attributes ] [ Expression Syntax ] [ Mule Expression Language ] [ Spring PropertyPlaceholders and Expressions ] [ Namespaces for XPath Expressions ] [ Expression Evaluator Reference ]

This page provides reference information for configuring expressions. For an introduction to expressionsin Mule, see Using Expressions.

Expression Attributes

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

Attribute Description

expression The expression to evaluate. The syntax of thisattribute will change depending on the evaluatorbeing used.

evaluator The expression evaluator to use. Expressionevaluators must be registered with theExpressionEvaluatorManager before they can beused. Using the custom evaluator allows you todefine your custom evaluator via the custom-evaluator attribute. Note that some evaluatorssuch as Xpath, Groovy, and Bean are loadedfrom other Mule modules (XML and Scripting,respectively). These modules must be on yourclasspath before their evaluators can be used.

custom-evaluator The name of a custom evaluator to use. Thisevaluator must be registered in the local registrybefore it can be used.

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

Expression Syntax

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

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

For these elements, you can set only a single expression for the element. When defining expressions forthings like property values, you can set multiple expressions using the following syntax:

Page 728: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 728

#[<evaluator>:<expression>]

The syntax requires that you precede an expression with #[, and then define the evaluator followed bya colon (:) and the expression to execute. Finally, you terminate the expression with a ]. You can definemultiple expressions as a string. For example:

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

For a list of available evaluators, see Expression Evaluator Reference below.

Optional Values

As of Mule 2.2, you can use an asterisk to indicate an optional property in the expression. For examplethe following expression would indicate that foo and car must be present, but bar is optional:

#[headers:foo,bar*,car]

or

#[mule:message.headers(foo,bar*,car)]

Syntax Change between Mule 2.0 and Mule 2.1

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

Mule Expression Language

As of Mule 2.2, there is a powerful expression language defined in the package org.mule.expression forquerying Mule information at run-time. It provides a unified language for querying message properties,attachments payload, Mule context information such as the current service or endpoint, and access tothe registry. The syntax is #[mule: followed by message, context, or registry, followed by a periodand then the object to query or an evaluator followed by the values in parentheses. Following is moreinformation on each of these types.

If you are working with files, also see the Expression Filename Parser in the File Transport.

Message Properties

You can extract information from the current message. You set an evaluator such as headers or payloadand then specify in parentheses the values to evaluate on that part of the message. You can also setroot message properties like correlationId. For more information, see Expression Evaluator Referencebelow.

For example:

Page 729: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 729

• #[mule:message.headers(foo, bar)] - retrieves two headers foo and bar and returns a Map• #[mule:message.attachments-list(attach1, attach2*)] - retrieves two named attachments in

a List. The asterisk on attach2 indicates that it is optional• #[mule:message.headers(all)] - retrieves all headers and returns as a Map• #[mule:message.payload(org.dom4j.Document)] - returns the payload and converts it to anorg.dom4j.Document

• #[mule:message.correlationId] - returns the correlationId on the message• #[mule:message.map-payload(foo)] - expects a Map payload object and retrieves the propertyfoo from the map

Context Properties

You can use #[mule:context to return information about the server itself, such as the server ID, or aboutthe current request, such as the current service name. Following are the properties you can return fromthe Mule context:

Context Property Description

serviceName Returns the name of the service currentlyprocessing the message

modelName Returns the name of the model that hosts thecurrent service

inboundEndpoint Returns the URI string of the endpoint thatreceived the current message

serverId The Mule instance server ID

clusterId The Mule instance cluster ID

domainId The Mule instance domain ID

workingDir Mule's working directory

homeDir Mule's home directory

For example:

• #[mule:context.serviceName]• #[mule:context.modelName]• #[mule:context.workingDir]

Registry Objects

You can use #[mule:registry to return objects you have written to the registry. For example:

• #[mule:registry.apple] - returns an object called apple from the registry• #[mule:registry.apple*] - returns an object called apple from the registry but is optional• #[mule:registry.apple.washed] - returns the property washed on an object called apple in the

registry

Spring Property Placeholders and Expressions

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

web.proxy.host=192.168.2.2

Page 730: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 730

web.proxy.port=8081

The Mule configuration file can embed these properties as placeholders.

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

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

Namespaces for XPath Expressions

As of Mule 2.2, you can specify a namespace globally so that it can be used by XPath expressions acrossMule. You can declare the namespace in any XML file in your Mule instance. To declare a namespace,include the mule-xml.xsd schema in your XML file:

<mule xsi:schemaLocation="http://www.mulesource.org/schema/mule/xml/2.2 http://www.mulesource.org/schema/mule/xml/2.2/mule-xml.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd">

Next, specify the <namespace-manager> element, and then add one or more <namespace> elementswithin it to declare the prefix and URI of each namespace you want to add to the namespace manager.If you already declared a namespace at the top of the file in the <mule> element, you can set theincludeConfigNamespaces attribute to true to have the namespace manager pick up those namespacesas well.

<mulexml:namespace-manager includeConfigNamespaces="true"> <mulexml:namespace prefix="foo" uri="http://foo.com"/> </mulexml:namespace-manager>

You can also declare a namespace locally in an expression filter, router, or transformer using the<namespace> element without the <namespace-manager> element. You can then use that prefix within theXPath expression. For example, the following Jaxen filter declares a namespace with the prefix "e", whichis then used in the filter expression:

<outbound> <filtering-router> <outbound-endpoint address="vm://echo" synchronous="true"/> <mule-xml:jaxen-filter pattern="/e:purchaseOrder/e:shipTo/@country" expectedValue="US"> <mule-xml:namespace prefix="e" uri="http://www.example.com"/> </mule-xml:jaxen-filter> </filtering-router>....</outbound>

If you had a global namespace with the "e" prefix, the local namespace URI would override the globalnamespace URI.

Page 731: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 731

You can specify the namespace on any XML-based functionality in Mule, including the JXPath filter,Jaxen filter, XPath filter, filter-based splitter, expression splitter, round-robin splitter, JXPath extractortransformer, and XPath extractor transformer in the XML Module, as well as the SXC filter and filteringrouter in the SXC Module.

Expression Evaluator Reference

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

Name Example Comments

attachment #[attachment:supporting-docs]

Not supported by expressionfilters.

attachments #[attachments:attach1,attach2]Returns a java.util.Map ofattachments. Not supported byexpression filters.

attachments-list #[attachments-list:attach1,attach2]

Returns a java.util.Listof attachments objects. Notsupported by expressionfilters. As of Mule 2.2, you canspecify {all} to retrieve allattachments.

bean #[bean:fruit.isWashed] The bean property expression.Use "." or "/" as elementdelimiter.

endpoint #[endpoint:myEP.address] Use endpointName.property.Not supported by expressionfilters.

exception-type #[exception-type:java.lang.RuntimeException]

Matches an exception type. Onlysupported by expression filters.

function #[function:dateStamp(dd-MM-yyyy)]

Performs a function: now, date,datestamp, systime, uuid,hostname, ip, or count. Notsupported by expression filters.

groovy #[groovy:payload.fruit.washed]Evaluates the expression usingthe Groovy language.

header #[header:Content-Type] Evaluates the specified part ofthe message header.

headers #[headers:Content-Type,Content-Length]

Returns a java.util.Map ofheaders. Not supported byexpression filters. As of Mule2.2, you can specify {all} toget all headers.

headers-list #[headers-list:Content-Type,Content-Length]

Returns a java.util.List ofheader values. Not supported byexpression filters.

jxpath #[jxpath:/fruit] JXPath expression that works onboth XML/DOM and Beans.

Page 732: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 732

map-payload #[map-payload:key] Returns a value from within ajava.util.Map payload. Notsupported by expression filters.

message #[message.correlationId] Available expressionsare id, correlationId,correlationSequence,correlationGroupSize,replyTo, payload, encoding,and exception. Not supportedby expression filters.

ognl #[ognl:[MULE:0].equals(42)] Set the evaluator attributeon the <expression-filter>element to ognl when specifyingan OGNL filter.

payload #[payload:com.foo.RequiredType]If expression is provided, it willbe a class to be class loaded.The class will be the desiredreturn type of the payload.See getPayload(Class) inMuleMessage . Not supported byexpression filters.

payload-type #[payload:java.lang.String] Matches the type of the payload.Only supported by expressionfilters.

regex #[regex:the quick brown(.*)]

Only supported by expressionfilters.

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

xpath #[xpath://fruit] The expression is an XPathexpression.

xpath-node #[xpath-node://fruit] (As of Mule 2.2) Returns thenode object from the XPathexpression as is.

Page 733: Mule 2.2.1 Users Guide

Document generated by Confluence on Mar 25, 2009 00:56 Page 733

WebLogic JMS Integration

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

WebLogic JMS Integration

Before using Mule with WebLogic, copy the weblogic.jar file to $MULE_HOME/lib/user.

JNDI destinations syntaxIf Mule fails to look up topics or queues in WebLogic's JNDI, but the JNDI tree lists themas available, try replacing JNDI subcontext delimiters with dots, so tracker/topic/PriceUpdates becomes tracker.topic.PriceUpdates.

WebLogic 8.x and Earlier

<jms:connector name="jmsConnector" jndiProviderUrl="t3://localhost:7001" connectionFactoryJndiName="javax.jms.QueueConnectionFactory" jndiDestinations="true" forceJndiDestinations="true" jndiInitialFactory="weblogic.jndi.WLInitialContextFactory" specification="1.0.2b"/>

WebLogic 9.x

For WebLogic 9.x, the configuration is almost the same. The only differences are:

• Supported JMS specification level is 1.1 (1.0.2b should still work, however)• The unified JMS connection factory can be used as a result of the above. The following example

demonstrates using the default factories available out of the box.

<jms:connector name="jmsConnector" jndiProviderUrl="t3://localhost:7001" connectionFactoryJndiName="weblogic.jms.ConnectionFactory" jndiDestinations="true" forceJndiDestinations="true" jndiInitialFactory="weblogic.jndi.WLInitialContextFactory" specification="1.1"/>