Space Details Key:
MULEUSER
Name:
Mule 1.x User Guide
Description:
Mule Users Guide for the 1.x release line
Creator (Creation Date):
ross (Jan 30, 2008)
Last Modifier (Mod. Date): tcarlson (Apr 15, 2008)
Available Pages •
Home Architecture Overview • Benchmark • •
Clustering
•
Components Interceptors • REST Service Wrapper • • •
Standard Components Bridge Component • Transformers XmlObject Transformer •
• •
Writing Components Calling no-arguments Methods • Configuration Options
•
Configuring Endpoints Configuring Components • Configuring Mule Programmatically
•
Configuring Properties
•
EJB EJB Session Beans • Spring EJB •
•
Escape URI Credentials
•
Exception Strategies
•
Filters
•
Functional Testing
•
General Transport Configuration
•
How to Ask for Help on the Lists
•
Internationalisation Internationalisation-1.4.1 •
•
J2EE Application Servers Geronimo Integration • JBoss Integration • Mule as MBean • Joram Integration •
•
•
Oracle Integration
•
Weblogic Integration
Document generated by Confluence on Apr 24, 2008 08:11
Page 1
•
•
•
WebSphere Integration • JBI Embedding Mule in JBI • Invoking JBI Components from Mule • Mule JBI Examples • JMS Configuring Jms • ActiveMQ Integration • Fiorano Integration • •
Integrating SwiftMQ with Mule
•
JBoss Jms Integration
•
OpenJms Integration
•
Oracle AQ Integration
•
SeeBeyond JMS Server Integration
•
SonicMQ Integration
•
Sun JMS Grid Integration
•
Tibco EMS Integration
•
Weblogic Jms Integration
WebSphere MQ Integration • Jmx Management DefaultJmxSupportAgent • Jdmk Configuration •
•
Message Routers Message Chunking Outbound Router • Using the WireTap Inbound Router •
•
Models
•
Mule Agents
•
Mule and .NET Webservices FAQ
•
Mule Client
•
Mule Configuration Overview
•
Mule Endpoint URIs
•
Mule Endpoints
•
Mule Security Component Authorization Using Acegi • Setting up LDAP Provider for Acegi •
•
Mule Server Notifications
•
Object Containers HiveMind Support • JNDI • Storing Mule objects in Jndi • •
Jndi Container
•
PicoContainer Support
•
Plexus support
Document generated by Confluence on Apr 24, 2008 08:11
Page 2
•
Quartz Scheduler Integration
•
Rapid Development with Mule JavaRebel Integration • Resource Adapter
• • • •
•
RMI Managing RMI Objects • Scripting Security Acegi Security • •
Jaas Security
•
PGP Security
Web Service Security • Spring Configuring a Spring context using Mule Xml • •
Configuring the Mule Server From a Spring Context
•
Sending and Receiving Mule Events From the Spring Context
•
Spring Remoting
•
Using Spring as a Component Factory • Streaming
•
Suggested Reading
•
Test Compatability Kit
•
Transaction Management Jotm Transaction Manager • Transaction Manager Lookup •
•
Transports Guide AS400 DQ Provider • •
BPM Connector
•
Ejb Provider
•
Email Provider
•
File Provider
•
Ftp Provider
•
Http Provider
•
Imap Provider
•
Jdbc Provider
•
Jms Provider
•
Multicast Provider
•
Pop3 Provider
•
Quartz Provider
•
Rmi Provider
•
SalesForce Connector
•
Servlet Provider
•
SFTP Connector SFTP Connector Example •
Document generated by Confluence on Apr 24, 2008 08:11
Page 3
•
•
•
SFTP Connector User Guide • Smtp Provider
•
Soap Provider
•
Ssl Provider
•
Stream Provider
•
Tcp Provider
•
Transports Feature Matrix
•
Udp Provider
•
Vfs Provider
•
Vm Provider
•
WSDL Provider
Xmpp Provider • Web Services Axis • Axis SOAP Styles • Axis Soap Transports •
• • •
SFTP Connector Installation Instructions
•
Axis Transport
•
Axis Web Services and Mule
Configuring Axis • Glue Glue transport • REST
XFire • Writing Transports Transport Service Descriptors • XSLT Transformer
•
• Topologies
•
Profiling Mule with YourKit
•
Glossary
•
Tools Config Visualizer • •
Mule IDE
•
Mule Project Wizard
•
Project Archetype
•
Transport Archetype • Implementation Guide
•
Configure Maven Plugins
•
Programmers Guide
•
Transformations and Mule Best Practices
•
Architecture Guide
•
MULE_SERVICE_METHOD
Document generated by Confluence on Apr 24, 2008 08:11
Page 4
•
•
MULE and Oracle SOA BPEL Integration How to invoke Oracle SOA BPEL engine from Mule using Web Services • How to invoke Oracle SOA BPEL from Mule Using JMS connector • How to invoke services hosted on Mule from SOA BPEL process • JavaSpaces
Document generated by Confluence on Apr 24, 2008 08:11
Page 5
Home This page last changed on Apr 22, 2008 by tcarlson.
Architecture Introduction Mule Integration • • • • • • •
Overview Models Endpoints Transports Routers Filters Transformers
Configuring Mule • • • • • • • • • • •
Mule Configuration Overview Configuration Options Configuring Mule Programmatically Configuring Endpoints Transports Guide JMX Management Configuring Jms Configuring Properties General Transport Configuration Object Containers Configuring Service Methods
Using Mule • • • • • • • • • • • • • •
Profiling Mule with YourKit Writing Components Writing Transports Exception Strategies Internationalisation Mule Endpoint URIs Mule Endpoints Message Routers Transaction Management Mule Client Mule Agents Mule Server Notifications Mule Security Rapid Development with Mule
Document generated by Confluence on Apr 24, 2008 08:11
• AppServers ° Geronimo ° JBoss ° Oracle ° JMS ° EJB ° JBI • MULE:Containers ° HiveMind ° PicoContainer ° Plexus ° Spring • JavaSpaces • JSR-223 Scripting (php, groovy, javascript) • JNDI • Quartz • Security ° Jaas Security ° Acegi Security ° PGP Security • Transaction Managers ° Jotm ° Tyrex • Web Services ° Axis ° Glue ° REST ° XFire • Clustering
Tools • Mule IDE • Benchmark • Config Visualizer
Suggested Reading
Page 6
Architecture Overview This page last changed on Jan 30, 2008 by ross.
The Basics At the most basic level, Mule is a distributable object broker called the Container or Mule Model. TM
The Container manages operational objects, or Universal Message Objects . These guys, UMOs for short, are simple Java objects that communicate between themselves and external applications. The communication points are called "Endpoints". The diagram below shows a simplified breakdown of the Mule Server components. Cannot resolve external resource into attachment.
The Mule Manager The Mule Manager is central to a Mule server instance (also known as a Node or Mule Node). Its primary role is to manage the various objects such as connectors, endpoints and transformers for a Mule instance. These objects are then used to control message flow to and from your services/components and provide services to the Model and the components it manages.
The Model The model is the container in which your components are managed and executed. It controls message flow to and from your components, manages threading, lifecycle and pooling. The default MuleModel is SEDA-based meaning it uses an efficient event-based queuing model to maximize performance and throughput. The container provides a range of services for UMO components such as transaction management, transformation of events, routing, event correlation, logging, auditing and management. Mule separates object construction from management meaning that popular IoC/DI containers such as Spring, PicoContainer or Plexus can be used to construct your UMO components.
UMO Components TM
UMO stands for Universal Message Object ; an object that can receive and send events from anywhere. UMO Components are your business objects. These are components that execute business logic on an incoming event. These components are standard JavaBeans, there is no Mule-specific code in your components. Mule handles all routing and transformation of events to and from your objects based on the configuration of your component
Endpoints Endpoints are fundamental to Mule's communication capabilities. An Endpoint defines a communication channel between two or more components, applications or repositories. They provide a powerful way of allowing your objects to talk over any protocol in a unified way. An endpoint can be configured with message filters, security interceptors and transaction information to control who, what and how messages are received or sent via the endpoint. For more information see Mule Endpoints.
External Applications External applications can be anything from application servers to legacy payroll systems, to mainframe trading applications or a client application. Basically, any application that has a way of serving or consuming data. As Mule performs all communication via endpoints, UMO components have no notion of what application produced the data, where the application is located nor the transport protocol used.
Mule Objects The terminology used within Mule might be a bit confusing, but it breaks down pretty simply.
Document generated by Confluence on Apr 24, 2008 08:11
Page 7
Object Term
Description
Transport
A transport or "provider", is a set of objects that add support to Mule to handle a specific kind of transport or protocol. For example, the "Email Provider" enables Mule to send and receive messages via the SMTP, POP and IMAP protocols.
Connector
A connector is the object that sends and receives messages on behalf of an endpoint. Connectors are bundled as part of specific transports or providers. For example, the FileConnector can read and write file system files.
Router
A router is the object that do something with messages once they have been received by a connector, or prior to being sent out by the connector.
Filter
A filter optionally filters incoming or outgoing messages that are coming into or going out from a connector. For example, the File Provider comes with a FilenameWildcardFilter that restricts which files are read by the connector based on file name patterns. Filters are used in conjunction with Routers.
Transformer
A transformer optionally changes incoming or outgoing messages in some way. For example, the ByteArrayToString transformer converts byte arrays into String objects.
Document generated by Confluence on Apr 24, 2008 08:11
Page 8
Benchmark This page last changed on Jan 30, 2008 by ross.
Document generated by Confluence on Apr 24, 2008 08:11
Page 9
Clustering This page last changed on Jan 30, 2008 by ross.
NOTE: This is a work in progress! Your feedback and improvements would be very welcome. Please email the user mailing list with your suggestions.
Introduction Clustering means many things to many people. As you build your application, its important to think critically about how to best architect your application to achieve the desired availability, fault tolerance, and performance characteristics. There is no one size fits all solution for everyone. This document attempts to outline some of the goals and tactics for achieving high availability and fault tolerance with your application.
Goals Typically when we are clustering an application we're trying to achieve two things: • High availability (HA): Making your system continually available in the event a server(s) or datacenter fails. • Fault tolerance (FT): The ability to recover from failure of some underlying component. Typically through transaction rollback or compensating actions.
Techniques for clustering, high availability and fault tolerance JMS Queues JMS can be used to achieve HA & FT by routing messages through JMS queues. In this case each message will be 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
Document generated by Confluence on Apr 24, 2008 08:11
Page 10
Load balancers Load balancers simply route requests to different servers based on the the current load of each server and which servers are currently up. Load balancers can be software or hardware based. This approach is commonly used with clustered databases (see below). Pros: • Straightforward to do • Well understood by developers Cons: • Not a complete solution on its own, doesn't provide fault tolerance.
Maintaining state in a database If you have a clustered database, one option for your application is to simply store all state in the database and rely on it to replicate the data consistently across servers. Pros: • Straightforward to do • Well understood by developers Cons: • Not all state is amenable to being stored in the database.
Handling stateful components While most applications can be supported by the above techniques, some require sharing state between JVMs more deeply. One common example of this is an aggregator component. Say we have an aggregator which is aggregating messages from two different producers. Producer #1 sends a message to the aggregator and it is received and held in memory until Producer #2 sends a message. Producer #1 ---> |----------| |Aggregator| --> Some other component Producer #2 ---> |----------|
If the server with the aggregator goes down between Producer #1 sending a message and Producer #2 sending a message, Producer #2 can't just send its message to a different server because that server will not have the message from Producer #1. The solution to this is to share the state of the aggregator component across different machines through clustering software such as Terracotta, Tangosol Coherence, JGroups, etc. By using one of these, Producer #2 can simply fail over to a different server. Pros: • Works for all clustering cases • Can work as a cache as well Cons: • Not implemented in Mule yet • Requires performance tuning to get things working efficiently
Document generated by Confluence on Apr 24, 2008 08:11
Page 11
Example Architectures HTTP + JMS Queues In this example architecture, HTTP requests come in through a load balancer and are immediately put on a JMS queue. The JMS queue is clustered between the different servers. A server will start processing a message off the JMS queue and wrap everything in a transaction.
If the server goes down, the transaction will roll back and another server will pick up the message and start processing it. NOTE: If the HTTP connection is open for the duration of this process, this will not work as the load balancer will not transparently switch connections between servers. In this case the HTTP client will need to retry.
Terracotta Terracotta is an open source JVM clustering technology. It is able to replicate the state of your components across JVMs. In this example architecture there is a load balancer which is proxying requests between multiple servers.
Document generated by Confluence on Apr 24, 2008 08:11
Page 12
In case one of the servers goes down, the load balancer will automatically route requests to a server that is up. Because all the state of your components is shared between the different servers, your internal process can continue on another server. NOTE: If the HTTP connection is open for the duration of this process, this will not work as the load balancer will not transparently switch connections between servers. In this case the HTTP client will need to retry.
Related topics There are many other topics that are important to discuss around clustering: • • • •
Maintaining geo-distributed clusters Data partioning ACID vs. BASE transactions Compensation and transactions
Document generated by Confluence on Apr 24, 2008 08:11
Page 13
Components This page last changed on Jan 30, 2008 by ross.
Writing Components - Best practices for writing Mule components. Standard Components - Components that ship with the Mule distribution. Exception Strategies - How to customise Exception management for your components. Interceptors - How to intercept the inbound and outbound event flow to a component to introduce new behaviour. Transformers - Transformers available in Mule and how to write your own. Endpoints - All you need to know about configuring Endpoints for your components. Message Routers - A guide to configuring routing paths to and from components and external systems. Filters - Can be used on endpoints and Routers, here is information about the filters provided by Mule and how to write your own.
Document generated by Confluence on Apr 24, 2008 08:11
Page 14
Interceptors This page last changed on Feb 13, 2008 by lorraine.busuttil.
Mule interceptors are useful for attaching common behaviour to multiple UMOs. The Interceptor or Command pattern is often referred to as practical AOP (Aspect Oriented Programming) as it allows the developer to intercept processing on an object and potentially alter the processing and outcome. Interceptors a very useful for attaching profiling, permission and security checks, etc, to a component in Mule.
Interceptor Types Mule has two types of interceptors 1. org.mule.interceptors.EnvelopeInterceptor - Envelope filter that will execute before and after the event is processed. Good for Logging and profiling. 2. org.mule.umo.UMOInterceptor - Simply gets invoked then forwards processing to the next element. An interceptor can stop further processing by not forwarding control to the next interceptor, for example as permissions checker interceptor.
Interceptor Event Flow The following shows an example interceptor stack and the event flow. Cannot resolve external resource into attachment.
Writing Interceptors If you want to intercept an event flow to a component on the inbound event flow, you should implement the org.mule.umo.UMOInterceptor interface. it has a single method UMOMessage intercept(Invocation invocation) throws UMOException;
The invocation parameter contains the current event and the UMODescriptor object of the target component. Developers can extract the current UMOMessage from the event and manipulate it any way they wish. The intercept method must return a UMOMessage that will be passed on to the component (or the next interceptor in the chain). The EnvelopeInterceptor works in the same way except that it exposes two methods that get invoked before and after the event processing. UMOMessage before(Invocation invocation) throws UMOException; UMOMessage after(Invocation invocation) throws UMOException;
Halting Event Flow If you wish to halt the event flow you can either call setStopFurtherProcessing() from the UMOEventContext or else throw an exception. This will cause the ExceptionStrategy on the component to be invoked.
Configuring Interceptors Interceptors can be configured on your components using the
element i.e. <mule-descriptor name="MyUMO" implementation="org.my.UMOService"> ....
You can also define interceptor stacks; these are one or more interceptors that can be referenced using a logical name. To define an interceptor stack you must first configure it in the global section of the Mule Xml config file (above the <model> element) -
Document generated by Confluence on Apr 24, 2008 08:11
Page 15
Then you can reference this stack on your components using <mule-descriptor name="MyUMO" implementation="org.my.UMOService"> ....
You can configure zero or more elements on your components and you can mix using explicit classnames or stack names.
Document generated by Confluence on Apr 24, 2008 08:11
Page 16
REST Service Wrapper This page last changed on Apr 18, 2008 by tcarlson.
This component can be used to proxy REST style services as local Mule Components. The org.mule.components.rest.RESTServiceWrapper can be configured with a service URL. A number of properties will allow you to configure the parameters and error conditions on the service.
Property
Description
Required
serviceUrl
the REST service url to invoke. If any parameters are specified on this url they will always be included on the Url invoked.
Yes unless the urlFromMessage is set to true
urlFromMessage
Determines if the REST URL to invoke should be obtained from the message. The rest.service.url property should be set on the message.
No
requiredParams
A map of required parameters that must be set on the REST serviceUrl. These can either be set explicity on the serviceUrl or the parameters must exist as properties on the current message.
No
optionalParams
A map of optional parameters that will be set on the service URL if they are available, but no error will occur if the parameters are not set on the message.
No
httpMethod
The Http method to use when invoking the service.
No. Default is GET.
payloadParameterName
This is the name of the parameter to set on the service URL that will be set to the message payload. If this is not set, the message payload is still sent in the body of the request. Superceded by payloadParameterNames
No
payloadParameterNames
This is a list where you need to provide the names of the parameters. The RestServiceWrapper can accept an Object[] as message payload, in which case it will extract the name parameter x from the payloadParameterNames and associate it with item x in the Object[]. If the payload is a simple object, the RestServiceWrapper will grab the first element from the payloadParameterNames and associate it with the payload. Since 1.4.2
No
Document generated by Confluence on Apr 24, 2008 08:11
Page 17
errorFilter
By default the RESTServiceWrapper uses a Regular Expression filter on REST service invocation result to determine if an error occurred. However, any filter configuration can be used to determine an error result by setting the errorFilter
No
errorExpression
A RegEx expression to execute on the result of the service invocation to determine if an error occurred.
No (if the errorFilter is set explicitly)
The MULEINTRO:Stock Quote Example demonstrates how to configure the RESTServletWrapper. It calls an ASPX Stock Quote service hosted by http://www.webservicex.net.
Document generated by Confluence on Apr 24, 2008 08:11
Page 18
Standard Components This page last changed on Jan 30, 2008 by ross.
Components are used to execute custom business logic in a Mule application. They are typically written according to application requirements. Still, Mule ships with some default components.
Simple components These are useful for testing or bypassing component execution.
Class Name
Description
org.mule.components.simple.BridgeComponent
A bridge between an inbound and outbound endpoint. Can be found at . Also see usage with Forwarding Consumer.
org.mule.components.simple.EchoComponent
Will send back whatever you send it.
org.mule.components.simple.LogComponent
Will log any events it receives to the console.
org.mule.components.simple.NullComponent
Prefer BridgeComponent instead. This is used when setting up a forwarding/pipeline component where a message is received on one endpoint and piped directly to another without invoking a component.
org.mule.components.simple.PassThroughComponentPrefer BridgeComponent instead. This should only be used if interceptor calls or component statistics are required because BridgeComponent doesn't call nor update those.
Specialized components These are more specialized towards various technologies or concepts.
Name
Description
MULE:BPEL Component
Execute BPEL processes using PXE BPEL engine.
org.mule.components.rest.RESTServiceWrapper
Proxy remote call to REST style web services as local components.
org.mule.components.script.jsr223.ScriptComponentRun scripts (JSR-223) as Mule components.
Document generated by Confluence on Apr 24, 2008 08:11
Page 19
Bridge Component This page last changed on Jan 30, 2008 by ross.
The org.mule.components.simple.BridgeComponent is a standard Mule component that enables a bridge between an inbound and outbound endpoint. Transformers can be used on the endpoints to convert the data being received in order to 'bridge' from one endpoint transport to another. When the BridgeComponent is used, it configures itself so that it will not actually be invoked, instead it tells Mule to bypass invocation of the component, which has a slight performance improvement. Note that because the compoennt is never actually invoked any interceptors configured on the component will not be invoked either. Example usage: Reading a file and send its contents onto a Jms Topic. <mule-descriptor name="FileToJmsBridge" implementation="org.mule.components.simple.BridgeComponent"> <endpoint address="file:///data/in"> <endpoint address="jms://topic:receivedFiles"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 20
Transformers This page last changed on Apr 15, 2008 by tcarlson.
Transformers are used to convert inbound data to an object type required by the UMO Component or outbound to an object type required by the transport such as a JmsMessage. Transformers can be configured on Endpoints that receive data to ensure that the expected object type is always received by an UMO Component. Transformers configured on an Outbound endpoint ensure that the endpoint receives the the correct object type before dispatching the event. Multiple transformers can be chained together to allow for finer grained transformer implementations that are easier to reuse. To configure an Endpoint to use more than one transformer, just specify a space separated list of transformers in the config file or programmatically chain the transformers together using the setNextTransformer() method on the transformer. For example an inbound transformer may look like Cannot resolve external resource into attachment. And an outbound transformer might look like Cannot resolve external resource into attachment. All Mule transformers must implement org.mule.transformer.UMOTransformer. There is an abstract transformer implementation that defines methods for controlling the object types this transformer supports and validates the expected return type, leaving the developer to implement a single transform() method.
Standard Transformers Below are a list of standard transformers for Mule. Individual transports may also have their own transformer types and these will be documented in the Transports Guide.
Xml These transformers can be found in the org.mule.transformers.xml package. XmlToObject <-> ObjectToXml Xml to Java Object and back again using XStream. XSLT Transform Xml payloads using XSL. DomToXml <-> XmlToDom Convert between dom objects and Xml. JXPath Query and extract Object graphs using XPath expressions. Scripting Transform objects using scripting, e.g. JavaScript or Groovy scripts.
Encryption These transformers can be found in the org.mule.transformers.encryption package. Encryption <-> Decryption A pair of transformers that will use a configured UMOEncrpytionStrategy implementation to Encrypt and Decrypt data.
Compression These transformers can be found in the org.mule.transformers.compression package and do not require any special configuration. GZipCompressTransformer <-> GZipUncompressTransformer
Document generated by Confluence on Apr 24, 2008 08:11
Page 21
A pair of transformers that can compress and uncompress data.
Encoding These transformers can be found in the org.mule.transformers.codec package and do not require any special configuration. SGMLEntityEncoder <-> SGMLEntityDecoder Convert to and from SGML entity encoding. Base64Encoder <-> Base64Decoder UUEncoder <-> UUDecoder UCEncoder <-> UCDecoder
Object These transformers can be found in the org.mule.transformers.simple package and do not require any special configuration. ByteArrayToSerializable <-> SerializableToByteArray Serialize and deserialize objects. StringToByteArray <-> ByteArrayToString Convert between strings and byte arrays.
Transformation Best Practices You may be wondering, how should I handle a given situation with regards to transformation and Mule. Here is a quick guide which will try to address some best practices with Mule around transformations: Transformations and Mule Best Practices
Document generated by Confluence on Apr 24, 2008 08:11
Page 22
XmlObject Transformer This page last changed on Jan 30, 2008 by ross.
Document generated by Confluence on Apr 24, 2008 08:11
Page 23
Writing Components This page last changed on Jan 30, 2008 by ross.
As components in Mule can be plain old objects it's not always clear to the newcomer how Mule will interact with their component.
Entry Points The entry point is the method executed by Mule when an event is received for the component. When an event is received for your component Mule dynamically chooses the method to invoke based on the payload type of the event. This means potentially your component may have many entry points. The payload type of the event is almost always determined by the inbound transformer for the provider that recieved the event for your component, but some providers such as the soap provider manage type mappings themselves so there are no need for transformers. If your component implements the Mule default event interface org.mule.umo.lifecycle.Callable it will override any dynamic resolution and call the interface method implementation. If you need to call a method on the component having no arguments, see Calling no-arguments Methods (since Mule 1.4.2).
Event Flow Mule has some default behavior rules about managing event flow to and from your component. 1. When a event is received the Entrypoint method is invoked as decribed above. 2. The response or outbound message is obtained using the following a. If the method invoked is not void, (Callable.onEvent() returns an Object) the method return value is used. If null is returned no further processing is done for the current request. b. If the method is void, the parameters used to invoke the method are used. This assumes that the parameters themselves were altered or there was no change to the event. 3. The outbound event is then automatically routed according the components configurationa. If there is an outbound router configured, that will be invoked to route the event. b. If there is only a single outbound endpoint configured, that will be used. c. If there are multiple outbound endpoints configured, the first one will be used.
Customizing Behavior While the default event flow behavior is sufficient, in most cases you may at some point want to customize it. To do this, you need to get a reference to the org.mule.umo.UMOEventContext. This can be done in two ways Implement org.mule.umo.lifecycle.Callable. The event context is passed as a parameter on this interface. public interface Callable { public Object onCall(UMOEventContext eventContext) throws Exception; }
You can also obtain the EventContext from the static RequestContext UMOEventContext context = RequestContext.getEventContext();
From the EventContext you can send and receive events synchronously and asynchronously, manage transactions and override the default event flow behavior. For example UMOEventContext context = RequestContext.getEventContext(); UMOEndpoint endpoint = new MuleEndpoint("jms://localhost/topic:stock.quotes"); //to send asynchronously context.dispatchEvent(new MuleMessage("IBM:0.01", null), endpoint); //or to receive UMOMessage quote = context.receive(endpoint, 5000);
Document generated by Confluence on Apr 24, 2008 08:11
Page 24
Even when you use the event context to manually control event flow, when your method returns, Mule will route the outbound event as normal. You can stop Mule processing events further using the following 2 methods. 1. If your service method is not void you can return null. This tells Mule there is no further event information to process. 2. If your service method is void, Mule will use the inbound event payload as the outbound event payload. If you don't want this to happen, you need to make the following callcontext.setStopFurtherProcessing(true);
Component Lifecycle Your component can implement zero or more lifecycle interfaces, namely • org.mule.umo.lifecycle.Initialisable - Is called only once for the lifecycle of the component. It is called when the component is created when the component pool initializes. • org.mule.umo.lifecycle.Startable - Is call when the component is started. This happens once when the server starts and whenever the component is stopped and started either through the API or JMX. • org.mule.umo.lifecycle.Stoppable - Is call when the component is stopped. This happens when the server stops or whenever the component is stopped either through the API or JMX. • org.mule.umo.lifecycle.Disposable - Is call when the component is disposed. This is caled once when the server shutsdown.
Getting the components Descriptor A component can get a reference to its descriptor on startup by implementing org.mule.impl.UMODescriptorAware. The UMODescriptor holds all configuration information about a component.
Document generated by Confluence on Apr 24, 2008 08:11
Page 25
Calling no-arguments Methods This page last changed on Jan 30, 2008 by ross.
Quite often there's a need to call a method having no arguments as part of the flow ( MULE-896). One can't do it out of the box with Mule's entry point resolvers. Before Mule 1.4.2 the only workaround was to implement a thin wrapper using a Callable interface and delegate an invocation to the method. Many felt this was an intrusion in their ideal POJO worlds, and Mule 1.4.2 now features a facility to go about the problem declaratively.
Parameter Name
Description
Mandatory?
delegateClass
A JavaBean class to instantiate and delegate to.
Either delegateClass or delegateInstance must be provided
delegateInstance
An instance of the object to delegate to. Intended for container-injection, when the delegate is not necessarily managed by Mule.
Either delegateClass or delegateInstance must be provided
delegateMethod
A no-args method to call
Yes
A code example is worth a thousand words: <mule-descriptor name="WrapperUMO" implementation="org.mule.components.simple.NoArgsCallWrapper"> <endpoint address="vm://invoke"/> <properties> <property name="delegateClass" value="org.mule.tck.testmodels.fruit.Apple"/> <property name="delegateMethod" value="toString"/>
In the config above, the result of the Apple.toString() will be returned to the caller. <mule-descriptor name="FruitWasher" implementation="org.mule.components.simple.NoArgsCallWrapper"> <endpoint address="vm://invoke"/> <endpoint address="vm://out"/> <properties> <property name="delegateMethod" value="wash"/>
In the config above, a delegate is instead injected from the Spring container, and the result of the wash() method call on it routed to the vm://out endpoint.
Document generated by Confluence on Apr 24, 2008 08:11
Page 26
Configuration Options This page last changed on Feb 12, 2008 by aguenther.
All mule configuration is accessible from a single object org.mule.config.MuleConfiguration that can be accessed using: MuleConfiguration config = MuleManager.getConfiguration();
Configuration Variables The configuration object Mule uses is org.mule.config.MuleConfiguration and it defines the following properties:
Property Name
Description
model
A property file can specify more than one Mule model. If more than one is defined, this property tells Mule which model to load. If this is not specified, the first model is used. This property currently is not used
serverUrl
This is the URL used by the server itself to receive incoming requests. This enables clients such as the Mule Client to marshal remote requests to a MuleManager instance. The default value is tcp:// localhost:60504. If you set the serverUrl to an empty string, Mule server components will not be set up, this can be useful when testing.
configResources
Is a String array of the config resources names used to configure the server instance. This property is automatically set by the configuration builder used to construct the Mule instance and cannot be set directly.
workingDirectory
The directory where Mule can write any temporary files or persist messages. the default value for this is ./.mule
synchronous
Specifies whether Mule should process messages synchronously, i.e. that a Mule model can only process one message at a time, or asynchonously. The default value is 'false'
synchronousReceive
Determines whether when running synchronously, return events are received before returning the call. i.e. in jms whether to wait for a replyTo message. Note that it's usually a good idea to turn this off unless a result from a remote invocation is expected as the call will block until it times out. If you want to make specific synchronous receive calls per event you can set the MuleProperties.SYNCHRONOUS_RECEIVE property on the event i.e. event.setProperty(MuleProperties.SYNCHRONOUS_RECEIVE, "true");. The default value is 'false'
synchronousEventTimeout
When running sychonously and using synchronousReceive, return events can be received over transports that support ack or replyTo his property determines how long to wait
Document generated by Confluence on Apr 24, 2008 08:11
Page 27
in milliseconds for a receive before timeing out. The default value is '3000' recoverableMode
Determines whether Mule's internal queues are persisted. If the server dies unexpectedly Mule can resume processing when the server starts. Default value for this is 'false'
poolingProfile
A pooling profile is used to configure the pooling behaviour of UMO components. Each Mule component descriptor can set it's own pooling profile otherwise the one specified here will be used
queueProfile
This is the default queue profile used to create internal queues for managed components. Developers can specify a queue profile for each Mule Managed component if that component need a different configuration to other components in the system. By default non-persistent queues are used with a maxOutstandingMessage size of 1000
defaultThreadingProfile
This defines the default threading profile if no other is specified. Threading profiles can be specified for component pooling, message dispatcher and message receivers
componentPoolThreadingProfile
Allows the developer to define a specific Threading profile for all components. You can also specify threading profiles at the component level
messageReceiverThreadingProfile
Defines the Threading profile used by Connector message receivers when receiving messages. It is also possible to set a threading profile for a message receiver on the connector
messageDispatcherThreadingProfile
Defines the Threading profile used by Connector message dispatchers when the connector dispatches an event. It is also possible to set a threading profile for a message dispatcher on the connector
Pooling Profiles A pooling profile is used to configure the pooling behaviour of UMO components. each descriptor can set it's own pooling profile or a default one can be set on the mule-configuration. The org.mule.config.PoolingProfile contains all the necessary values to create a pool of UMOComponent proxies.
Property Name
Description
Default
maxActive
Controls the maximum number of Mule UMOs that can be borrowed from a Session at one time. When non-positive, there is no limit to the number of components that may be active at one time. When maxActive is exceeded, the pool is said to be exhausted.
5
Document generated by Confluence on Apr 24, 2008 08:11
Page 28
maxIdle
Controls the maximum number of Mule UMOs that can sit idle in the pool at any time. When nonpositive, there is no limit to the number of Mule UMOs that may be idle at one time.
5
initialisationPolicy
Determines how components in a pool should be initialised. The possible values (deprecated values in parentheses) are:
INITIALISE_ONE
• INITIALISE_NONE : Will not load any components into the pool on startup • INITIALISE_ONE (INITIALISE_FIRST) : Will load one initial component into the pool on startup • INITIALISE_ALL : Will load all components in the pool on startup exhaustedAction
Specifies the behaviour of the Mule UMO pool when the pool is exhausted:
WHEN_EXHAUSTED_GROW
• WHEN_EXHAUSTED_FAIL (FAIL) : will throw a NoSuchElementException • WHEN_EXHAUSTED_WAIT (BLOCK) : will block (invoke Object.wait(long) until a new or idle object is available. • WHEN_EXHAUSTED_GROW (GROW): will create a new Mule and return it(essentially making maxActive meaningless.) If a positive maxWait value is supplied, it will block for at most that many milliseconds, after which a NoSuchElementException will be thrown. If maxThreadWait is nonpositive, it will block indefinitely. maxWait
Specifies the number of milliseconds to wait for a pooled component to become available when the pool is exhausted and the exhaustedAction is set to WHEN_EXHAUSTED_BLOCK.
factory
A fully qualified classname of the pool factory to use with this pool profile. Implementations must implement org.mule.util.ObjectFactory
Document generated by Confluence on Apr 24, 2008 08:11
4000
Page 29
Threading Profiles Threading Profiles are used to control how thread pools behave in Mule. Thread pools in Mule use the JDK 1.4-compatible util.concurrent backport library so all the variables defined on org.mule.config.ThreadingProfile are synonymous with ThreadPoolExecutor.
Property Name
Description
Default
id
The threading profile system id is used to identify which system component should use the profile. This attribute is only used when declaring profiles on the <mule-evironmentproperties/> element and on connector components where 'messageReceiver', 'messageDispatcher', 'component' or 'default' can be used. For all other cases it can be set to 'default'
default
maxThreadsActive
Controls the maximum number of threads that can be executed at any one time in a thread pool.
10
maxThreadsIdle
Controls the maximum number threads that can be inactive or idle in a thread pool before they are destroyed.
10
threadTTL
Detemines how long an inactive thread is kept in the pool before being discarded.
60000
poolExhaustedAction
If the maximum pool size or queue size is bounded, then it is possible for incoming execute requests to block. There are five supported policies for handling this situation (deprecated shorthand values are in parentheses):
WHEN_EXHAUSTED_RUN
• WHEN_EXHAUSTED_RUN (RUN) : The thread making the execute request runs the task itself. This policy helps guard against lockup. • WHEN_EXHAUSTED_WAIT (WAIT) : Wait until a thread becomes available. This policy should, in general, not be used if the minimum number of of threads is zero, in which case a thread may never become available. • WHEN_EXHAUSTED_ABORT (ABORT) : Throw a RuntimeException
Document generated by Confluence on Apr 24, 2008 08:11
Page 30
• WHEN_EXHAUSTED_DISCARD (DISCARD) : Throw away the current request and return. • WHEN_EXHAUSTED_DISCARD_OLDEST (DISCARD_OLDEST) : Throw away the oldest request and return. threadWaitTimeout
Controls the time to wait for the WHEN_EXHAUSTED_WAIT policy, in milliseconds. Use -1 (or any other negative value) to wait forever.
30
maxBufferSize
Determines how many requests if any are queue when the pool is at maximum usage capacity. The buffer is used as an overflow.
0
Queue Profiles A Queue Profile is used to describe the the properties of an internal Mule queue. Internal queues are used to queue events for each component managed by Mule.
Property Name
Description
Default
maxOutstandingMessage
Defines the maximum number of message that can be queued.
1000
persistenceStrategy
A persistence strategy defines the mechanism used to store Mule events to a persistent store. Primarily, this is used for for persisting queued events to disk so that the servers internal state is mirrored on disk in case the server fails and needs to be restarted. If no strategy is set the any queues created from this profile are not persistent
null
Comments The Queue Profiles section has to be updated. The allowed properties, according to the API and DTD, are: • maxOutstandingMessage • persistent yc Posted by yuenchi.lian at Dec 19, 2007. .....................................................................................................................................................................
Document generated by Confluence on Apr 24, 2008 08:11
Page 31
Configuring Endpoints This page last changed on Feb 26, 2008 by kevin.depew.
Endpoints in Mule are used to communicate with other applications or mule instances. They are like message gateways through which events can be sent and received for more information see Mule Endpoints.
Configuration Endpoints can be configured on Exception Strategies, routers and catch-all strategies. The <endpoint> elements represents the org.mule.umo.endpoint.UMOEndpoint class. Lets start with a component example. the following configures one inbound and one outbound endpoint <mule-descriptor name="test" implementation="org.foo. MyComponent"> <endpoint address="jms://my.queue"/> <endpoint address="smtp://[email protected]"/>
The most simple endpoint configuration just needs to provide an address. For more information about configuring components go here. Attributes on the endpoint element are -
Attribute
Description
Required
address
A valid Mule Endpoint URI or an endpoint-identifier, which is a friendly name mapping to a URI specified in the cinfiguration in the <endpoint-identifiers> element
Yes
name
An Identifying name for the endpoint
No
connector
The name of the specific connector to use for this endpoint. If this is not specified the connector is selected from the currently registered connectors or one is created if none of the configured connectors know how to handle the scheme on the address
No
type
Determines whether the endpoint provider is a sender, receiver or a senderAndReceiver. An endpoint can be senderAndReciever meaning that there is no difference for the endpoint configuration if it is used as a sender or receiver. This attribute
Document generated by Confluence on Apr 24, 2008 08:11
Page 32
only applies if the endpoint is a global endpoint. transformers
A space-separated list of transformer to use with this endpoint. These will transform data when it is received or sent by the UMO component (depending on whether this endpoint is a receiver or not). Connectors such as Jms have default inbound and outbound transformers, If this value is not set the default transformers on the connector will be used.
No
Filters A filter can be configured on an endpoint to filter inbound messages. The filter can be transport specific such as a Jms selector or file filter or can be a general filter such as using JXPath to filter on email messages. Filtering is not supported by all transports and setting a filter on an endpoint using some transports will result in an UnsupportedOperationException. See the Transports Guide for more information about filtering on a particular transport. For more information about Filters see Filters.
Transactions Transaction element can be configured between two endpoints where the event processing between each is synchronous, this is controlled by setting the synchronous property on the connectors for each of the endpoints. For more information about configuring transactions go here.
Properties Properties on endpoints can be used to customise behaviour for a particular endpoint instance. Any properties set on the endpoint can be used to overload properties on the connector. An example of this would be having an Smtp outbound endpoint and setting the fromAddress. See Configuring Properties for more information about how various property types can be used.
Global Endpoints Global endpoints are configured Endpoints that are registered with the MuleManager. This means any object in Mule can make use of these endpoints. When you reference a global endpoint Mule actually returns a clone of the Endpoint. This allows client code to change any attributes on the endpoint without affecting other objects in the system that also use the endpoint. To configure a global endpoint in the Mule Xml configuration use the following <mule-configuration> <endpoint name="ExceptionQueue" address="jms://exception.queue"/> .... <mule-configuration>
A clone of this endpoint can be obtained in code using UMOEndpoint endpoint = MuleManager.getInstance().lookupEndpoint("ExceptionQueue");
To reference a global endpoint in the configuration you use the element. The only attibutes that can be set on this element are -
Document generated by Confluence on Apr 24, 2008 08:11
Page 33
• name - The name of the global endpoint to use. • address - an URI string that will override the address configured on the endpoint You can also set properties, transactions and filters on the referenced endpoint and these will override the values set on the global endpoint. To use the global ExceptionQueue endpoint as the catch all endpoint on our router do the following <mule-descriptor name="test" implementation="org.foo. MyComponent"> <endpoint address="smtp://[email protected]"/>
Endpoint Identifiers Endpoint identifiers can be used to map logical names to endpoint URIs. These identifiers can be used in place of the actual URI in the configuration and in code. This allows you to define all your endpoint URIs in one location which can be very useful when you move Mule instances between environments. <mule-configuration> <endpoint-identifiers> <endpoint-identifier name="Component1Inbound" value="jms://in.queue"/> <endpoint-identifier name="Component1Outbound" value="jms://out.queue"/> <endpoint-identifiers> <model> <mule-descriptor name="Component1" inboundEndpoint="Component1Inbound" outboundEndpoint="Component1Outbound" implementation="com.foo.Component"> <mule-configuration>
Document generated by Confluence on Apr 24, 2008 08:11
Page 34
Configuring Components This page last changed on Jan 30, 2008 by ross.
The below configuration which is also depicited in the Hello World example shows you how to configure endpoints at Component level. This is the simplest form of defining a endpoint. Here the component GreeterUMO would receive the event by configuring the attribute named inboundEndpoint. Similarly the component GreeterUMO would send the event by configuring the outboundEndpoint attribute. <mule-descriptor name="GreeterUMO" inboundEndpoint="stream://System.in" inboundTransformer="StringToNameString" outboundEndpoint="vm://chitchatter" implementation="org.mule.samples.hello.Greeter">
Document generated by Confluence on Apr 24, 2008 08:11
Page 35
Configuring Mule Programmatically This page last changed on Jan 30, 2008 by ross.
Developers can use the QuickConfigurationBuilder to programmatically build a Mule Manager instance. This can be especially useful when configuring a Mule Instance from script or for test cases. You can configure a server with only a few lines of code, for example to configure a server with a single component QuickConfigurationBuilder builder = new QuickConfigurationBuilder(); builder.createStartedManager(true, "tcp://localhost:60504"); UMOEndpoint inboundEndpoint = new MuleEndpoint("axis:http://localhost:81/services"); builder.registerComponent(EchoComponent.class.getName(), "echoComponent", inboundEndpoint);
This creates a new Mule Instance with a server admin url of 'tcp://localhost:60504' (if you don't want the Mule Admin Agent to start, set this to ""). It also creates a Mule Component called 'echoComponent' that is an Axis web service that will receive requests on 'http://localhost:81/services/echoComponent'. The following example creates an asynchronous Mule Instance without an Admin Agent with a single component that receives events via tcp and writes them out to file. QuickConfigurationBuilder builder = new QuickConfigurationBuilder(); builder.createStartedManager(false, ""); UMOEndpoint inboundEndpoint = new MuleEndpoint("tcp://localhost:5555"); UMOEndpoint outboundEndpoint = new MuleEndpoint("file:///tmp/events"); builder.registerComponent(AnotherComponent.class.getName(), "aComponent", inboundEndpoint, outboundEndpoint);
The next example demonstrates adding additional configuration to the manager. In this case adding a jms connector. QuickConfigurationBuilder builder = new QuickConfigurationBuilder(); UMOManager manager = builder.createStartedManager(false, ""); //Only the jms connector cannot be created automatically, //so we must create one, we'll use ActiveMQ JmsConnector connector = new JmsConnector(); connector.setName("jmsConnector"); connector.setJndiInitialFactory("org.codehaus.activemq.jndi.ActiveMQInitialContextFactory"); connector.setConnectionFactoryJndiName("ConnectionFactory"); connector.setSpecification(JmsConnector.JMS_SPECIFICATION_11); //Register the connector with the server manager.registerConnector(connector); UMOEndpoint inboundEndpoint = new MuleEndpoint("tcp://localhost:5555"); UMOEndpoint outboundEndpoint = new MuleEndpoint("jms://topic:jms.topic"); builder.registerComponent(AnotherComponent.class.getName(), "aComponent", inboundEndpoint, outboundEndpoint);
Document generated by Confluence on Apr 24, 2008 08:11
Page 36
Configuring Properties This page last changed on Feb 15, 2008 by kevindepew.
Quick Links Standard Properties - Simple key/value pairs System Properties - Using system properties Container Properties - Setting objects as properties from a container such as Jndi or Spring Map Properties - Defining property maps List Properties - Defining property lists and arrays File Properties - Loading properties from file Text Properties - Embedding Scripts and Xml in your configuration Factory Properties - Using Object factories to create properties Property Placeholders - Using variables
Mule Properties Most of the configuration elements in the Mule Xml configuration can have a <properties> element. This defines a set of bean properties that will be set on an object using standard getters and setters. As such, the properties names themselves must follow the JavaBean naming convention where the 'get' or 'set' part of the property method is removed and the first character of the property name is lowercase. So for a bean that has a methods getTestProperty() and setTestProperty(...) the property name is testProperty. <properties> <property name="testProperty" value="foo"/>
If a property is of type boolean, int, long, double, byte or float it will be automatically converted to the correct type. Properties can also be Maps, Lists arrays,System properties, objects from a configured IoC container and factory objects. Each of these are described in more detail below.
System Properties A property can be set as a system property i.e. a property retrievable using String prop = System.getProperty("prop");
To define a system property you must use the <system-property> element. <properties> <system-property name="testProperty" key="TestProperty" defaultValue="foo"/>
The name attribute refers to the name of the property on the bean, the key is the name of the property to look for in the System properties. The defaultValue provides an optional default value if the property is not set on the System properties. If the desired default value is null, just omit this attribute.
Container Properties These are properties that are retrieved from a configured IoC or Naming container, such as Spring, Jndi or EJB. The container is configured on the root configuration element using the ≶container-context> element. See Object Containers for more information. <properties>
Attribute
Document generated by Confluence on Apr 24, 2008 08:11
Description
Page 37
name
specifies the bean property name. If the object has methods setTestProperty(..) and getTestProperty() the property name is testProperty.
reference
The reference name of the object in the container.
required
Determines whether an exception is thrown if the object reference is not found in the container. The default is true.
container
An optional attribute that tells Mule only to look for the object in the specifed container, otherwise Mule will search all containers in the order they are configured.
Factory Properties Factory properties allow a property attribute to be created using a factory object. For example, in testing you might want a property factory to create an InitialContext to save setting up Jndi. A property factory must implement org.mule.config.PropertyFactory. This interface has a single method create with a java.util.Map parameter that is a map of all the properties contained within the current <properties> element. So you can configure properties for the factory instead of the bean itself if required. <properties>
Configuring Maps Maps can be expressed in a properties element using the <:map> element. The name of the property is specified as an attribute of the element and each property entry below will be added to the map. <properties> <map name="testMap"> <property name="testProperty1" value="foo"/> <property name="testProperty2" value="bar"/>
A map element can contain all types of property elements listed above. <properties> <map name="testMap"> <system-property name="testProperty2" value="bar"/> <property name="testProperty4" value="test4"/>
Configuring Lists Lists and Arrays are configured in the same way, in that there is not difference in configuring an array or list in the configuration file, when the property is set it will be converted to a List or array depending on the expected type. <properties> <list name="testList"> <entry value="foo"/> <entry value="bar"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 38
You can configure list entries as container, factory or system properties by using the 'container-entry', 'factory-entry' and 'system-entry' respectively. <properties> <list name="propertiesList"> <system-entry key="os.version"/> <entry value="test1"/>
Loading properties from a file You can load properties for any object from a Java .properties file by using the 'file-properties' element. This will load a properties file from the classpath or file system. You can also specify an 'override' property that if set to true will over write any properties already configured on the object. The default for 'override' is true. <properties>
Text Properties You can load a blob of text as a property string inside a Mule Xml Configuration file. This text can be an embedded script, Xml, Xsl or any other type of text string. If embedding Xml you need to wrap the text in a CDATA block. For example, to embed xml <properties> ]]>
The CDATA block is not necessary if embedding regular text. The following example embeds a groovy script <mule-descriptor name="GroovyUMO1" inboundEndpoint="vm://groovy.1" implementation="org.mule.components.script.jsr223.ScriptComponent"> <properties> return "Groovy Received!" <property name="scriptEngineName" value="groovy"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 39
Property Placeholders Property placeholders can be used to substitute a property value in the Mule Xml configuration at run time. Properties can be loaded from Java .properties files and be referenced by any attribute in the Mule Xml configuration using familiar ant-style notation. Say you have a jndi.properties file with properties in it jms.initial.context=org.jnp.interfaces.NamingContextFactory jms.provider.url=jnp://localhost/ jms.connection.factory=java:/ConnectionFactory jms.specification=1.1
These properties can then be loaded into the MuleManager properties. To load property values the Mule Xml 'environment-properties' element must be used. <mule-configuration> <environment-properties> ...
Now you can reference the property values using property placeholders <properties> <property name="connectionFactoryJndiName" value="${jms.connection.factory}"/> <property name="jndiInitialFactory" value="${jms.initial.context}"/> <property name="jndiProviderUrl" value="${jms.provider.url}"/> <property name="specification" value="${jms.specification}"/>
If a property is not found in the environment-properties the property placeholder is left intact. Theoretically any attribute value in Mule Xml configuration can be substituted with a property placeholder. However, the mule-configuration.dtd will complain if a placeholder is used in an attribute that is an NMTOKEN or ID dtd type, such as class names. If you want to use placeholders in these fields you will have to customise the mule-configuration.dtd.
Document generated by Confluence on Apr 24, 2008 08:11
Page 40
EJB This page last changed on Jan 30, 2008 by ross.
EJB Session Beans - Configure Mule to manage your EJBs. Ejb Transport - Invoke remote Ejb session beans from your components. Mule Resource Adapter - deploy Mule to your Application server and use JCA to configure your EJBs to use Mule transports. App Server Integration - Help deploying the Mule Resource Adapter to specific Application Servers. Managing EJBs From Spring - how to invoke Spring-managed EJBs from Mule.
Document generated by Confluence on Apr 24, 2008 08:11
Page 41
EJB Session Beans This page last changed on Jan 30, 2008 by ross.
The EjbContainerContext can be used to expose EJB Session beans as Mule components. To configure an Ejb container you need to add a element that uses the org.mule.impl.container.EjbContainerContext and set the Jndi environment properties. The following example configures a JBoss Ejb container context <properties> <map name="environment"> <property name="java.naming.factory.initial" value="org.jnp.interfaces.NamingContextFactory"/> <property name="java.naming.provider.url" value="jnp://localhost"/> <property name="java.naming.factory.url.pkgs" value="org.jboss.naming:org.jnp.interfaces"/> <property name="securityPolicy" value="/projects/foo/classes/wideopen.policy"/> <property name="securityManager" value="java.rmi.RMISecurityManager"/>
Components can reference an Ejb session bean by setting the implementation attribute of a <muledescriptor> to the name of the Session bean stored in Jndi. <mule-descriptor name="EJBComponent" implementation="myEjbRef"> ....
Document generated by Confluence on Apr 24, 2008 08:11
Page 42
Spring EJB This page last changed on Jan 30, 2008 by ross.
The following sample code and spring config fragements together with examples on page Using Spring as a Component Factory, will help illustrate how Ejb can be exposed as Mule components via Spring container.
Code your business interface class Using business delegate pattern to extend those business methods on Ejb client class that will be called by Mule UMO. public interface KitchenService extends KitchenServiceEjbClient{ public void submitOrder(Order order); }
Setting up Spring <property name="jndiEnvironment"> <props> <prop key="java.naming.factory.initial">${InitialContextFactoryClassName} <prop key="java.naming.provider.url">${ProviderUrl} <prop key="java.naming.security.principal">${Uid} <prop key="java.naming.security.credentials">${Password} <property name="jndiName"> kitchenService <property name="businessInterface"> com.foo.KitchenService <property name="kitchenService">
Spring 1.2.x Starting from Spring 1.2, you can use a simpler form for property configuration. See Section 3.3.3.7 in Spring Reference Documentation for details. The above config would look like this: ... <property name="jndiName" value="kitchenService"/ <property name="businessInterface" value="com.foo.KitchenService"/> <property name="kitchenService" ref="kitchenService"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 43
Escape URI Credentials This page last changed on Jan 30, 2008 by ross.
Escape your credentials Sometimes you'll have illegal (for URI) characters in your login/password. Use the standard escape syntax your browser would use, e.g. the username user@mule would become user %40mule.
Document generated by Confluence on Apr 24, 2008 08:11
Page 44
Exception Strategies This page last changed on Apr 18, 2008 by dirk.
Exception strategies are used to handle exception conditions when an error occurs processing an event. There are two objects that support Exception strategies; components and connectors, plus a common component exception strategy for components can be set on the model. Cannot resolve external resource into attachment. Exception Strategies associated with components or the Model are used to handle component exceptions. These are typically business logic exceptions and the user will often want to customise the exception handler to control how these exceptions are logged and routed. Exceptions strategies associated with the connector handle exceptions thrown when events are received or sent using a connector. It is less common that these strategies will be customised by the developer but they may be configured to route exceptions to a common error queue. The default exception strategy used by the model (and thus all components managed by the Model) is org.mule.impl.DefaultComponentExceptionStrategy and the connectors use org.mule.impl.DefaultExceptionStrategy by default. Both of these strategies can be configured to dispatch to one or more endpoints.
Component Exception Strategies A strategy can be set on a component using the <exception-strategy> element in Mule XML <mule-descriptor name="myComponent" implementation="org.foo.MyComponent"> ... <exception-strategy className=" org.mule.impl.DefaultComponentExceptionStrategy"/>
Or you can set a common strategy for all components managed by the Model by setting it on the Model <model name="myModel"> ... <exception-strategy className=" org.mule.impl.DefaultComponentExceptionStrategy"/> ...
This will cause all components to use this exception strategy unless there is one explicitly defined for the component. You can set a endpoint on an exception strategy to forward the event that failed to a destination such as an error queue. The org.mule.impl.DefaultComponentExceptionStrategy is a default implementation that can be configured with an endpoint i.e. <mule-descriptor name="mycomponent" implementation="org.foo.mycomponent"> ... <exception-strategy className=" org.mule.impl.DefaultComponentExceptionStrategy"> <endpoint address="jms://error.queue"/>
To implement your own strategy you class can extend the org.mule.impl.AbstractExceptionListener though it is recommended that you extend the DefaultComponentExceptionStrategy and just overload the defaultHandler() method. Bean properties can be set on your custom exception strategy in the same way as other Mule configured objects using a <properties> element. <mule-descriptor name="myComponent" implementation="org.foo.MyComponent">
Document generated by Confluence on Apr 24, 2008 08:11
Page 45
... <exception-strategy className=" org.mule.impl.DefaultComponentExceptionStrategy"> <endpoint address="jms://error.queue"/> <properties> <property name="foo" value="bar"/>
It is up to the defaultHandler() method to do all necessary processing to contain the exception. In other words an exception should never be thrown from an Exception Strategy. In situations were a fatal error occurs the strategy must manage this as well. For example, if an error queue is being used but the dispatch fails you might want to stop the current component and fire a server notification to alert a system monitor and write the event to file. In some situations, you might want to change the way exceptions are logged. If so, all you have to do is override the logException() method from the AbstractExceptionListener.
Connector Exception Strategies connector Exception Strategies are configured in the same way and behave in the same way as Component exception Strategies. ... <exception-strategy className=" org.mule.impl.DefaultExceptionStrategy"/>
The main difference is the type of exceptions that a Connector Exception Strategy will have to deal with. These exceptions will typically be connection related exceptions that may or may not be recoverable. The org.mule.impl.DefaultExceptionStrategy is the default used for connectors that simply logs the exception and continues.
Document generated by Confluence on Apr 24, 2008 08:11
Page 46
Filters This page last changed on Feb 07, 2008 by kevindepew.
Filters Quick Reference • • • • • • • •
Payload Type Filter RegEx Filter Wildcard Filter XPath Filter OGNL Filter Logic Filters Message Property Filter Writing your own Filters
Configuring Filters Filters can be used to express the rules that control how routers behave. Mule has the following default filters: PayloadTypeFilter will check the class type of the payload object inside an event.
RegExFilter will apply a regular pattern to the event payload. The filter will do a toString() on the event payload, so users may also want to apply a PayloadTypeFilter as well to the event using an AndFilter to make sure the event payload is a String.
WildcardFilter will apply a wildcard pattern to the event payload. The filter will do a toString() on the event payload, so users may also want to apply a PayloadTypeFilter as well to the event using an AndFilter to make sure the event payload is a String. For the string "the quick brown fox jumped over the lazy dog" the following patterns would match • *x jumped over the lazy dog • the quick* • *fox*
JXPathFilter JXPath is an XPath interpreter that can apply XPath expressions to XML DOM objects or any other object graph. For more information about JXpath see the user guide or this tutorial. Also there is a good XPath tutorial at zvon.org.
It is possible to set other JXPath context properties on the filter. Two of the important ones are namespaces and value which is used to compare to the result of the XPath expression (value is 'true' by default).
Document generated by Confluence on Apr 24, 2008 08:11
Page 47
className="org.mule.routing.filters.xml.JXPathFilter"> <properties> <property name="value" value="success"/> <map name="namespaces"> <propety name="foo" value="http://www.foo.org/ns"/>
OGNLFilter OGNL is a simple yet very powerful expression language for plain Java objects. Similar to (J)XPath it works on object graphs; the corresponding filter therefore enables simple and very efficient content routing for payloads. As an example: <properties> <property name="expression" value="\[MULE:0\].equals(42)"/>
This filter would block any messages whose payloads are not arrays or lists and do not contain the value 42 as first element. MessagePropertyFilter This filter allows you add logic to your routers based on the value of one or more properties of a Message. This can be very powerful because Message properties of the underlying message are exposed meaning you can reference any transport-specific or user defined property. So for an Http event you can match one or more Http Headers; the same applies for all other message types such as Jms or email.
The expression is always a key value pair. If you want to have more complex extressions you can use the logic filters. For example
Logic Filters AndFilter An And filter combines two filters and only accepts if both filters match. Logic filters can be nested so that more complex logic can be expressed.
OrFilter The Or filter combines two filters and accepts if either of the filters match.
Document generated by Confluence on Apr 24, 2008 08:11
Page 48
NotFilter A not filter will accept if the filter assigned to it does not accept.
Writing your own filters The filters provided should be able to handle most filtering requirements however if you need to write your own it is really easy. You just need to implement the UMOFilter interface which has a single method. public boolean accept(UMOMessage message);
This method should return true if the UMOMessage matches whatever critia the filter imposes otherwise it should return false. Like all other Mule object bean properties can be set on the filter. The Mule DTD defines a number of default attibutes that can be set on a element in Mule Xml such as pattern, expression, configFile, expectedType and path. You don't have to use these if you dont want to as you can set any property using the <properties> element.
Document generated by Confluence on Apr 24, 2008 08:11
Page 49
Functional Testing This page last changed on Mar 13, 2008 by lorraine.busuttil.
Testing Mule As Mule is light-weight and embeddable it is easy to run a Mule Server inside a testcase. In fact Mule provides an abstract JUnit test case called org.mule.tck.FunctionalTestCase for running Mule inside a testcase and manages the lifecycle of the server. The Mule TCK also contains a number of other supporting classes for functionally testing Mule code. These are described in more detail in the following sections.
The FunctionalTestCase The FunctionalTestCase is a base test case for tests that initialize Mule using a configuration file. Generally we would make our Mule test cases extend the FunctionalTestCase so that we could use its functionality. The default configuration builder used in the FunctionalTestCase is the MuleXmlConfigurationBuilder. For this to work you need to have the mule-modules-builders jar on your classpath. This enables us to just enter the name of the mule configuration file we are using in the method getConfigResources and the FunctionalTestCase would automatically call the default builder to configure Mule. protected String getConfigResources() { return"mule-conf.xml"; }
Here, you can specify a comma-separated list of config files. If you want to use a different configuration builder, just overload the getBuilder() method of this class to return the type of builder you want to use with your test. protected ConfigurationBuilder getBuilder() { return new ScriptConfigurationBuilder("groovy"); }
Quick Links to Examples • A Complete Test Example using a Mule Configuration File • A Complete Test Example using the QuickConfigurationBuilder • Example Using the QuickConfigurationBuilder to get the instance of a Spring bean • Example Using the FunctionalTestCase with the Mule Configuration File to get the instance of a Spring bean
The FunctionalTestComponent: The FunctionalTestComponent is a component which, as the name implies, is used in the testing environment. The component comprises of two methods: the onCall method and the onReceive method that basically do the same thing
Document generated by Confluence on Apr 24, 2008 08:11
Page 50
• onCall: receives a UMOEventContext as input and returns an Object. • onReceive: receives an Object as input and returns an Object. What the FunctionalTestComponent does in either one of the methods is to take the message passed to it (either from the UMOEventContext or from the Object) and transform it into a String. It will then create a message that it will send back to the caller. It also checks whether either one of its three properties are set and acts accordingly.
The Properties of the FunctionalTestComponent: • String returnMessage • EventCallback eventCallback • boolean throwException
The returnMessage Property By default the FunctionalTestComponent returns the received message and appends the word "Received" to it, i.e. if we send the message "Hello World" it returns the message "Hello World Received". The returnMessage property enables us to replace this default message with one of our own. We can set our message in the returnMessage property in one of two ways: We could set this property on the component in the mule-config.xml file <mule-descriptor name="myComponent" implementation="org.mule.tck.functional.FunctionalTestComponent"> <endpoint address="vm://test"/> <endpoint address="vm://testout"/> <properties> <property value="Customized Return Message" name="returnMessage"/>
We could set the property programmatically in our test case. FunctionalTestComponent myComponent = new FunctionalTestComponent(); single.setReturnMessage("Customized Return Message");
The eventCallback Property The eventCallback is a property which refers to the EventCallback interface. The scope of the Event Callback is to be able to get a component we are using and to control it. This is especially useful when we have beans configured in Spring that we need to exercise some form of control on, example setting properties at runtime instead of in the configuration. To be able to use the eventCallback from our test case, first we need to make our test case implement the EventCallback interface. Then we would need to implement the single method that this interface exposes, i.e. the eventReceived method. In the example below, we are using the eventReceived method to get a message from the event context. Then we transform the component received as an input parameter into a FunctionalTestComponent by typecasting it and we set the returnMessage property discussed previously on the FunctionalTestComponent at runtime. public void eventReceived(UMOEventContext context, Object Component) throws Exception {
Document generated by Confluence on Apr 24, 2008 08:11
Page 51
UMOMessage message = context.getMessage(); FunctionalTestComponent fc = (FunctionalTestComponent) Component; fc.setReturnMessage("Customised Return Message"); }
For Information regarding how to use the EventCallback with components configured as Spring beans click on the following link: Using the eventCallback with a bean configured in Spring
The throwException Property The throwException property enables us to throw a MuleException from inside the FunctionalTestComponent. By default this property is set to "false" so all we need to do is set it to "true". There are two ways we can go about doing this. 1. We could set this property on the component in the mule-config.xml file <mule-descriptor name="myComponent" implementation="org.mule.tck.functional.FunctionalTestComponent"> <endpoint address="vm://test"/> <properties> <property value="true" name="throwException"/>
2. We could use the QuickConfigurationBuilder to build the configuration in our test case and set the property programmatically. FunctionalTestComponent myComponent = new FunctionalTestComponent(); single.setThrowException(true);
FunctionalTestNotificationListener: When an event is received, the FunctionalTestComponent fires a notification informing us that the event has been received. It is up to us to set up a listener (the FunctionalTestNotificationListener) on our test to capture this notification. To be able to do so, we must first make our test case implement the FunctionalTestNotificationListener interface. Then we must implement the method exposed by this listener, which is the onNotification. In the example below, we check the notification.getAction to see whether it is the FunctionalTestNotification fired by the FunctionalTestComponent. If it is, we print it out to the console. public void onNotification(UMOServerNotification 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. When using the QuickConfigurationBuilder, which will soon be discussed, the listener is registered like so: builder.getManager().registerListener(this,"myComponent");
Alternatively we could set it directly on the MuleManager.
Document generated by Confluence on Apr 24, 2008 08:11
Page 52
MuleManager.getInstance().registerListener(listener);
Overloading the Default Configuration Builder: Sometimes it is useful to be able to able to overload the default configuration builder to be able to create the configuration builder through our test case. In such a case we would use the QuickConfigurationBuilder. With this type of configuration we must be careful to do the following: • • • • •
create a new Configuration Builder create a Mule Manager create our components create our endpoints register our components together with their endpointURIs
The following is an example where we use the QuickConfigurationBuilder to overload the default configuration builder. Note: The method setUp() is the implementation of the method exposed by the TestCase class which our test class extends. protected void setUp() throws Exception { builder = new QuickConfigurationBuilder(); // we create our MuleManager. builder.createStartedManager(false, null); // we create a "SINGLE" endpoint and set the address to vm://single UMOEndpoint vmSingle = builder.createEndpoint("vm://Single","SingleEndpoint", true); // we create a FunctionalTestComponent and call it myComponent FunctionalTestComponent myComponent = new FunctionalTestComponent(); builder.registerComponentInstance(myComponent, "SINGLE",vmSingle.getEndpointURI()); }
A Complete Example using the QuickConfigurationBuilder: We will now proceed in building a complete example using the FunctionalTestComponent as our component and configuring everything via the QuickConfigurationBuilder in our test case. This will amalgamate everything we discussed previously. public class MyTestCase extends TestCase implements EventCallback, FunctionalTestNotificationListener { QuickConfigurationBuilder builder; // this is where we create our configuration protected void setUp() throws Exception { builder = new QuickConfigurationBuilder(); // we create our MuleManager builder.createStartedManager(false, null); // we create a "SINGLE" endpoint and set the address to vm://single UMOEndpoint vmSingle = builder.createEndpoint("vm://Single","SingleEndpoint", true); // we create a FunctionalTestComponent and call it myComponent FunctionalTestComponent myComponent = new FunctionalTestComponent();
Document generated by Confluence on Apr 24, 2008 08:11
Page 53
// we set out Event Callback on our test class myComponent.setEventCallback(this); // we register our component instance. builder.registerComponentInstance(myComponent,"SINGLE",vmSingle.getEndpointURI()); // we register our listener which we called "SINGLE" builder.getManager().registerListener(this,"SINGLE"); }
We tear down our configuration once the test case is run. protected void tearDown() throws Exception { builder.disposeCurrent(); }
The eventReceived method is the implementation of the method exposed by the EventCallback interface. We simply set the returnMessage property on our FunctionalTestComponent to "Customized Return Message", which is the message that we will expect to be returned to our test case public void eventReceived(UMOEventContext context, Object Component) throws Exception { UMOMessage message = context.getMessage(); FunctionalTestComponent fc = (FunctionalTestComponent) Component; fc.setReturnMessage("Customized Return Message"); }
The following is our test case, i.e. from where we are going to send our request public void testSingleComponent() throws Exception { MuleClient client = new MuleClient(); // we send a message on the endpoint we created, i.e. vm://Single UMOMessage result = client.send("vm://Single", "hello", null); assertNotNull(result); assertEquals("Customized Return Message", result.getPayloadAsString()); }
The onNotification method where we assert that the notification received was the one fired by the FunctionalTestComponent public void onNotification(UMOServerNotification notification) { assertTrue(notification.getAction() == FunctionalTestNotification.EVENT_RECEIVED); } }
A Complete Example using the Mule Configuration file Using the FunctionalTestCase, we can run the same example as above but using the mule configuration file. So first, we need to configure the mule-config.xml file to add our FunctionalTestComponent. <mule-configuration id="Mule_Sample" version="1.0"> <mule-environment-properties enableMessageEvents="true"/> <model name="myTest Model"> <mule-descriptor name="myComponent" implementation=" org.mule.tck.functional.FunctionalTestComponent"> <endpoint address="vm://Single"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 54
Next we need to build a Test Case that extends the FunctionalTestCase. Since, unlike the test with the QuickConfigurationBuilder, we do not create the component ourselves but is created for us through the configuration, we need to get an instance of that component, i.e. myComponent. To do this we need to use the MuleManager and retrieve from it the instance of the component from the model as seen in the snippet of code below. FunctionalTestComponent myComponent = (FunctionalTestComponent)MuleManager.getInstance().getModel().getComponent("myComponent").getInstance();
Once we have the instance we have to create an eventCallback and set it on the component. Note that we do not have to configure the setUp method since the setup will be done automatically. However, you can implement the doPreFunctionalSetUp() method if you need to add some additional things set up in your configuration. public class MyTestCase extends FunctionalTestCase { public void testSingleComponent() throws Exception { FunctionalTestComponent myComponent = (FunctionalTestComponent)MuleManager._getInstance_().getModel().getComponent("myComponent").getInstance(); // Create Callback EventCallback callback = new EventCallback() { public void eventReceived(UMOEventContext context, Object o) throws Exception { UMOMessage message = context.getMessage(); FunctionalTestComponent fc = (FunctionalTestComponent) o; fc.setReturnMessage("Customised Return Message"); } }; // set callback myComponent.setEventCallback(callback); // send the request MuleClient client = new MuleClient(); UMOMessage message = client.send("vm://test","hello", null); }
We have to give the name of our configuration file to the method getConfigResources. We need to implement this method when extending the FunctionalTestCase. Note: Remember, the mule configuration must be on your classpath. protected String getConfigResources() { return "mule-config.xml"; } }
Using the eventCallback with a bean configured in Spring: When our mule-descriptor refers to a component whose implementation refers to a bean configured in Spring, getting the instance of the bean and setting the eventCallback is slightly different. Imagine we have our FunctionalTestComponent configured as a bean in Spring...
If we are configuring Mule with the configuration file then we would have to use the Mule Manager to get an instance of the bean from the ContainerContext. FunctionalTestComponent myComponent = (FunctionalTestComponent)MuleManager.getInstance().getContainerContext().getComponent("FunctionalTestBean");
Document generated by Confluence on Apr 24, 2008 08:11
Page 55
Alternatively, if we are using the QuickConfigurationBuilder to configure Mule we would get the Mule Manager through the builder in the following way. FunctionalTestComponent myComponent = (FunctionalTestComponent)builder.getManager().getContainerContext().getComponent("FunctionalTestBean");
Once we have retrieved the instance of the bean, we create an eventCallback and set it on the bean. EventCallback callback = new EventCallback() { public void eventReceived(UMOEventContext context, Object o) throws Exception { UMOMessage message = context.getMessage(); FunctionalTestComponent fc = (FunctionalTestComponent) o; fc.setReturnMessage("Customised Return Message"); } }; myComponent.setEventCallback(callback);
A Complete Example Using the QuickConfigurationBuilder to get the instance of a Spring bean The following is a complete example of how we would retrieve an instance of a spring bean from the springcontainer using the QuickConfigurationBuilder style of configuring Mule. public class MyTestCase extends TestCase implements FunctionalTestNotificationListener { QuickConfigurationBuilder builder; // this is the set-up of our configuration protected void setUp() throws Exception builder = new QuickConfigurationBuilder(); builder.createStartedManager(false, null);
{
//We need to create a SpringContainerContext and load the Spring configuration file in it. SpringContainerContext ctx =new SpringContainerContext(); ctx.initialise(); ctx.setConfigFile("spring-context-config.xml"); builder.setContainerContext(ctx); //We need to get an instance of the bean we have configured in Spring and set the Callback on it. FunctionalTestComponent myComponent = (FunctionalTestComponent)builder.getManager().getContainerContext().getComponent("FunctionalTestBean"); EventCallback callback = new EventCallback() { public void eventReceived(UMOEventContext context, Object o) throws Exception { UMOMessage message = context.getMessage(); FunctionalTestComponent fc = (FunctionalTestComponent) o; fc.setReturnMessage("Customised Return Message"); } }; myComponent.setEventCallback(callback); // Now we can continue to configure mule normally by adding the endpoints and registering the listener, etc. UMOEndpoint vmSingle = builder.createEndpoint("vm://Single","SingleEndpoint", true); builder.registerComponentInstance(myComponent, "SINGLE",vmSingle.getEndpointURI()); builder.getManager().registerListener(this,"SINGLE"); }
This is our normal teardown protected void tearDown() throws Exception {
Document generated by Confluence on Apr 24, 2008 08:11
Page 56
builder.disposeCurrent(); }
Now we proceed to set our test case. The FunctionalTestComponent should return the message "Customized Return Message". public void testSingleComponent() throws Exception { MuleClient client = new MuleClient(); UMOMessage result = client.send("vm://Single", "", null); assertNotNull(result); // expect the returning message to be Customised Return Message assertEquals("Customised Return Message", result.getPayloadAsString()); }
This is the notification of events that will listen for the notification fired by the FunctionalTestComponent. public void onNotification(UMOServerNotification notification) { assertTrue(notification.getAction() == FunctionalTestNotification.EVENT_RECEIVED); } }
Note: The Spring configuration file is still used to configure the beans.
A Complete Example using the FunctionalTestCase with the Mule Configuration File to get the instance of a Spring bean Using the FunctionalTestCase, we can run the same example as above but using the mule configuration file. So first, we need to configure the mule-config.xml file, with our component referring to the bean we have configured in Spring (FunctionalTestBean). Note: We will be using the same Spring bean we configured in the previous example. <mule-configuration id="Mule_Sample" version="1.0"> <mule-environment-properties enableMessageEvents="true"/> <properties> <property name="configFile" value="spring-context-config.xml"/> <model name="test"> <mule-descriptor name="myComponent" implementation="FunctionalTestBean"> <endpoint address="vm://test"/>
Next we need to build a Test Case that extends the FunctionalTestCase. We should get the instance of the component from the Container Context. FunctionalTestComponent myComponent = (FunctionalTestComponent)MuleManager._getInstance_().getContainerContext().getComponent("FunctionalTestBean");
As usual, once we get the instance of the bean, we can create an eventCallback and set it on the component. public class myTestCase extends FunctionalTestCase{ public void testIDontKnow() throws Exception
Document generated by Confluence on Apr 24, 2008 08:11
Page 57
{ FunctionalTestComponent myComponent = (FunctionalTestComponent)MuleManager.getInstance().getContainerContext().getComponent("FunctionalTestBean"); EventCallback callback = new EventCallback() { public void eventReceived(UMOEventContext context, Object o) throws Exception { UMOMessage message = context.getMessage(); FunctionalTestComponent fc = (FunctionalTestComponent) o; fc.setReturnMessage("Customised Return Message"); } }; myComponent.setEventCallback(callback); MuleClient client = new MuleClient(); UMOMessage message = client.send("vm://Single","hello", null); } protected String getConfigResources() { return "mule-config.xml"; } }
Document generated by Confluence on Apr 24, 2008 08:11
Page 58
General Transport Configuration This page last changed on Jan 30, 2008 by ross.
Transport providers can be configured in 3 ways 1. Using an endpoint URI that defines the scheme and connection information for the transport, such as tcp://localhost:12345. See Mule Endpoint URIs for more information. The URI consists of the protocol followed by transport specific information and then zero or more parameters to set as properties on the connector. 2. Defining a connector configuration in Mule XML, Spring or any other supported configuration. 3. Transport provider properties can be set on endpoints to customise the transport behaviour for a single endpoint instance. The actual configuration parameters for each transport type are described in the Transports Guide for each particular transport. The following describes the common properties for all transports.
Standard Connector Properties Property
Description
Default
Required
name
The identifying name of the connector
exceptionListener
The exception listener to use when errors occur in the connector.
org.mule.impl. Yes DefaultExceptionStrategy
receiverThreadingProfile
This defines the threading properties and WorkManager to use when receiving events from the connector
The Yes defaultReceiverThreadingProfile set on the Mule Configuration
Yes
dispatcherThreadingProfileThis defines the threading properties and WorkManager to use when dispatching events from the connector
The Yes defaultDispatcherThreadingProfile set on the Mule Configuration
createDispatcherPerRequest Determines whether the connector caches a MessageDispatcher once it has been created for an endpoint or if a new one should be created for each dispatch request
false
connectionStrategy
org.mule.providers. Yes SingleAttemptConnectionStrategy
Is the object responsible for controlling how connection failures and retries are handled. The connectionStrategy can attempt to make a connection based on frequency, retry attempts, Jmx, or some other trigger.
Document generated by Confluence on Apr 24, 2008 08:11
Yes
Page 59
serviceOverrides
Is a map of service configuration values that can be used to override the default configuration for this transport. Service Overrides are described later in this document
No
For information about specific properties for a particular transport provider see the Transports Guide.
Connection Strategies Connection strategies are used to configure how a connector behaves when its connection fails. Different strategies can be used to control how a reconnection is made based on retries, frequency, exceptions occurred or other factors such as only allowing a reconnect from JMX. A connection strategy is configured on the connector using the element. When a element is added to a connector the strategy is applied to inbound and outbound connections. If you require a different behaviour for inbound and outbound connections on the same connector you need to configure two connectors to handle inbound and outbound connections differently. For example, to configure a TCP connector that will try to connect 3 times every 2 seconds if the connection is lost <properties> <property name="retryCount" value="3"/> <property name="frequency" value="2000"/>
Tip: setting retryCount to -1 will make it retry connections infinitely (available since Mule 1.4.2). However, be careful with it depending on the nature of the transport. A doThreading option can be useful in certain cases, it'll decouple the Mule thread from the reconnection attempts. You can set a default connection strategy for all connectors on a Mule instance by setting the strategy in the <mule-environment-properties> element, i.e. <mule-environment-properties> <properties> <property name="retryCount" value="3"/> <property name="frequency" value="2000"/>
Customising Connection Strategies Mule comes with a few basic connection strategies such as the the SimpleRetryConnectionStrategy shown above. However, you may need to implement your own. The ConnectionStrategy is an interface with one method public void doConnect(UMOConnectable connectable) throws FatalConnectException;
This method should attempt to call connect() on the UMOConnectable object, until the connection works or the connection policy implemented by the custom UMOConnectionStrategy fails. If the connection fails a FatalConnectException should be thrown to tell Mule that it cannot connect. No other exceptions including RuntimeExceptions should be thrown.
Document generated by Confluence on Apr 24, 2008 08:11
Page 60
Connector Service Descriptors Each transport has a service descriptor that describes what classes are used to construct the transport. The file is located in META-INF/services/org/mule/providers and the file has the same name as the transport protocol i.e. META-INF/services/org/mule/providers/tcp. Using the TCP transport provider as an example the file looks like connector=org.mule.providers.tcp.TcpConnector dispatcher.factory=org.mule.providers.tcp.TcpMessageDispatcherFactory message.receiver=org.mule.providers.tcp.TcpMessageReceiver message.adapter=org.mule.providers.tcp.TcpMessageAdapter inbound.transformer=org.mule.transformers.simple.ByteArrayToString outbound.transformer=org.mule.transformers.simple.StringToByteArray endpoint.builder=org.mule.impl.endpoint.SocketEndpointBuilder
Property
Description
Required
connector
The class name of the UMOConnector implementation to use
Yes if no connector.factory
connector.factory
The class name of the factory that can be used to construct the UMOConnector instance if the 'connector' property is not set. The factory class must implement org.mule.util.ObjectFactory.
No
dispatcher.factory
The class name of the class that implements UMOMessageDispatcherFactory, which is used to construct UMOMessageDispatcher instances for this transport. If the transport provider only supports inbound communication this property is not set
No
message.receiver
The class name of the class that implements UMOMessageReceiver, which is used to register message listeners with the transport. If the transport provider only supports outbound communication this property is not set
No
transaction.factory
If this transport is transactional the property defines the class name of the UMOTransactionFactory implementation used to create transactions for this transport
No
message.adapter
The class name of the UMOMessageAdapter implementation used to provide generic access to information
Yes
Document generated by Confluence on Apr 24, 2008 08:11
Page 61
about the underlying message type for this transport inbound.transformer
The default inbound transformer for this transport. This transformer will be used to transform incoming messages if there is no transformer configured on the endpoint using this transport. If the endpoint is inbound and it defines a transformer this value will be ignored.
No
outbound.transformer
The default outbound transformer for this transport. This transformer will be used to transform outgoing messages if there is no transformer configured on the endpoint using this transport. If the endpoint is outbound and it defines a transformer this value will be ignored.
No
response.transformer
The default response transformer for this transport. Transports may or may no use this transformer depending on whether the transport supports sending responses back from a request; such as http. This transformer will be used to transform response messages if there is no transformer configured on the response router for the current component.
No
endpoint.builder
The endpoint builder used to configure MuleEndpointURI instances for the transport. It is responsible for extracting information from URIs in a way understood by this connector. For example, the URI jms://topic:datafeed will be processed by the ResourceNameEndpointBuilder such that the endpoint address will be 'datafeed' and 'topic' will be set as the resourceInfo for the endpoint telling the Jms connector to use/create a topic called 'datafeed'.
Yes
service.finder
Some transport providers such as SOAP provide multiple, vendor-specific implementations of the transport such as Axis, Glue or XFire. The service finder class can be used to determine which implementation to use, often based on what's on the
No
Document generated by Confluence on Apr 24, 2008 08:11
Page 62
classpath. so for the endpoint URI soap:http//localhost/8080/ services the SOAPServiceFinder will be used to see if Axis or Glue is on the classpath and will constuct the service accordingly. service.error
If for any reason a transport connector cannot be constructed using an endpoint URI, an error message can be set here and a ConnectorFactoryException will be thrown with this message if an attempt is made to construct the connector from an URI (instead of configuring the connector explicitly in configuration)
No
When an endpoint URI is processed by Mule, it's service descriptor is located using the endpoint protocol and the descriptor along with the information on the URI are used to create a connector and endpoint instance.
Overriding Service Properties Each Mule transport has a Connector Service Descriptor for each protocol the transport supports that contains some of the properties listed above. Users can override any of these settings for a particular transport so that its behaviour can be customised to suit a particular usage. For example the FileConnector reads individual files from a directory, but a developer could write a custom UMOMessageReceiver for the file connector to just read changes from an existing file. Every connector has a serviceOverrides property which is a map containing one or more of the service properties listed above. Continuing with the custom File Receiver example, a developer can override the 'message.reciever' Connector Service Descriptor property. <properties> ... <map name="serviceOverrides"> <property name="message.receiver" value="com.foo.MyFileReceiver"/>
Setting Default Connector values For some transports its easy to set all configuration info for the transport in URI i.e. tcp:// localhost:12345. For other transports such as JMS, the developer needs to set lots of configuration parameters to create the connection and it becomes difficult to set these parameters on the URI. One option is to pre-configure all connectors in a configuration file, which is fine for some scenarios. However there is another another option, Mule allows for default properties to be defined for connectors that will be used in absence of the properties being set directly. The properties themselves are set using the name of the property for the connector pre-pended with the connector protocol. For example, to set a default value for the JMS jndiInitialFactory property <environment-properties> <property name="jms.jndiInitialFactory" value="org.codehaus.activemq.jndi.ActiveMQInitialContextFactory"/>
or MuleManager.getInstance.setProperty("jms.jndiInitialFactory", "org.codehaus.activemq.jndi.ActiveMQInitialContextFactory");
Document generated by Confluence on Apr 24, 2008 08:11
Page 63
These properties can be set on the MuleManager or Client. For a more complete example see the Mule Cookbook: Configuring Multiple Jms Clients
Writing your own Transport If you want to implement a custom Transport for Mule see Writing Transports.
Document generated by Confluence on Apr 24, 2008 08:11
Page 64
How to Ask for Help on the Lists This page last changed on Jan 30, 2008 by ross.
Guidelines to Posting on the Mule User List If you're reading this you must be wondering what you have to do to increase the probability that your problem is resolved. Following is a brief discussion of what your explanation of the problem should include: • Explain briefly what you problem is. Use point form or short paragraphs as it makes it easier to read and understand. • Specify the Mule version, Jdk version as well as the version numbers of other technologies you are using in your application • If the application involves any complicated routing, it will be useful to provide a diagram of your system (possibly generated using the visualizer tool available with Mule). • Provide the relevant exception stack listing • Provide your configuration file or at least the relevant parts of your configuration. • Whenever possible, also provide a test case package that would illustrate your problem. Actually, this is the ideal situation since this will save other people from having to replicate your error first. We will now take a look at a problem which was actually taken from the Mule User List and illustrate how a test case can be built to illustrate the scenario depicted here.
Case Study: My server should be able to send a message with attachment (eg. image) to client over soap. I expect that sending image as an attachment would be more efficient than sending it as for example a byte array. A client should be able to receive the attachment and for example display it to the user. Service Component: public DataHandler getMapImage() throws Exception { BufferedImage image = ImageIO.read(new FileInputStream("map_image.jpg")); UMOMessage result = new MuleMessage("image"); DataSource ds = new ImageDataSource("image", image); DataHandler dataHandler = new DataHandler(ds); result.addAttachment("image attachement", dataHandler); return dataHandler; }
Service config: <endpoint-identifiers> <endpoint-identifier name="AxisWSEndpoint" value="axis:http://localhost:8080/services" /> <model name="soapGisSample"> <mule-descriptor name="gisService" implementation="sample.gis.Geo"> <endpoint address="AxisWSEndpoint" transformers="HttpRequestToSoapRequest"> <security-filter className="org.mule.extras.acegi.filters.http.HttpBasicAuthenticationFilter"> <properties> <property name="realm" value="mule-realm"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 65
Client: MuleClient client = new MuleClient(); String mapUrl = "axis:http://testuser:testpass@localhost:8080/services/gisService? method=getMapImage"; UMOMessage mapResult = client.receive(mapUrl, 100);
... ...and it fails when invokes receive method.
Analyzing the problem In the above scenario, the problem is evident; the Server can't send Attachments over Axis to client application. In other cases, there may be more than one problem. In such cases you should list the problems individually and test for each independently on any other errors. Once the problem is identified you should build a test case in order to test for this problem and build a scenario where the problem is replicable.
Creating a Test Case The FunctionalTestCase available in Mule not only allows you to build JUnit tests but also to define a mule configuration file (which will be used to load Mule), so extending this class for your tests is encouraged. An important factor to keep in mind when creating a test case is the level of detail. It is better to cut down to the basic stuff by removing anything from the configuration that does not directly relate to the problem. For example, in the configuration that the client provided for us above, the security filter and the transformers can be removed. As a test component we can create a class called org.foo.FileOperationsComponent that will implement a method that is very similar to the one provided to us by the user. This method, once called, will create a file, create a datahandler with that file, and send it back to the client. We must also provide an interface for this class since we're using Axis. package org.foo; import import import import import
java.io.File; javax.activation.DataHandler; javax.activation.FileDataSource; org.mule.impl.MuleMessage; org.mule.umo.UMOMessage;
public class FileOperationsComponent implements FileOperationsService { static File repo; public FileOperationsComponent() { // empty constructor } public DataHandler getFile(String fileName) throws Exception { File file = new File("repo"); FileOperationsComponent.repo = file; DataHandler fileData = new DataHandler(new FileDataSource(File.createTempFile(fileName,".txt", file))); UMOMessage message = new MuleMessage(fileData.getName()); message.addAttachment(fileName, fileData); return fileData; }
We build the mule configuration file for this test the same way we would build our mule configuration. Below we configure our OperationsComponent to accept an inbound message over the Axis transport:
Document generated by Confluence on Apr 24, 2008 08:11
Page 66
<\!DOCTYPE mule-configuration PUBLIC "-//MuleSource //DTD mule-configuration XML V1.0//EN" "http:// mule.mulesource.org/dtds/mule-configuration.dtd"> <mule-configuration id= "axis-attachments-config" version= "1.0"> <model name="Attachment_Test"> <mule-descriptor name= "TestComponent" implementation="org.foo.FileOperationsComponent"> <endpoint address="axis:http://localhost:8999"/>
The test case would look something like the following. Please note that the mule-config.xml file as seen above is referenced in the getConfigResources() method in the test case. public class AxisAttachmentsTestCase extends FunctionalTestCase { public void testAxisAttachments() throws Exception { MuleClient muleClient = new MuleClient(); UMOMessage result= muleClient.send("axis:http://localhost:8999/TestComponent?method=getFile",new MuleMessage("TestFile"); assertNotNull(result.getPayload()); assertTrue(result.getAttachmentNames().size() > 0); assertNotNull(result.getAttachment(result.getPayloadAsString())); } String getConfigResources() { return "mule-config.xml" } }
Note that there are three assertions that we are making above. 1. We assert that the payload returned by the message is not null. 2. We assert that attachments are being returned in the MuleMessage from the FileOperationsComponent 3. We assert that the attachment returned is the correct one. In the case of this particular problem, the test case will not meet the second two conditions and will fail thus demonstrating that there is a problem with Attachments being received from the server over Axis in a more clear-cut and concise way.
Document generated by Confluence on Apr 24, 2008 08:11
Page 67
Internationalisation This page last changed on Jan 30, 2008 by ross.
This page describes the i18n as implemented up to Mule 1.4.0. For the new i18n implementation see Internationalisation-1.4.1 Mule supports internationalisation of exception messages, or any other type of string message. Mule has Support for the following Languages• English • Japanese
Using Internationalisation Mule uses the java ResourceBundle class to load messages from properties files on the classpath based on the current systems locale. Mule only has full set of messages in English and Japanese but may have translations in future. Users will need to understand about how MUle loads messages if they want to throw any Mule exception that extends UMOException. This is the base class of all Mule checked exceptions and can only be constructed using internationalised messages. Mule internationalised messages are represented by the org.mule.config.i18n.Message . This object can be constructed with a message id and zero or more message parameters. Mule has a list of core messages that can be found in META-INF/service/org.mule/i18n/core-message.properties. Constants for these messages can be found in the org.mule.config.i18n.Messages class. To create a message for an exception you would do the following UMOException e = new MuleException( new Message(Messages.SOMETHING_FAILED)); throw e;
The argument in the Message constructor refers to a error code constant. You can also pass in message parameters when creating a Message object. these will be used to embed variable information in the message. The message constants defined in org.mule.config.i18n.Messages uses X's to denote how many parameters the message expects. For example UMOException e = new InitialisationException( new Message(Messages.FAILED_TO_INITIALISE_X, "whatever this is")); throw e;
Using custom message bundles When writing Mule extensions or even applications that want to use the Mule internationalisation class, developers can supply custom message bundles containing message specific to their application or extension. To do this developers should create a bundle in the form of 1=Error message one 2=Error message with 2 parameters; param {0} and param {1} ...
where the number is the message id and the actual message comes after. Note that message parameters are specified using '{0}' notation which is standard when using the java MessageFormat class.
Document generated by Confluence on Apr 24, 2008 08:11
Page 68
The file should be named xxx-message.properties where xxx is the identifying name for this bundle. This file should then be located in your jar under META-INF/services/org/mule/i18n/xxx-messages.properties. To load a message from this bundle the developer just needs to pass in the resource bundle name Message m = new Message("xxx", 2, "one", "two"); System.out.println(m.toString());
This loads the message with id 2 from xxx-message.properties, formats the message with 2 parameters "one" and "two" and prints out the message to System.out Error message with 2 parameters; param one and param two
Document generated by Confluence on Apr 24, 2008 08:11
Page 69
Internationalisation-1.4.1 This page last changed on Jan 30, 2008 by ross.
Mule supports internationalisation of exception messages, or any other type of string message. Mule has Support for the following Languages• English • Japanese
Using Internationalisation Mule uses the java ResourceBundle class to load messages from properties files on the classpath based on the current systems locale. Mule only has full set of messages in English and Japanese but may have translations in future. The examples come with more localizations, though. Users will need to understand about how Mule loads messages if they want to throw any Mule exception that extends UMOException. This is the base class of all Mule checked exceptions and can only be constructed using internationalised messages. Mule's internationalised messages are represented by the org.mule.config.i18n.Message class. Instances can be constructed with a message id and zero or more message parameters. Mule has a list of core messages that can be found in META-INF/service/org.mule/i18n/core-message.properties. Constants for these messages can be found in the org.mule.config.i18n.Messages class. You never create instances of Message directly, instead you use subclasses of MessageFactory. Each of Mule's modules and transports has such a messages class. Its name is equal to the module with Messages appended e.g. for the JMS transport you will use JmsMessages to retrieve the messages specific to the JMS transport. The dedicated messages class per module/transport has the following advantages: • • • •
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, this can be done in the module specific messages class
To create a message for an exception you would do the following UMOException e = new MuleException(CoreMessages.failedToGetPooledObject()); throw e;
Using custom message bundles When writing Mule extensions or even applications that want to use the Mule internationalisation class, developers can supply custom message bundles containing message specific to their application or extension. To do this developers should create a bundle in the form of 1=Error message one 2=Error message with 2 parameters; param {0} and param {1} ...
where the number is the message id and the actual message comes after. Note that message parameters are specified using '{0}' notation which is standard when using the java MessageFormat class. The file should be named xxx-messages.properties where xxx is the identifying name for this bundle. This file should then be located in your jar under META-INF/services/org/mule/i18n/xxx-messages.properties but can be placed in any other location on the classpath. In order to access the messages of your own resource bundle, create a subclass of MessageFactory as follows: public class MyMessages extends MessageFactory
Document generated by Confluence on Apr 24, 2008 08:11
Page 70
{ // getBundlePath puts together the correct path (META-INF/services/org/mule/i18n/mymessages.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 the developer just needs to pass in the resource bundle name Message m = MyMessages.anotherErrorMessage("one", "two"); System.out.pritln(m.toString());
This loads the message with id 2 from xxx-message.properties, formats the message with 2 parameters "one" and "two" and prints out the message to System.out 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. transformer) use Message myMessage = MessageFactory.createStaticMessage("Oops");
Document generated by Confluence on Apr 24, 2008 08:11
Page 71
J2EE Application Servers This page last changed on Jan 30, 2008 by ross.
The following pages describe how to deploy Mule to various application servers and how to Configure App server Resources such as Jms to be used with Mule. These pages are works in progress, where new information is added as people submit configurations for their particular app server. If you are using Mule with an AppServer not listed or think that we are missing some important information please contact us with the details. It will be greatly appreciated!
Application Servers • • • • • • •
Geronimo Integration JBoss Integration Oracle Integration MULE:SeeBeyond Integration MULE:Sun One Integration Weblogic Integration WebSphere Integration
Document generated by Confluence on Apr 24, 2008 08:11
Page 72
Geronimo Integration This page last changed on Jan 30, 2008 by ross.
Deploying Mule to Geronimo The following describes how to deploy the Mule JCA Resource Adapter to the Geronimo application server allowing EJBs to send and receive Mule events. TODO
ActiveMQ Configuration Geronimo uses ActiveMq as it's default Jms provider. To configure a default embedded broker. <properties> <property name="specification" value="1.1"/> <property name="connectionFactoryJndiName" value="ConnectionFactory"/> <property name="jndiInitialFactory" value="org.activemq.jndi.ActiveMQInitialContextFactory"/> <map name="connectionFactoryProperties"> <property name="brokerURL" value="vm://localhost"/> <property name="brokerXmlConfig" value="classpath:/org/mule/test/activemq-config.xml"/>
The specification property tells Mule to use the Jms 1.1 specification, which is the specification ActiveMQ supports. To disable queue persistence, you'll need to specify it in ActiveMQ configuration file (see below). You can pass in any provider specific configuration using the connectionFactoryProperties property on the JmsConnector. These will get set on the ConnectionFactory implementation. To configure ActiveMQ on a specific brokerUrl or from an ActiveMQ configuration file use the following (Spring version) mule-config.xml <properties> <property name="configFile" value="classpath:/org/mule/test/activemq-spring.xml"/> <properties> <property name="specification" value="1.1"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 73
Configure ActiveMQ from Spring: activemq-spring.xml <property name="brokerURL" value="vm://localhost"/> <property name="brokerXmlConfig" value="classpath:/org/mule/test/activemq-config.xml"/>
Your ActiveMQ config is a standard one. E.g. to use in-JVM messaging without persistent queues (very useful for testing) the file will be as follows: activemq-config.xml <serverTransport uri="vm://localhost"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 74
JBoss Integration This page last changed on Jan 30, 2008 by ross.
Deploying Mule to JBoss The following describes how to deploy the Mule JCA Resource Adapter JBoss application server allowing EJBs to send and receive Mule events and how to configure Mule to use JBoss MQ.
Building an Ear file for the deployment of the Mule JCA Resource Adapter on JBoss 4.0.5 Although the Mule JCA Resource Adapter could be deployed directly, the best way to deploy Mule on JBoss is for the resource adapter to be placed inside an EAR file. The advantage of deployment using an Ear file over using the Mule JCA Resource Adapter directly are the following: • JBoss allows Ear, War and Sar files to have classloader isolation. This feature is not yet available for the Rar file. • The Mule JCA Resource Adapter contained in the Ear file is specific for JBoss deployment. • The mule-jboss-ds.xml file has to be moved from the mule-module-jca-1.4.0-jboss.jar file up to the ear level which makes it easier to edit. The importance of Classloader Isolation When JBoss comes to classloading, unless classloader isolation is specified, JBoss will first try to use its own classes for deployment and only when these are not found will it look for them in the libraries of the deployment file. Classloading isolation is important since the versions of the libraries used to load Mule are not the same as the ones used by JBoss and so various errors may crop, the most common being ClassCastExceptions. Adaptation of the .rar file for use with the Ear file The mule-jca-1.4.0-jboss.rar file needs a couple of modifications to be able to work inside an isolated Ear file. The following are the libraries that you need to remove: • • • • •
log4j-1.2.14.jar mx4j-jmx-2.1.1.jar xercesImpl-2.8.1.jar xml-apis-1.3.03.jar the mule-jboss-ds.xml needs to be removed from the mule-modules-jca-1.4.0.jar Package Format If you are going to repackage the mule-jca-1.4.0-jboss.rar please note that this should be in a simple zip file format and should not be confused with the RAR packaging. Xerces Parser The xerces and xml-apis jars have to be removed because JBoss has a problem with parsers being in an isolated package and they will conflict with JBoss' own xerces and xml-apis files. Pending a fix for this on the JBoss' side, you'll have to use the JBoss parsers.
The mule-ear-1.4.0.ear File Structure The file structure of the Ear file should have the following format: META-INF | - application.xml | - jboss-app.xml | - MANIFEST.MF mule-jca-1.4.0-jboss.rar
Document generated by Confluence on Apr 24, 2008 08:11
Page 75
mule-jboss-ds.xml
The Ear Configuration Files Below are the configuration files for the XML files shown in the above file structure: mule-jboss-ds.xml
<jndi-name>mule/ConnectionFactory mule-ear-1.4.0.ear#mule-jca-1.4.0-jboss.rar org.mule.ra.MuleConnectionFactory
This mule-jboss-ds.xml file is an adaptation of the one we removed from the mule-modules-jca-1.4.0.jar file. Note that since the rar file is found inside the ear the name inside the tag should be the ear file name and the rar file name separtated by the # symbol. This will be our datasource. application.xml
mule-ear <description>Ear packaging for Mule Resource Adapter <module> mule-jca-1.4.0-jboss.rar
This file is required for us to tell the .ear file to use our mule-jca-1.4.0-jboss.rar as a connector. In this way this can be deployed as resource adapter. jboss-app.xml In the following configuration file, we are creating a loader-repository in which to load our classes during the classloading operation. The java2ParentDelegation property has to be set to false in order to enable classloader isolation. We specify our mule-jboss-ds.xml as a service to be loaded. <jboss-app> org.mule:loader=mule-ear-1.4.0.ear java2ParentDelegaton=false <module> <service>mule-jboss-ds.xml
Deploying the JBoss-specific Ear distribution containing the Mule JCA Resource Adapter: Deployment is the easiest thing. Just drop the EAR file into the JBoss server deployment folder and start up JBoss. JBoss will take care of deploying everything for you.
Document generated by Confluence on Apr 24, 2008 08:11
Page 76
Deploying your Application The resource adapter comes configured with a dummy mule-config.xml file. However, you will want to use your own configuration file. One way to do this is to physically replace the mule-config.xml file in the Mule JCA Resource Adapter (mule-modules-jca-1.4.0.jar) with your own. A more elagant way to do it would be the following: Assuming that you have your pojos bundled in a jar file you can do the following: • put the resource files(xslt, properties, etc.) in your jar file (these should be picked up automatically when mule starts) • create a folder in the root of the mule-jca-1.4.0-jboss.rar file and put your mule configuration in there. For the time being, let's call this folder "conf". • edit the ra.xml file found in mule-jca-1.4.0-jboss.rar META-INF folder and reference your configuration file name as seen below. Configurations java.lang.String conf/my-config1.xml
The should contain a list of configuration files separated by a comma. The "conf/" is the path name telling the loader to look at the conf folder found in the root of the rar file. If only the name of the configuration file is given, the loader will only look for the configuration file inside the mule-module-jca-1.4.0.jar.
JBoss MQ Configuration To configure a JBoss Jms connector for Mule use the following <properties> <property name="jndiInitialFactory" value="org.jnp.interfaces.NamingContextFactory"/> <property name="jndiProviderUrl" value="jnp://localhost/"/> <property name="connectionFactoryJndiName" value="java:/ConnectionFactory"/>
Any provider-specific properties can be passed to the InitialContext for this connector using the jndiProviderProperties attribute. Use connectionFactoryProperties to set JBoss-specific properties on the ConnectionFactory. Connection Credentials If you use user creditials to connect to JBossMQ make sure that the user has the 'guest' role assigned to it. This will ensure that there are no issues if Temporary Topics or Queues (i.e. in RemoteSync calls) are used.
Scenarios for Mule Deployment on JBoss 1. Deploying the User Application in the mule-ear.ear For this scenario the deployment is very simple; the user just needs to add his own jar files to the muleear file. Since everything will be deployed in the mule-ear, then all the classes required by both the user application and mule will be found in the same classloader and be able to communicate. However it may not always be feasible to deploy the application in this way. For example, if mule has to use an existing and deployed component, then Mule should be able to communicate with the application even if the classes are deployed outside the mule-ear.
Document generated by Confluence on Apr 24, 2008 08:11
Page 77
2. Packaging the mule-ear file inside the user ear The user can literally create an ear file containing all his required classes as well as the mule-ear. This will have the same advantages and disadvantages as the previous scenario. However, it helps to keep the user application and the mule-ear more distinct. In addition to this, the mule-ear file requires less modifications. However, there is a small change that needs to be done to the mule-jboss-ds.xml inside the mule-ear. Since we now have another layer that encapsulates our resource adapter, i.e. the user ear, we need to change the connection name of the resource adapter to the following format: user-ear.ear#mule-ear.ear#mule-jca.rar
3. Deploying the User Application in a separate ear file If the application/classes that the user wants to use do not depend on the mule code itself, then deployment for this scenario is also relatively easy. First of all, since mule is in an isolated classloader, the user ear file must share the same classloader. In this way the libraries become accessible to the user application. The second issue is that if the mule configuration file inside the mule-ear.ear file refers to some classes in the user ear, then we have to make sure that the user ear file is loaded before the muleear file. The best way to do this is to enumerate the ear files in the order in which the user wants them to be deployed. For example if the user ear file is called 1-user-ear.ear and the mule ear file is called 2mule-ear.ear, Jboss will load the user ear file first and mule second, ensuring that the user libraries are already loaded in the shared classloader repository for mule to find. For more information about Jboss Deployment Order please read the following: http://wiki.jboss.org/wiki/Wiki.jsp?page=DeploymentOrder
4. Getting around cross-dependencies The situation becomes more complex when the user wants to deploy mule dependant code in a separate ear file (for example the user has a custom transformer that extends mule's AbstractTransformer). In such a case we have a situation of cross dependencies. The user ear depends on the mule libraries to be loaded to be able to load the custom transformer library, while Mule expects the user ear to be loaded to be able to use the transformer class that is found in the user ear. To solve this you can create a shared library (in another ear file perhaps) and make both the mule-ear and the user-ear use the classloader repository of the shared library.
Document generated by Confluence on Apr 24, 2008 08:11
Page 78
Mule as MBean This page last changed on Jan 30, 2008 by ross.
Mule as MBean | Creating a Simple MBean | Creating JBoss Service Descriptor | Deploy MBean to JBoss | References | External References | Related
Mule as MBean An MBean[MULE:1] is a named managed object representing a resource in an JMX environment. We can have an MBean deployed with Mule in it easily, the steps as follows: 1. 2. 3. 4.
Create an MBean (see MULE:#Creating a Simple MBean) Create service descriptor (see MULE:#Creating JBoss Service Descriptor) Deploy MBean (as .sar) to application server (see MULE:#Deploy MBean to JBoss) Copy dependencies to service's classpath
Just as you have not yet noticed, we are using JBoss application server in this document.
Creating a Simple MBean To create an MBean, you will need an interface and an implementation, e.g. package foo.mbean; public public public public }
interface FooServiceMBean { String getBar(); void start(); void stop();
package foo.mbean; import import import import
org.jboss.system.ServiceMBeanSupport; org.mule.config.builders.MuleXmlConfigurationBuilder; org.mule.umo.manager.UMOManager; org.mule.umo.manager.UMOServerNotification;
public class FooService extends ServiceMBeanSupport implements FooServiceMBean{ private UMOManager muleManager = null; public String getBar() { return "bar"; } public void start() { this.getLog().info("MBean being started"); try{ MuleXmlConfigurationBuilder builder = new MuleXmlConfigurationBuilder(); UMOManager manager = builder.configure("mule-config.xml"); manager.start(); manager.registerListener(this); } catch(Exception e){ e.printStackTrace(); } this.getLog().info("MBean started"); } public void stop() { this.getLog().info("MBean being stopped");
Document generated by Confluence on Apr 24, 2008 08:11
Page 79
try { if (muleManager != null) { muleManager.stop(); muleManager.dispose(); // If we can get the muleServer exposed.. :( } this.getLog().info("Done stopping Mule MBean Service!"); } catch (Exception ex) { this.getLog().error("Stopping Mule caused and exception!", ex); } } }
The extension of ServiceMBeanSupport is simply to provide you more control over the API provided by JBoss.
Creating JBoss Service Descriptor A service descriptor has to be located at META-INF/, here is a simple example of it: <server> <mbean code="foo.FooService" name="foo:service=Foo">
Deploy MBean to JBoss So, your distro looks like this (using the examples above): . ./foo ./foo/FooService ./foo/FooServiceMBean ./META-INF ./META-INF/jboss-service.xml
Pack it, either as a JAR (which can then be renamed to a *.sar, and eventually you will need to extract it as JBoss might not be picking it up for whatever reason that I have no idea about) or as a directory called <whatever>.sar. Follow the steps below to complete the deployment: 1. Copy your <whatever>.sar/ directory to JBOSS_HOME/server/default/deploy/ 2. Copy all dependencies of Mule, i.e. MULE_HOME/lib/*/*.jar to the <whatever>.sar/ directory 3. Start JBoss and you'll see the MBean appears in its MBean console, tada :-)
References External References 1. Wikipedia - MBean 2. The Java Tutorials - Standard MBeans
Related Mule as MBean — Deploying Mule into JBoss
Document generated by Confluence on Apr 24, 2008 08:11
Page 80
Joram Integration This page last changed on Jan 30, 2008 by ross.
Using Joram with Mule is a little less straight forward that the other Jms servers if you do not have a Jndi context set up for your connections and destinations. If you have Jndi set up you can use the following <properties> <property name="connectionFactoryJndiName" value="QueueConnectionFactory"/> <property name="specification" value="1.1"/> <property name="jndiDestinations" value="true"/> <property name="connectionFactoryJndiName" value="ConnectionFactory"/> <property name="jndiInitialFactory" value="fr.dyade.aaa.jndi2.client.NamingContextFactory"/> <map name="jndiProviderProperties"> <property name="java.naming.factory.host" value="localhost"/> <property name="java.naming.factory.port" value="16400"/>
Durable Subscribers When using durable subscribers Mule automatically sets the Jms clientId on the connection, if not explicitly set. Joram complains if the clientId is set, so you need to tell Mule not to set it by setting the clientId on the JmsConnector to "". If you do not have Jndi set up you need to manually create a Jndi Initial Context. You can do this by adding a Mule property factory (like the one listed below). Your configuration will look something like <properties> <property name="connectionFactoryJndiName" value="QueueConnectionFactory"/> <property name="specification" value="1.1"/> <property name="jndiDestinations" value="true"/> <list name="jndiQueues"> <entry value="exception.queue"/> <property-factory name="jndiContext" value="com.foo.joram.JoramInitialContextFactory"/>
The Jndi property factory class will look like the following, though you may want to add support for other Joram properties. JoramInitialContextFactory.java public class JoramTest implements PropertyFactory { public Object create(Map properties) throws Exception { String connectionFactoryJndiName = (String) properties.get("connectionFactoryJndiName"); if (connectionFactoryJndiName == null) { throw new InitialisationException( "connectionFactoryJndiName must be set"); } // Connecting to JORAM server: AdminModule.connect("root", "root", 60); //Create anonymous user if security is not required User user = User.create("anonymous", "anonymous"); // Creating the JMS administered objects: javax.jms.ConnectionFactory connFactory = TcpConnectionFactory.create(); // Binding objects in JNDI:
Document generated by Confluence on Apr 24, 2008 08:11
Page 81
//Create Jndi Queues javax.naming.Context jndiCtx = new javax.naming.InitialContext(); jndiCtx.bind(connectionFactoryJndiName, connFactory); List queues = (List)properties.get("jndiQueues"); if(queues!=null) { Queue queue; String name; for (Iterator iterator = queues.iterator(); iterator.hasNext();) { name = (String) iterator.next(); queue = (Queue) Queue.create(0); // Setting free access to the queue: queue.setFreeReading(); queue.setFreeWriting(); jndiCtx.bind(name, queue); } } //Create Jndi Topics List topics = (List)properties.get("jndiTopics"); if(topics!=null) { Topic topic; String name; for (Iterator iterator = topics.iterator(); iterator.hasNext();) { name = (String) iterator.next(); topic = (Topic) Topic.create(0); // Setting free access to the queue: topic.setFreeReading(); topic.setFreeWriting(); jndiCtx.bind(name, topic); } } AdminModule.disconnect(); return jndiCtx; } }
Document generated by Confluence on Apr 24, 2008 08:11
Page 82
Oracle Integration This page last changed on Jan 30, 2008 by ross.
Deploying Mule to Oracle Application Server The following describes how to deploy the Mule JCA Resource Adapter Oracle application server allowing EJBs to send and receive Mule events and how to configure Mule to use Oracle Advanced queuing. TODO. If you are using Mule with Oracle Application Server please contact us with your configuration and any tips to getting Oracle Application Server and Mule working together. Thanks!
Oracle Adnvaced Queuing (AQ) Configuration There are some tricks to getting Oracle AQ working with Mule because the AQ implementation veers from the Jms specification when creating Connection Factories. The big difference is that Oracle uses a dbcentric queue model meaning that really when you create a Connection you are creating a Oracle Jdbc connection. This connector will let Mule talk via the Jms API to a queue in an oracle database without using Jndi. (oracle standard edition disables exporting a queue to a repository). This connector can be used to send a jms message when table data changes. The Oracle JMS Provider extends the standard Mule Jms Provider with functionality specific to Oracle's JMS implementation based on Advanced Queueing (Oracle AQ). The javadoc for this transport provider can be found here. And the Source Xref can be found here. The Oracle JMS Provider adds support for queues with ADT (Advanced Data Type) payloads, including Oracle's native XML data type Unlike the standard JMS Provider, the Oracle JMS Provider does not require a JNDI provider to use. As of Oracle 9i, only the JMS 1.0.2b specification is supported.
Properties In addition to the properties available for the standard Jms Provider, the Oracle JMS Provider adds the following properties:
Property
Description
Default
url
The JDBC URL for the Oracle database, for example jdbc:oracle:oci:@myhost.
Required yes
The user and password may be specified in the URL itself, for example jdbc:oracle:oci:scott/ tiger@myhost, in which case the
Document generated by Confluence on Apr 24, 2008 08:11
Page 83
(standard JMS Provider) properties username and password are not required.
multipleSessionsPerConnection Some versions of Oracle do not support more than one JMS session per connection. In this case we need to open a new connection for each session to avoid the following error: JMS-106: Cannot have more than one open Session on a JMSConnection payloadFactory
false
If the queue's payload is an ADT (Oracle Advanced Data Type), the appropriate payload factory must be specified in the endpoint's properties.
no
no
Transformers In addition to the transformers available for the standard Jms Provider, the Oracle JMS Provider adds the following transformers, found in org.mule.vendor.oracle.jms.transformers.
Transformer
Description
StringToXMLMessage
Expects a string containing properly-formed XML. Creates a JMS message whose payload is Oracle's native XML data type.
XMLMessageToDOM
Expects a JMS message whose payload is Oracle's native XML data type. Returns the XML as a W3C Document (DOM).
XMLMessageToStream
Expects a JMS message whose payload is Oracle's native XML data type. Returns the XML as an InputStream.
XMLMessageToString
Expects a JMS message whose payload is Oracle's native XML data type. Returns the XML as a String.
The default transformers are the same as the standard JMS Provider (JMSMessageToObject and ObjectToJMSMessage).
Document generated by Confluence on Apr 24, 2008 08:11
Page 84
Example Configuration The following is an example configuration using the Oracle JMS Provider: <mule-configuration id="TestConfiguration" version="1.0"> <properties> <property name="url" value="jdbc:oracle:oci:@myhost" /> <property name="username" value="scott" /> <property name="password" value="tiger" /> <endpoint name="XmlQueue" address="oaq://XML_QUEUE" transformers="StringToXMLMessage" /> <model name="Test Model"> <mule-descriptor name="XML-Driven UMO" implementation="com.foo.MyUMO"> <endpoint address="oaq://XML_QUEUE" transformers="XMLMessageToString"> <properties> <property name="payloadFactory" value="oracle.xdb.XMLTypeFactory" />
Endpoints Oracle AQ endpoints are expressed in the same way as Jms endpoints except the protocol is different. oaq://my.queue or oaq://topic:my.topic
You can define an Oracle AQ endpoint without declaring the connector (as shown above), by including all necessary information on the endpoint uri i.e. oaq://XML_QUEUE?url=jdbc:oracle:oci:scott/tiger@myhost
Refer to the unit tests for more examples on how to use the provider.
Dependencies The Oracle JMS Provider requires the following Oracle libraries, which should be included in your Oracle installation:
Document generated by Confluence on Apr 24, 2008 08:11
Page 85
• • • • •
ojdbc14.jar aqapi13.jar jmscommon.jar xdb.jar (only required for native XML support) xmlparserv2.jar (only required for native XML support)
These jars are included in the distribution.
Unit Tests In order to run the unit tests in tests/vendor/oracle against your Oracle database, you will need to create a JMS user "mule" and grant it AQ rights as follows. sqlplus sys/sys@xe as sysdba create user mule identified by mule; grant connect, resource, aq_administrator_role to mule identified by mule; grant execute on sys.dbms_aqadm to mule; grant execute on sys.dbms_aq to mule; grant execute on sys.dbms_aqin to mule; grant execute on sys.dbms_aqjms to mule; exec dbms_aqadm.grant_system_privilege('ENQUEUE_ANY','mule'); exec dbms_aqadm.grant_system_privilege('DEQUEUE_ANY','mule');
The URL (jdbc:oracle:thin:@//127.0.0.1:1521/xe) given in the test config files (tests/vendor/ oracle/src/test/resources) assumes a default local installation of Oracle XE. If this is not the case, you will also need to modify this URL before running the tests.
Document generated by Confluence on Apr 24, 2008 08:11
Page 86
Weblogic Integration This page last changed on Jan 30, 2008 by ross.
Deploying Mule to Weblogic The following describes how to deploy the Mule JCA Resource Adapter to the Weblogic application server allowing EJBs to send and receive Mule events. TODO
Jms Configuration Before using Mule with Weblogic copy the weblogic.jar file to $MULE_HOME/lib/user. JNDI destinations syntax If Mule fails to lookup topics or queues in Weblogic's JNDI, but the JNDI tree lists them as available, try replacing JNDI subcontext delimiters with dots, so tracker/topic/ PriceUpdates becomes tracker.topic.PriceUpdates.
Weblogic 8.x and below <properties> <property name="jndiDestinations" value="true"/> <property name="forceJndiDestinations" value="true"/> <property name="specification" value="1.0.2b"/> <property name="connectionFactoryJndiName" value="javax.jms.QueueConnectionFactory" /> <property name="jndiInitialFactory" value="weblogic.jndi.WLInitialContextFactory"/> <property name="jndiProviderUrl" value="t3://localhost:7001"/>
Weblogic 9.x For Weblogic 9.x the config is almost the same. The only differences are: • Supported JMS specification level is 1.1 (1.0.2b should still work, however) • The unified JMS connection factory can be used as a result of the above. The following example demonstrates using the default factories available out of the box. <properties> <property name="specification" value="1.1"/> <property name="jndiDestinations" value="true"/> <property name="forceJndiDestinations" value="true"/> <property name="connectionFactoryJndiName" value="weblogic.jms.ConnectionFactory"/> <property name="jndiInitialFactory" value="weblogic.jndi.WLInitialContextFactory"/> <property name="jndiProviderUrl" value="t3://localhost:7001"/>
JDK version In case you are getting the following error when connecting to Weblogic 9.x
Document generated by Confluence on Apr 24, 2008 08:11
Page 87
org.mule.MuleServer: A Fatal error has occurred while the server was running: class weblogic.utils.classloaders.GenericClassLoader overrides final method ?.? java.lang.VerifyError: class weblogic.utils.classloaders.GenericClassLoader overrides final method ?.? make sure Mule is started with JDK 5 and above, anything below will not work.
Document generated by Confluence on Apr 24, 2008 08:11
Page 88
WebSphere Integration This page last changed on Jan 30, 2008 by ross.
Document generated by Confluence on Apr 24, 2008 08:11
Page 89
JBI This page last changed on Jan 30, 2008 by ross.
JBI integration Embedding Mule in JBI - You can use Mule transports, transformers and components inside any JBI compliant container. Invoking JBI Components from Mule - Mule has a JBI binding allow you to invoke components form JBI containers allow JBI components to invoke Mule components. Mule JBI Examples - Configuration examples for using Mule in JBI containers.
Mule and JBI After careful consideration of the JBI implementation th Mule team decided that the JBI spec really only covered a sub-set of use-cases that are required when developing an SOA or integration solution. Essentially, the JBI sec if a specification written by vendors for vendors. Mule's whole approach is the exact opposite - it's an SOA/integration platform written for developers by developers. Note that there is a new JBI-2 effort that has recently started. This approach seems to be recognising that POJO services are the right way to go (you saw it here first ) so we think we made the right choice not to adopt JBI. Also, there seems to have been very little uptake of the specification since it was launched in 2005.
Document generated by Confluence on Apr 24, 2008 08:11
Page 90
Embedding Mule in JBI This page last changed on Jan 30, 2008 by ross.
Mule provides a set of JBI components that allow Mule Endpoints (transports), components and transformers to be used in any JBI container.
Endpoints Endpoints are used to send or receive data via a Mule supported transports such as Jms, Jdbc, Http, Soap, Xmpp, Ftp, Ejb, Rmi, Quartz, tcp, udp, and more. There are 2 JBI components for using Mule endpoints: 1. MuleReceiver - will receive data over any Mule transport and deliver them as JBI messages. 2. MuleDispatcher - will send Jbi Normalised Messages over any Mule transport.
MuleReceiver The component has a few properties that must be set. The most obvious one is the endpoint on which it will receive events. This endpoint is a Mule endpoint and is independent of the JBI container being used. The other required property is the name of the target service that this component will foward the event to.
Property
Type
Description
Required
endpoint
java.lang.String
A Mule Endpoint URI on which to receive events
Yes
endpointProperties
java.util.Map
Any properties to set on the endpoint. These are any properties supported by the transport provider being used.
No
muleEndpoint
org.mule.impl.endpoint.MuleEndpoint This allows you to specify a Mule endpoint object instead of an EndpointURI string. This gives you greater flexibility to specify filters, transactions and transformers on the endpoint.
No
targetService
javax.xml.namespace.QName The target service to be invoked after this component
Yes
targetServiceName
java.lang.String
No
workManager
javax.resource.spi.work.WorkManager The manager that will manage threads
Document generated by Confluence on Apr 24, 2008 08:11
A string representation of the 'targetService' QName in the form of [MULE:prefix]: [MULE:localName]: [MULE:namespace]. This can be set instead of the targetService property.
No
Page 91
for this component. You can configure all resource management configuration for Mule using the MuleConfigComponent (see below)
MuleDispatcher Again the most obvious one is the endpoint on which it will dispatch events. This endpoint is a Mule endpoint and is independent of the JBI container being used.
Property
Type
Description
Required
endpoint
java.lang.String
A Mule Endpoint URI on which to dispatch events
Yes
endpointProperties
java.util.Map
Any properties to set on the endpoint. These are any properties supported by the transport provider being used.
No
muleEndpoint
org.mule.impl.endpoint.MuleEndpoint This allows you to specify a Mule endpoint object instead of an EndpointURI string. This gives you greater flexibility to specify filters, transactions and transformers on the endpoint.
No
Components //Todo
Transformers The Mule transformer component allows any Mule transformer to run inside JBI. To configure it you must add an instance of the org.mule.providers.jbi.components.TransformerComponent. This expects to have a Mule transformer instance set on it that will be invoked when the component receives the message. The way in which the transformer is set varies from the Jbi container you are using. See Mule JBI Examples for details.
Document generated by Confluence on Apr 24, 2008 08:11
Page 92
Invoking JBI Components from Mule This page last changed on Jan 30, 2008 by ross.
Document generated by Confluence on Apr 24, 2008 08:11
Page 93
Mule JBI Examples This page last changed on Jan 30, 2008 by ross.
The following are examples of how to use Mule inside any JBI container. They provide configuration examples for each of the open source JBI containers.
File Binding This reads a file from one directory 'inbox' and writes it to an 'outbox' directory. The example shows how it can be configured in Mule-JBI, ServiceMix and Celtix.
Mule JBI <jbi-container id="mule" xmlns:foo="http://www.mulejbi.org/foo/"> <mule-component name="foo:fileReceiver" className="org.mule.providers.jbi.components.MuleReceiver"> <endpoint address="file://./inbox?pollingFrequency=1000"/> <endpoint address="container://foo:fileSender"/> <mule-component name="foo:fileSender" className="org.mule.providers.jbi.components.MuleDispatcher"> <endpoint address="container://foo:fileSender"/> <endpoint address="file://./outbox?outputPattern=$[MULE:ORIGINALNAME]"/>
ServiceMix <property name="useMBeanServer" value="true"/> <property name="createMBeanServer" value="true"/> <property name="dumpStats" value="true"/> <property name="statsInterval" value="10"/> <property name="workManager" ref="workManager"/> <property name="endpoint" value="file://./inbox?pollingFrequency=1000"/> <property name="targetServiceName" value="fileSender"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 94
<property name="endpoint" value="file://./outbox?outputPattern=$[MULE:ORIGINALNAME]"/> <property name="threadPoolSize" value="30"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 95
JMS This page last changed on Apr 18, 2008 by tcarlson.
Configuring Jms - A guide for configuring various JMS servers with Mule. These include ActiveMQ JBoss MQ, Joram OpenJms, Oracle AQ, SeeBeyond, Sun JMS Grid, UberMQ, Weblogic Jms and IBM WebSphere MQ. Jms Provider - How to configure the Mule Jms transport. Transaction Management - Managing Jms Local and distributed (XA) transactions.
Examples Using Jms Redelivery - How to configure Jms Redelivery in Mule. Configuring Multiple Jms Clients - How to configure more than one Jms Connection in a single Mule instance. Configuring a Component Exception Queue - configuring a Jms error queue for your components. Jms Provider Bridging - Moving jms messages between Jms servers from different vendors. Spring Events - An example of how to Have you Spring Beans use Mule transports without configuring the Mule Server. The example demonstates using JMS, Axis web services and Email.
Document generated by Confluence on Apr 24, 2008 08:11
Page 96
Configuring Jms This page last changed on Feb 15, 2008 by ross.
This page descibes the specifics for setting up various Jms Servers in Mule. For more information about all Mule Jms configuration go here. The following Jms server configurations are described • • • • • • • • • • • • • •
ActiveMQ JBoss MQ Joram OpenJms Oracle AQ SeeBeyond SonicMQ Sun JMS Grid Tibco EMS UberMQ Weblogic Jms IBM WebSphere MQ SwiftMQ FioranoMQ
If you have configuration for a Jms server not listed here or there is a mistake on this page please raise a JIRA to get the document updated. Thanks. JMS Endpoint URIs and JNDI destinations Some JNDI implementations treat dot (.) and forward slash symbols differently in destination names, so jms://order/incoming may not be the same as jms://order.incoming, but the former will not give you the order/incoming destination, but incoming. If you are dealing with such a server (JBoss is known to behave this way), here is a trick to help you:
jms:////order/incoming For topics, add the standard prefix, so it takes the following form:
jms:////topic:order/incoming Note: If using JBoss, remember to omit the queue/ and topic/ from the full JNDI name. See Mule Endpoint URIs for reference. and JmsEndpointTestCase for some more examples. The following are just examples and configuration values will change depending on your application environment.
ActiveMQ To configure a default embedded broker. <properties> <property name="specification" value="1.1"/> <property name="connectionFactoryJndiName" value="ConnectionFactory"/> <property name="jndiInitialFactory" value="org.activemq.jndi.ActiveMQInitialContextFactory"/> <map name="connectionFactoryProperties"> <property name="brokerURL" value="vm://localhost"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 97
<property name="brokerXmlConfig" value="classpath:/org/mule/test/activemq-config.xml"/>
The specification property tells Mule to use the Jms 1.1 specification, which is the specification ActiveMQ supports. To disable queue persistence, you'll need to specify it in ActiveMQ configuration file (see below). You can pass in any provider specific configuration using the connectionFactoryProperties property on the JmsConnector. These will get set on the ConnectionFactory implementation. To configure ActiveMQ on a specific brokerUrl or from an ActiveMQ configuration file use the following (Spring version) mule-config.xml <properties> <property name="configFile" value="classpath:/org/mule/test/activemq-spring.xml"/> <properties> <property name="specification" value="1.1"/>
Configure ActiveMQ from Spring: activemq-spring.xml <property name="brokerURL" value="vm://localhost"/> <property name="brokerXmlConfig" value="classpath:/org/mule/test/activemq-config.xml"/>
Your ActiveMQ config is a standard one. E.g. to use in-JVM messaging without persistent queues (very useful for testing) the file will be as follows: activemq-config.xml
Document generated by Confluence on Apr 24, 2008 08:11
Page 98
<serverTransport uri="vm://localhost"/>
JBoss MQ To configure a JBoss Jms connector for Mule use the following <properties> <property name="jndiInitialFactory" value="org.jnp.interfaces.NamingContextFactory"/> <property name="jndiProviderUrl" value="jnp://localhost/"/> <property name="connectionFactoryJndiName" value="java:/ConnectionFactory"/>
Any provider-specific properties can be passed to the InitialContext for this connector using the jndiProviderProperties attribute. Use connectionFactoryProperties to set JBoss-specific properties on the ConnectionFactory. Connection Credentials If you use user creditials to connect to JBossMQ make sure that the user has the 'guest' role assigned to it. This will ensure that there are no issues if Temporary Topics or Queues (i.e. in RemoteSync calls) are used.
OpenJms The following example configuration describes how to configure a MUle JmsConnector for OpenJms. You will probably need to change the connectionFactoryJndiName to one that is configured from your OpenJms configuration. <properties> <property name="connectionFactoryJndiName" value="QueueConnectionFactory"/> <property name="jndiInitialFactory" value="org.exolab.jms.jndi.InitialContextFactory"/> <property name="jndiProviderUrl" value="tcp://localhost:3035"/>
UberMQ Todo. If you are using Mule with Uber MQ please contact us with your configuration and any tips to getting Uber MQ and Mule working together. Thanks!
WebLogic Jms Before using Mule with Weblogic copy the weblogic.jar file to $MULE_HOME/lib/user.
Document generated by Confluence on Apr 24, 2008 08:11
Page 99
JNDI destinations syntax If Mule fails to lookup topics or queues in Weblogic's JNDI, but the JNDI tree lists them as available, try replacing JNDI subcontext delimiters with dots, so tracker/topic/ PriceUpdates becomes tracker.topic.PriceUpdates.
Weblogic 8.x and below <properties> <property name="jndiDestinations" value="true"/> <property name="forceJndiDestinations" value="true"/> <property name="specification" value="1.0.2b"/> <property name="connectionFactoryJndiName" value="javax.jms.QueueConnectionFactory" /> <property name="jndiInitialFactory" value="weblogic.jndi.WLInitialContextFactory"/> <property name="jndiProviderUrl" value="t3://localhost:7001"/>
Weblogic 9.x For Weblogic 9.x the config is almost the same. The only differences are: • Supported JMS specification level is 1.1 (1.0.2b should still work, however) • The unified JMS connection factory can be used as a result of the above. The following example demonstrates using the default factories available out of the box. <properties> <property name="specification" value="1.1"/> <property name="jndiDestinations" value="true"/> <property name="forceJndiDestinations" value="true"/> <property name="connectionFactoryJndiName" value="weblogic.jms.ConnectionFactory"/> <property name="jndiInitialFactory" value="weblogic.jndi.WLInitialContextFactory"/> <property name="jndiProviderUrl" value="t3://localhost:7001"/>
JDK version In case you are getting the following error when connecting to Weblogic 9.x
org.mule.MuleServer: A Fatal error has occurred while the server was running: class weblogic.utils.classloaders.GenericClassLoader overrides final method ?.? java.lang.VerifyError: class weblogic.utils.classloaders.GenericClassLoader overrides final method ?.? make sure Mule is started with JDK 5 and above, anything below will not work.
Oracle Advanced Queuing (AQ) There are some tricks to getting Oracle AQ working with Mule because the AQ implementation veers from the Jms specification when creating Connection Factories. The big difference is that Oracle uses a dbcentric queue model meaning that really when you create a Connection you are creating a Oracle Jdbc
Document generated by Confluence on Apr 24, 2008 08:11
Page 100
connection. This connector will let Mule talk via the Jms API to a queue in an oracle database without using Jndi. (oracle standard edition disables exporting a queue to a repository). This connector can be used to send a jms message when table data changes. The Oracle JMS Provider extends the standard Mule Jms Provider with functionality specific to Oracle's JMS implementation based on Advanced Queueing (Oracle AQ). The javadoc for this transport provider can be found here. And the Source Xref can be found here. The Oracle JMS Provider adds support for queues with ADT (Advanced Data Type) payloads, including Oracle's native XML data type Unlike the standard JMS Provider, the Oracle JMS Provider does not require a JNDI provider to use. As of Oracle 9i, only the JMS 1.0.2b specification is supported.
Properties In addition to the properties available for the standard Jms Provider, the Oracle JMS Provider adds the following properties:
Property
Description
Default
url
The JDBC URL for the Oracle database, for example jdbc:oracle:oci:@myhost.
Required yes
The user and password may be specified in the URL itself, for example jdbc:oracle:oci:scott/ tiger@myhost, in which case the (standard JMS Provider) properties username and password are not required.
multipleSessionsPerConnection Some versions of Oracle do not support more than one JMS session per connection. In this case we need to open a new connection
Document generated by Confluence on Apr 24, 2008 08:11
false
no
Page 101
for each session to avoid the following error: JMS-106: Cannot have more than one open Session on a JMSConnection payloadFactory
If the queue's payload is an ADT (Oracle Advanced Data Type), the appropriate payload factory must be specified in the endpoint's properties.
no
Transformers In addition to the transformers available for the standard Jms Provider, the Oracle JMS Provider adds the following transformers, found in org.mule.vendor.oracle.jms.transformers.
Transformer
Description
StringToXMLMessage
Expects a string containing properly-formed XML. Creates a JMS message whose payload is Oracle's native XML data type.
XMLMessageToDOM
Expects a JMS message whose payload is Oracle's native XML data type. Returns the XML as a W3C Document (DOM).
XMLMessageToStream
Expects a JMS message whose payload is Oracle's native XML data type. Returns the XML as an InputStream.
XMLMessageToString
Expects a JMS message whose payload is Oracle's native XML data type. Returns the XML as a String.
The default transformers are the same as the standard JMS Provider (JMSMessageToObject and ObjectToJMSMessage).
Example Configuration The following is an example configuration using the Oracle JMS Provider: <mule-configuration id="TestConfiguration" version="1.0"> <properties> <property name="url" value="jdbc:oracle:oci:@myhost" /> <property name="username" value="scott" /> <property name="password" value="tiger" />
Document generated by Confluence on Apr 24, 2008 08:11
Page 102
<endpoint name="XmlQueue" address="oaq://XML_QUEUE" transformers="StringToXMLMessage" /> <model name="Test Model"> <mule-descriptor name="XML-Driven UMO" implementation="com.foo.MyUMO"> <endpoint address="oaq://XML_QUEUE" transformers="XMLMessageToString"> <properties> <property name="payloadFactory" value="oracle.xdb.XMLTypeFactory" />
Endpoints Oracle AQ endpoints are expressed in the same way as Jms endpoints except the protocol is different. oaq://my.queue or oaq://topic:my.topic
You can define an Oracle AQ endpoint without declaring the connector (as shown above), by including all necessary information on the endpoint uri i.e. oaq://XML_QUEUE?url=jdbc:oracle:oci:scott/tiger@myhost
Refer to the unit tests for more examples on how to use the provider.
Dependencies The Oracle JMS Provider requires the following Oracle libraries, which should be included in your Oracle installation: • • • • •
ojdbc14.jar aqapi13.jar jmscommon.jar xdb.jar (only required for native XML support) xmlparserv2.jar (only required for native XML support)
These jars are included in the distribution.
Unit Tests In order to run the unit tests in tests/vendor/oracle against your Oracle database, you will need to create a JMS user "mule" and grant it AQ rights as follows. sqlplus sys/sys@xe as sysdba create user mule identified by mule; grant connect, resource, aq_administrator_role to mule identified by mule; grant execute on sys.dbms_aqadm to mule;
Document generated by Confluence on Apr 24, 2008 08:11
Page 103
grant execute on sys.dbms_aq to mule; grant execute on sys.dbms_aqin to mule; grant execute on sys.dbms_aqjms to mule; exec dbms_aqadm.grant_system_privilege('ENQUEUE_ANY','mule'); exec dbms_aqadm.grant_system_privilege('DEQUEUE_ANY','mule');
The URL (jdbc:oracle:thin:@//127.0.0.1:1521/xe) given in the test config files (tests/vendor/ oracle/src/test/resources) assumes a default local installation of Oracle XE. If this is not the case, you will also need to modify this URL before running the tests.
SonicMQ Configuration tested with versions 6.1 and 7.0. <properties> <property name="specification" value="1.1"/> <property name="connectionFactoryJndiName" value="sonic-cf"/> <property name="jndiInitialFactory" value="com.sonicsw.jndi.mfcontext.MFContextFactory"/> <property name="jndiProviderUrl" value="tcp://localhost:2506"/> <map name="connectionFactoryProperties"> <property name="clientID" value="clientIDString"/> <property name="connectID" value="connectIDString"/> <property name="connectionURLs" value="somURLStrings here"/> <property name="defaultUser" value="userString"/> <property name="defaultPassword" value="passwordString"/> <property name="prefetchCount" value="10"/> <property name="prefetchThreshold" value="10"/> <property name="faultTolerant" value="true"/> <property name="persistentDelivery" value="true"/> <property name="loadBalancing" value="true"/> <property name="sequential" value="false"/>
<map name="jndiProviderProperties"> <property name="com.sonicsw.jndi.mfcontext.domain" value="Domain1"/> <property name="java.naming.security.principal" value="Administrator"/> <property name="java.naming.security.credentials" value="Administrator"/> <property name="com.sonicsw.jndi.mfcontext.idleTimeout" value="5000"/>
<property name="username" value="Administrator"/> <property name="password" value="Administrator"/>
Thanks to Knut Lerpold for contributing this configuration.
SeeBeyond The configuration provided is for the SeeBeyond ICAN IQManager JMS Server. Note the values in [ ] (square brackets), these should be replaced by values relevant to your installation. <properties>
Document generated by Confluence on Apr 24, 2008 08:11
Page 104
<property name="jndiInitialFactory" value="com.stc.is.naming.NamingContextFactory"/> <property name="jndiProviderUrl" value="[MULE:ServerName]:18006"/> <property name="connectionFactoryJndiName" value="/jms/connectionfactory/queue/[MULE:LogicalHostName]_[MULE:JMS iqManager Name]" />
For a topic, the connectionFactoryJndiName would be /jms/connectionfactory/topic/ [MULE:LogicalHostName]_[MULE:JMS iqManager Name]. You will need the following jars and files from the Java ApiKit on your classpath: • • • • • • •
com.stc.jmsis.jar fscontext.jar providerutil.jar jms.jar jta.jar log4j.jar log4j.properties
Thanks to Brian Kalbfus for contributing this configuration.
IBM WebSphere MQ To configure a WebSphere MQ Jms connector for Mule you will need to do the following 1. Set up a Connection Factory in the WAS admin console 2. Confiure a Jms Connector in Mule to use the Connection Factory.
Set up the Connection Factory Under WAS Admin Console > Resources > WebSphere MQ JMS Provider > WebSphere MQ Queue Connection Factories Set the following properties • • • •
Name: Connection Factory JNDI Name: jms/ConnectionFactory Queue Manager: (Your QMGR Here) Host, Port, etc.
Mule Configuration Add the following connector configuration <properties> <property name="specification" value="1.1"/> <property name="hostName" value="myMQServer"/> <property name="transportType" value="1"/> <property name="name" value="myMQConnector"/> <property name="jndiInitialFactory" value="com.ibm.websphere.naming.WsnInitialContextFactory"/> <property name="connectionFactoryJndiName" value="jms/ConnectionFactory"/>
The hostName property is mandatory and refers to a name that will be used for this connection. This is different to the host property which refers to an IP address or network name of the server hosting WebSphere MQ. Apart from the name attribute for the connector, WebSphere mandates a name property.
Document generated by Confluence on Apr 24, 2008 08:11
Page 105
If you're using IBM's connection factory, you may additionally need the following configuration - the connection factory is configured in Spring here: <properties> <property name="name" value="ThisConnector"/> <property name="hostname" value="MyHost"/> <property name="hostName" value="MyHost"/> <property name="port" value="6969"/> <property name="channel" value="S_machine"/> <property name="queueManager"> QM_machine <property name="transportType">1 <property name="specification"> 1.1
Note that WebSphere MQ v5.3 requires at least Fix Pack 6 (CSD06) applied for JMS 1.1 support. Earlier levels must set the specification property to 1.0.2b. The latest WebSphere MQ Fix Packs can be downloaded here: http://www-1.ibm.com/support/ docview.wss?uid=swg27006037 You will also need the following IBM Websphere jars on your classpath: • • • •
com.ibm.mq.jar com.ibm.mqjms.jar connector.jar dhbcore.jar If you are using WAS, refer to this discussion for some known limitations.
Sun JMS Grid The following demonstrates how to configure Mule to use the Sun JMS Grid server. <properties> <property name="specification" value="1.1"/> <property name="connectionFactoryJndiName" value="QueueConnectionFactory"/> <property name="jndiInitialFactory" value="com.spirit.directory.SpiritVMDirectoryContextFactory"/> <map name="jndiProviderProperties"> <property name="driverName" value="WMSEmbedded"/>
Tibco EMS The following demonstrates how to configure Mule to use the Tibco Enterprise Message Server (EMS) with authentication in place. <properties> <property name="jndiProviderUrl" value="tibjmsnaming://:port"/> <property name="connectionFactoryJndiName" value="QueueConnectionFactory"/> <map name="jndiProviderProperties"> <property name="java.naming.factory.initial" value="com.tibco.tibjms.naming.TibjmsInitialContextFactory"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 106
<property name="java.naming.security.principal" value="<username>"/> <property name="java.naming.security.credentials"value="<password>/> <property name="username" value="<username>"/> <property name="password" value="<password>"/>
For XA Transactions you will have to create an XA Connection Factory from TIBCO administration-tool (tibemsadmin) in the following way: > create factory XAQueueConnectionFactory xaqueue url=tcp://7222
Joram Jms Using Joram with Mule is a little less straight forward that the other Jms servers if you do not have a Jndi context set up for your connections and destinations. If you have Jndi set up you can use the following <properties> <property name="connectionFactoryJndiName" value="QueueConnectionFactory"/> <property name="specification" value="1.1"/> <property name="jndiDestinations" value="true"/> <property name="connectionFactoryJndiName" value="ConnectionFactory"/> <property name="jndiInitialFactory" value="fr.dyade.aaa.jndi2.client.NamingContextFactory"/> <map name="jndiProviderProperties"> <property name="java.naming.factory.host" value="localhost"/> <property name="java.naming.factory.port" value="16400"/>
Durable Subscribers When using durable subscribers Mule automatically sets the Jms clientId on the connection, if not explicitly set. Joram complains if the clientId is set, so you need to tell Mule not to set it by setting the clientId on the JmsConnector to "". If you do not have Jndi set up you need to manually create a Jndi Initial Context. You can do this by adding a Mule property factory (like the one listed below). Your configuration will look something like <properties> <property name="connectionFactoryJndiName" value="QueueConnectionFactory"/> <property name="specification" value="1.1"/> <property name="jndiDestinations" value="true"/> <list name="jndiQueues"> <entry value="exception.queue"/> <property-factory name="jndiContext" value="com.foo.joram.JoramInitialContextFactory"/>
The Jndi property factory class will look like the following, though you may want to add support for other Joram properties. JoramInitialContextFactory.java public class JoramTest implements PropertyFactory {
Document generated by Confluence on Apr 24, 2008 08:11
Page 107
public Object create(Map properties) throws Exception { String connectionFactoryJndiName = (String) properties.get("connectionFactoryJndiName"); if (connectionFactoryJndiName == null) { throw new InitialisationException( "connectionFactoryJndiName must be set"); } // Connecting to JORAM server: AdminModule.connect("root", "root", 60); //Create anonymous user if security is not required User user = User.create("anonymous", "anonymous"); // Creating the JMS administered objects: javax.jms.ConnectionFactory connFactory = TcpConnectionFactory.create(); // Binding objects in JNDI: //Create Jndi Queues javax.naming.Context jndiCtx = new javax.naming.InitialContext(); jndiCtx.bind(connectionFactoryJndiName, connFactory); List queues = (List)properties.get("jndiQueues"); if(queues!=null) { Queue queue; String name; for (Iterator iterator = queues.iterator(); iterator.hasNext();) { name = (String) iterator.next(); queue = (Queue) Queue.create(0); // Setting free access to the queue: queue.setFreeReading(); queue.setFreeWriting(); jndiCtx.bind(name, queue); } } //Create Jndi Topics List topics = (List)properties.get("jndiTopics"); if(topics!=null) { Topic topic; String name; for (Iterator iterator = topics.iterator(); iterator.hasNext();) { name = (String) iterator.next(); topic = (Topic) Topic.create(0); // Setting free access to the queue: topic.setFreeReading(); topic.setFreeWriting(); jndiCtx.bind(name, topic); } } AdminModule.disconnect(); return jndiCtx; } }
FioranoMQ
JMS Connector Configuration for FioranoMQ 2007 FioranoMQ is a High Performance Enterprise Communication Backbone.
Document generated by Confluence on Apr 24, 2008 08:11
Page 108
Many thanks to Ed Narayanan for submitting the following configuration info. for Mule! <properties> <property name="connectionFactoryJndiName" value="PrimaryCF"/> <property name="jndiInitialFactory" value="fiorano.jms.runtime.naming.FioranoInitialContextFactory"/> <property name="specification" value="1.1"/> <property name="jndiProviderUrl" value="http://localhost:1856"/> <property name="username" value="anonymous"/> <property name="password" value="anonymous"/> <-- A few optional values for the factory --> <map name="connectionFactoryProperties"> <property name="clientID" value="sampleClientID"/> <property name="ConnectURL" value="http://localhost:1856"/> <property name="BackupConnectURLs" value="http://localhost:1956"/>
You will need the following jars on your classpath: • FioranoMQ2007/fmq/lib/client/all/fmq-client.jar • FioranoMQ2007/framework/lib/all/fiorano-framework.jar
Sample Usage The following steps illustrate modifying the "Echo" sample shipped with Mule. Instead of using System.out in the outbound router, we will write the output onto a Topic in FioranoMQ using the above configuration. Modify the outbound router in the echo-config.xml under examples\echo\conf to use a Topic: <endpoint address="jms://topic:muleTopic"/>
Start the durable connection sample available in FioranoMQ from a command prompt in fmq/samples/ PubSub/DurableSubscribers as shown below: runClient DurableSubscriber -clientid sampleClientID -topicName muleTopic
Now on starting Mule with the above echo-config.xml file we can push messages onto the topic and consequently to the subscriber. The durable connection property can also be tested by killing the subscriber, pumping in more messages and then again starting the subscriber.
Document generated by Confluence on Apr 24, 2008 08:11
Page 109
ActiveMQ Integration This page last changed on Jan 30, 2008 by ross.
To configure a default embedded broker. <properties> <property name="specification" value="1.1"/> <property name="connectionFactoryJndiName" value="ConnectionFactory"/> <property name="jndiInitialFactory" value="org.activemq.jndi.ActiveMQInitialContextFactory"/> <map name="connectionFactoryProperties"> <property name="brokerURL" value="vm://localhost"/> <property name="brokerXmlConfig" value="classpath:/org/mule/test/activemq-config.xml"/>
The specification property tells Mule to use the Jms 1.1 specification, which is the specification ActiveMQ supports. To disable queue persistence, you'll need to specify it in ActiveMQ configuration file (see below). You can pass in any provider specific configuration using the connectionFactoryProperties property on the JmsConnector. These will get set on the ConnectionFactory implementation. To configure ActiveMQ on a specific brokerUrl or from an ActiveMQ configuration file use the following (Spring version) mule-config.xml <properties> <property name="configFile" value="classpath:/org/mule/test/activemq-spring.xml"/> <properties> <property name="specification" value="1.1"/>
Configure ActiveMQ from Spring: activemq-spring.xml <property name="brokerURL" value="vm://localhost"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 110
<property name="brokerXmlConfig" value="classpath:/org/mule/test/activemq-config.xml"/>
Your ActiveMQ config is a standard one. E.g. to use in-JVM messaging without persistent queues (very useful for testing) the file will be as follows: activemq-config.xml <serverTransport uri="vm://localhost"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 111
Fiorano Integration This page last changed on Jan 30, 2008 by ross.
JMS Connector Configuration for FioranoMQ 2007 FioranoMQ is a High Performance Enterprise Communication Backbone. Many thanks to Ed Narayanan for submitting the following configuration info. for Mule! <properties> <property name="connectionFactoryJndiName" value="PrimaryCF"/> <property name="jndiInitialFactory" value="fiorano.jms.runtime.naming.FioranoInitialContextFactory"/> <property name="specification" value="1.1"/> <property name="jndiProviderUrl" value="http://localhost:1856"/> <property name="username" value="anonymous"/> <property name="password" value="anonymous"/> <-- A few optional values for the factory --> <map name="connectionFactoryProperties"> <property name="clientID" value="sampleClientID"/> <property name="ConnectURL" value="http://localhost:1856"/> <property name="BackupConnectURLs" value="http://localhost:1956"/>
You will need the following jars on your classpath: • FioranoMQ2007/fmq/lib/client/all/fmq-client.jar • FioranoMQ2007/framework/lib/all/fiorano-framework.jar
Sample Usage The following steps illustrate modifying the "Echo" sample shipped with Mule. Instead of using System.out in the outbound router, we will write the output onto a Topic in FioranoMQ using the above configuration. Modify the outbound router in the echo-config.xml under examples\echo\conf to use a Topic: <endpoint address="jms://topic:muleTopic"/>
Start the durable connection sample available in FioranoMQ from a command prompt in fmq/samples/ PubSub/DurableSubscribers as shown below: runClient DurableSubscriber -clientid sampleClientID -topicName muleTopic
Now on starting Mule with the above echo-config.xml file we can push messages onto the topic and consequently to the subscriber. The durable connection property can also be tested by killing the subscriber, pumping in more messages and then again starting the subscriber.
Document generated by Confluence on Apr 24, 2008 08:11
Page 112
Integrating SwiftMQ with Mule This page last changed on Jan 30, 2008 by ross.
Integrate SwiftMQ with Mule 1.3 Configuring a Mule JMS Connector To integrate SwiftMQ it is recommended to integrate it via JNDI, thus, the following attributes have to be specified:
Attribute
Description
Recommended Value
jndiInitialFactory
InitialContext factory
com.swiftmq.jndi.InitialContextFactoryImpl
jndiProviderUrl
JNDI Provider URL
smqp://localhost:4001/ timeout=10000
jndiDestinations
JNDI lookup of queues/topics
true
forceJndiDestinations
Forces a JNDI exception if a destination was not found in JNDI
true
specification
Version of the JMS specification
1.1
connectionFactoryJndiName
Name of the JMS connection factory to use
ConnectionFactory
Example: <properties> <property name="connectionFactoryJndiName" value="ConnectionFactory"/> <property name="jndiInitialFactory" value="com.swiftmq.jndi.InitialContextFactoryImpl"/> <property name="jndiProviderUrl" value="smqp://localhost:4001/timeout=10000"/> <property name="jndiDestinations" value="true"/> <property name="forceJndiDestinations" value="true"/> <property name="specification" value="1.1"/>
Copy swiftmq.jar into Mule's "lib/user" directory and start the SwiftMQ Router. Now you can use SwiftMQ from Mule.
Configuring Mule's LoanBroker ESB Example with SwiftMQ The description of the LoanBroker ESB example can be found in the Mule documentation. The only change necessary in both example configuration files loan-broker-esb-mule-config.xml and loanbroker-esb-mule-config-container.xml is the JMS connector. With a SwiftMQ Router running on the local host it is: <properties> <property name="connectionFactoryJndiName" value="ConnectionFactory"/> <property name="jndiInitialFactory" value="com.swiftmq.jndi.InitialContextFactoryImpl"/> <property name="jndiProviderUrl" value="smqp://localhost:4001/timeout=10000"/> <property name="jndiDestinations" value="true"/> <property name="forceJndiDestinations" value="true"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 113
<property name="specification" value="1.1"/>
The LoanBroker ESB example uses the following JMS queues (Mule syntax):
jms://esb.loan.quotes jms://esb.credit.agency jms://esb.lender.service jms://esb.banks SwiftMQ does not allow dots '.' in queue names. Instead we use underscores '_' in SwiftMQ's routerconfig.xml: <swiftlet name="sys$queuemanager">
To match with the LoanBroker ESB example's JMS queue names, we define JNDI aliases in SwiftMQ's routerconfig.xml <swiftlet name="sys$jndi"> <jndi-replications/>
That's it! The LoanBroker ESB example must be rebuild with Ant or Maven in order that the configuration changes take effect. Then start the SwiftMQ Router and the LoanBroker ESB example. The @ sign can be escaped with the %40 in Mule URI so for an alternate configuration you can use the following: <endpoint-identifiers> <endpoint-identifier name="LoanBrokerRequestsREST" value="jetty:rest://localhost:8080/loanbroker"/> <endpoint-identifier name="LoanBrokerRequests" value="vm://loan.broker.requests"/> <endpoint-identifier name="LoanQuotes" value="jms://esb_loan_quotes%40router1"/> <endpoint-identifier name="CreditAgencyGateway" value="jms://esb_credit_agency%40router1"/> <endpoint-identifier name="CreditAgency" value="ejb://localhost:1099/local/CreditAgency? method=getCreditProfile"/> <endpoint-identifier name="LenderGateway" value="jms://esb_lender_service%40router1"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 114
<endpoint-identifier name="LenderService" value="vm://lender.service"/> <endpoint-identifier name="BankingGateway" value="jms://esb_banks%40router1"/> <endpoint-identifier name="Bank1" value="axis:http://localhost:10080/mule"/> <endpoint-identifier name="Bank2" value="axis:http://localhost:20080/mule"/> <endpoint-identifier name="Bank3" value="axis:http://localhost:30080/mule"/> <endpoint-identifier name="Bank4" value="axis:http://localhost:40080/mule"/> <endpoint-identifier name="Bank5" value="axis:http://localhost:50080/mule"/>
Keep in mind that a SwiftMQ JNDI alias also decouples a queue from its physical location. You can move a queue to another router without affecting clients. So it's always recommended to avoid physical queue names.
Document generated by Confluence on Apr 24, 2008 08:11
Page 115
JBoss Jms Integration This page last changed on Jan 30, 2008 by ross.
To configure a JBoss Jms connector for Mule use the following <properties> <property name="jndiInitialFactory" value="org.jnp.interfaces.NamingContextFactory"/> <property name="jndiProviderUrl" value="jnp://localhost/"/> <property name="connectionFactoryJndiName" value="java:/ConnectionFactory"/>
Any provider-specific properties can be passed to the InitialContext for this connector using the jndiProviderProperties attribute. Use connectionFactoryProperties to set JBoss-specific properties on the ConnectionFactory. Connection Credentials If you use user creditials to connect to JBossMQ make sure that the user has the 'guest' role assigned to it. This will ensure that there are no issues if Temporary Topics or Queues (i.e. in RemoteSync calls) are used.
Document generated by Confluence on Apr 24, 2008 08:11
Page 116
OpenJms Integration This page last changed on Jan 30, 2008 by ross.
The following example configuration describes how to configure a MUle JmsConnector for OpenJms. You will probably need to change the connectionFactoryJndiName to one that is configured from your OpenJms configuration. <properties> <property name="connectionFactoryJndiName" value="QueueConnectionFactory"/> <property name="jndiInitialFactory" value="org.exolab.jms.jndi.InitialContextFactory"/> <property name="jndiProviderUrl" value="tcp://localhost:3035"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 117
Oracle AQ Integration This page last changed on Jan 30, 2008 by ross.
There are some tricks to getting Oracle AQ working with Mule because the AQ implementation veers from the Jms specification when creating Connection Factories. The big difference is that Oracle uses a dbcentric queue model meaning that really when you create a Connection you are creating a Oracle Jdbc connection. This connector will let Mule talk via the Jms API to a queue in an oracle database without using Jndi. (oracle standard edition disables exporting a queue to a repository). This connector can be used to send a jms message when table data changes. The Oracle JMS Provider extends the standard Mule Jms Provider with functionality specific to Oracle's JMS implementation based on Advanced Queueing (Oracle AQ). The javadoc for this transport provider can be found here. And the Source Xref can be found here. The Oracle JMS Provider adds support for queues with ADT (Advanced Data Type) payloads, including Oracle's native XML data type Unlike the standard JMS Provider, the Oracle JMS Provider does not require a JNDI provider to use. As of Oracle 9i, only the JMS 1.0.2b specification is supported.
Properties In addition to the properties available for the standard Jms Provider, the Oracle JMS Provider adds the following properties:
Property
Description
Default
url
The JDBC URL for the Oracle database, for example jdbc:oracle:oci:@myhost.
Required yes
The user and password may be specified in the URL itself, for example jdbc:oracle:oci:scott/ tiger@myhost, in which case the (standard JMS Provider) properties username and password are not required.
Document generated by Confluence on Apr 24, 2008 08:11
Page 118
multipleSessionsPerConnection Some versions of Oracle do not support more than one JMS session per connection. In this case we need to open a new connection for each session to avoid the following error: JMS-106: Cannot have more than one open Session on a JMSConnection payloadFactory
false
If the queue's payload is an ADT (Oracle Advanced Data Type), the appropriate payload factory must be specified in the endpoint's properties.
no
no
Transformers In addition to the transformers available for the standard Jms Provider, the Oracle JMS Provider adds the following transformers, found in org.mule.vendor.oracle.jms.transformers.
Transformer
Description
StringToXMLMessage
Expects a string containing properly-formed XML. Creates a JMS message whose payload is Oracle's native XML data type.
XMLMessageToDOM
Expects a JMS message whose payload is Oracle's native XML data type. Returns the XML as a W3C Document (DOM).
XMLMessageToStream
Expects a JMS message whose payload is Oracle's native XML data type. Returns the XML as an InputStream.
XMLMessageToString
Expects a JMS message whose payload is Oracle's native XML data type. Returns the XML as a String.
The default transformers are the same as the standard JMS Provider (JMSMessageToObject and ObjectToJMSMessage).
Example Configuration The following is an example configuration using the Oracle JMS Provider: <mule-configuration id="TestConfiguration" version="1.0"> <properties> <property name="url" value="jdbc:oracle:oci:@myhost" /> <property name="username" value="scott" /> <property name="password" value="tiger" />
Document generated by Confluence on Apr 24, 2008 08:11
Page 119
<endpoint name="XmlQueue" address="oaq://XML_QUEUE" transformers="StringToXMLMessage" /> <model name="Test Model"> <mule-descriptor name="XML-Driven UMO" implementation="com.foo.MyUMO"> <endpoint address="oaq://XML_QUEUE" transformers="XMLMessageToString"> <properties> <property name="payloadFactory" value="oracle.xdb.XMLTypeFactory" />
Endpoints Oracle AQ endpoints are expressed in the same way as Jms endpoints except the protocol is different. oaq://my.queue or oaq://topic:my.topic
You can define an Oracle AQ endpoint without declaring the connector (as shown above), by including all necessary information on the endpoint uri i.e. oaq://XML_QUEUE?url=jdbc:oracle:oci:scott/tiger@myhost
Refer to the unit tests for more examples on how to use the provider.
Dependencies The Oracle JMS Provider requires the following Oracle libraries, which should be included in your Oracle installation: • • • • •
ojdbc14.jar aqapi13.jar jmscommon.jar xdb.jar (only required for native XML support) xmlparserv2.jar (only required for native XML support)
These jars are included in the distribution.
Unit Tests In order to run the unit tests in tests/vendor/oracle against your Oracle database, you will need to create a JMS user "mule" and grant it AQ rights as follows.
Document generated by Confluence on Apr 24, 2008 08:11
Page 120
sqlplus sys/sys@xe as sysdba create user mule identified by mule; grant connect, resource, aq_administrator_role to mule identified by mule; grant execute on sys.dbms_aqadm to mule; grant execute on sys.dbms_aq to mule; grant execute on sys.dbms_aqin to mule; grant execute on sys.dbms_aqjms to mule; exec dbms_aqadm.grant_system_privilege('ENQUEUE_ANY','mule'); exec dbms_aqadm.grant_system_privilege('DEQUEUE_ANY','mule');
The URL (jdbc:oracle:thin:@//127.0.0.1:1521/xe) given in the test config files (tests/vendor/ oracle/src/test/resources) assumes a default local installation of Oracle XE. If this is not the case, you will also need to modify this URL before running the tests.
Document generated by Confluence on Apr 24, 2008 08:11
Page 121
SeeBeyond JMS Server Integration This page last changed on Jan 30, 2008 by ross.
The configuration provided is for the SeeBeyond ICAN IQManager JMS Server. Note the values in [ ] (square brackets), these should be replaced by values relevant to your installation. <properties> <property name="jndiInitialFactory" value="com.stc.is.naming.NamingContextFactory"/> <property name="jndiProviderUrl" value="[MULE:ServerName]:18006"/> <property name="connectionFactoryJndiName" value="/jms/connectionfactory/queue/[MULE:LogicalHostName]_[MULE:JMS iqManager Name]" />
For a topic, the connectionFactoryJndiName would be /jms/connectionfactory/topic/ [MULE:LogicalHostName]_[MULE:JMS iqManager Name]. You will need the following jars and files from the Java ApiKit on your classpath: • • • • • • •
com.stc.jmsis.jar fscontext.jar providerutil.jar jms.jar jta.jar log4j.jar log4j.properties
Thanks to Brian Kalbfus for contributing this configuration.
Document generated by Confluence on Apr 24, 2008 08:11
Page 122
SonicMQ Integration This page last changed on Jan 30, 2008 by ross.
Configuration tested with versions 6.1 and 7.0. <properties> <property name="specification" value="1.1"/> <property name="connectionFactoryJndiName" value="sonic-cf"/> <property name="jndiInitialFactory" value="com.sonicsw.jndi.mfcontext.MFContextFactory"/> <property name="jndiProviderUrl" value="tcp://localhost:2506"/> <map name="connectionFactoryProperties"> <property name="clientID" value="clientIDString"/> <property name="connectID" value="connectIDString"/> <property name="connectionURLs" value="somURLStrings here"/> <property name="defaultUser" value="userString"/> <property name="defaultPassword" value="passwordString"/> <property name="prefetchCount" value="10"/> <property name="prefetchThreshold" value="10"/> <property name="faultTolerant" value="true"/> <property name="persistentDelivery" value="true"/> <property name="loadBalancing" value="true"/> <property name="sequential" value="false"/>
<map name="jndiProviderProperties"> <property name="com.sonicsw.jndi.mfcontext.domain" value="Domain1"/> <property name="java.naming.security.principal" value="Administrator"/> <property name="java.naming.security.credentials" value="Administrator"/> <property name="com.sonicsw.jndi.mfcontext.idleTimeout" value="5000"/>
<property name="username" value="Administrator"/> <property name="password" value="Administrator"/>
Thanks to Knut Lerpold for contributing this configuration.
Document generated by Confluence on Apr 24, 2008 08:11
Page 123
Sun JMS Grid Integration This page last changed on Jan 30, 2008 by ross.
The following demonstrates how to configure Mule to use the Sun JMS Grid server. <properties> <property name="specification" value="1.1"/> <property name="connectionFactoryJndiName" value="QueueConnectionFactory"/> <property name="jndiInitialFactory" value="com.spirit.directory.SpiritVMDirectoryContextFactory"/> <map name="jndiProviderProperties"> <property name="driverName" value="WMSEmbedded"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 124
Tibco EMS Integration This page last changed on Feb 07, 2008 by andrew.calafato.
The following demonstrates how to configure Mule to use the Tibco Enterprise Message Server (EMS) with authentication in place. <properties> <property name="jndiProviderUrl" value="tibjmsnaming://:port"/> <property name="connectionFactoryJndiName" value="QueueConnectionFactory"/> <map name="jndiProviderProperties"> <property name="java.naming.factory.initial" value="com.tibco.tibjms.naming.TibjmsInitialContextFactory"/> <property name="java.naming.security.principal" value="<username>"/> <property name="java.naming.security.credentials"value="<password>/> <property name="username" value="<username>"/> <property name="password" value="<password>"/>
For XA Transactions you will have to create an XA Connection Factory from TIBCO administration-tool (tibemsadmin) in the following way: > create factory XAQueueConnectionFactory xaqueue url=tcp://7222
Document generated by Confluence on Apr 24, 2008 08:11
Page 125
Weblogic Jms Integration This page last changed on Jan 30, 2008 by ross.
Before using Mule with Weblogic copy the weblogic.jar file to $MULE_HOME/lib/user. JNDI destinations syntax If Mule fails to lookup topics or queues in Weblogic's JNDI, but the JNDI tree lists them as available, try replacing JNDI subcontext delimiters with dots, so tracker/topic/ PriceUpdates becomes tracker.topic.PriceUpdates.
Weblogic 8.x and below <properties> <property name="jndiDestinations" value="true"/> <property name="forceJndiDestinations" value="true"/> <property name="specification" value="1.0.2b"/> <property name="connectionFactoryJndiName" value="javax.jms.QueueConnectionFactory" /> <property name="jndiInitialFactory" value="weblogic.jndi.WLInitialContextFactory"/> <property name="jndiProviderUrl" value="t3://localhost:7001"/>
Weblogic 9.x For Weblogic 9.x the config is almost the same. The only differences are: • Supported JMS specification level is 1.1 (1.0.2b should still work, however) • The unified JMS connection factory can be used as a result of the above. The following example demonstrates using the default factories available out of the box. <properties> <property name="specification" value="1.1"/> <property name="jndiDestinations" value="true"/> <property name="forceJndiDestinations" value="true"/> <property name="connectionFactoryJndiName" value="weblogic.jms.ConnectionFactory"/> <property name="jndiInitialFactory" value="weblogic.jndi.WLInitialContextFactory"/> <property name="jndiProviderUrl" value="t3://localhost:7001"/>
JDK version In case you are getting the following error when connecting to Weblogic 9.x
org.mule.MuleServer: A Fatal error has occurred while the server was running: class weblogic.utils.classloaders.GenericClassLoader overrides final method ?.? java.lang.VerifyError: class weblogic.utils.classloaders.GenericClassLoader overrides final method ?.? make sure Mule is started with JDK 5 and above, anything below will not work.
Document generated by Confluence on Apr 24, 2008 08:11
Page 126
WebSphere MQ Integration This page last changed on Apr 21, 2008 by andrew.
To configure a WebSphere MQ Jms connector for Mule you will need to do the following 1. Set up a Connection Factory in the WAS admin console 2. Confiure a Jms Connector in Mule to use the Connection Factory.
Set up the Connection Factory Under WAS Admin Console > Resources > WebSphere MQ JMS Provider > WebSphere MQ Queue Connection Factories Set the following properties • • • •
Name: Connection Factory JNDI Name: jms/ConnectionFactory Queue Manager: (Your QMGR Here) Host, Port, etc.
Mule Configuration Add the following connector configuration <properties> <property name="specification" value="1.1"/> <property name="hostName" value="myMQServer"/> <property name="transportType" value="1"/> <property name="name" value="myMQConnector"/> <property name="jndiInitialFactory" value="com.ibm.websphere.naming.WsnInitialContextFactory"/> <property name="connectionFactoryJndiName" value="jms/ConnectionFactory"/>
The hostName property is mandatory and refers to a name that will be used for this connection. This is different to the host property which refers to an IP address or network name of the server hosting WebSphere MQ. Apart from the name attribute for the connector, WebSphere mandates a name property. If you're using IBM's connection factory, you may additionally need the following configuration - the connection factory is configured in Spring here: <properties> <property name="name" value="ThisConnector"/> <property name="hostname" value="MyHost"/> <property name="hostName" value="MyHost"/> <property name="port" value="6969"/> <property name="channel" value="S_machine"/> <property name="queueManager"> QM_machine <property name="transportType">1 <property name="specification"> 1.1
Note that WebSphere MQ v5.3 requires at least Fix Pack 6 (CSD06) applied for JMS 1.1 support. Earlier levels must set the specification property to 1.0.2b. The latest WebSphere MQ Fix Packs can be downloaded here: http://www-1.ibm.com/support/ docview.wss?uid=swg27006037
Document generated by Confluence on Apr 24, 2008 08:11
Page 127
You will also need the following IBM Websphere jars on your classpath: • • • •
com.ibm.mq.jar com.ibm.mqjms.jar connector.jar dhbcore.jar If you are using WAS, refer to this discussion for some known limitations.
Document generated by Confluence on Apr 24, 2008 08:11
Page 128
Jmx Management This page last changed on Jan 30, 2008 by ross.
The Mule Jmx agent enables the configuration of a local or remote Jmx connection to Mule and registers Mule resources with the MBean server. With Jmx enabled you can do the following against a local or remote instance • • • • •
View the configuration state of the MuleManager Stop and start the Mule instance. Stop and start the model. Stop, start, pause and resume components. Query event processing and endpoint routing stats on individual components or for the whole server instance.
To configure the agent with Mule use the following configuration
You can set the following properties on the agent.
Property
Description
Default
locateServer
Whether the agent should try locating an MBeanServer instance before creating one
true
createServer
Whether the agent should create an MBean server if one couldn't be found or locateServer was set to false.
true
connectorServerUrl
A remote Jmx Connector server Url
null
mBeanServer
The mBean server to use. Optionally developers can set this to an MBeanServer in a container or using a factory property
null
enableStatistics
Determines whether statistics reporting is enabled for the Mule instance
true
domain
The JMX domain for this Mule server (no longer available since Mule 1.3)
Mule.<Mule ID> from XML config or an autogenerated Mule. otherwise
credentials
A Map of username/password entries used to authenticate remote JMX access. If not specified, remote access is not restricted. (since Mule 1.4)
empty Map
Remote Management It's also possible to configure the Mule JMX subsystem for remote management with 3rd-party tools like MC4J:
Document generated by Confluence on Apr 24, 2008 08:11
Page 129
<properties> <property name="connectorServerUrl" value="service:jmx:rmi:///jndi/rmi://localhost:1099/server"/> <map name="connectorServerProperties"> <property name="jmx.remote.jndi.rebind" value="true"/> <map name="credentials"> <property name="muleusername" value="mulepassword"/> <property name="admin" value="secret"/>
Running an External RMI Server If you are using JDK1.4 and running the RMI Registry externally using rmiregistry.exe (Bundled with JDK 1.4) you will need to add the JMX remoting Jar to your JDK classpath in order for the external RMI registry to serve Remote JMX clients. This isn't an issue if running with JDK 1.5 as the JMX remoting classes are now part of the JDK.
Jmx Adapter Agents In addition to the JmxAgent you can configure other agents to configure Jmx Adaptors or register supporting MBeans. Mule currently ships with two Jmx Adaptor agents: Mx4j and Jdmk.
Mx4j Configuration To configure Mule to use the Mx4j Html Adaptor <properties> <property name="jmxAdaptorUrl" value="http://localhost:9999"/>
http://localhost:9999 _is the default URL and can be ommitted if there's no need to change it._ For security's sake, the management console is only accesible from the localhost. If you wish to loosen this restriction, change "localhost" to "0.0.0.0". This will allow access from any machine in the LAN. Refer to the MX4J docs for more details.
Mx4j Security As of Mule 1.3 it is possible to protect the JMX web console with a login and password. If the login property has been specified, the protection scheme kicks in: <properties> <property name="login" value="user"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 130
<property name="password" value="password"/>
By default, the BASIC authentication scheme is used. As of Mule 1.3 SSL protection is also available: <properties> <map name="socketFactoryProperties"> <property name="keyStoreName" value="serverKeystore"/> <property name="keyStorePassword" value="mulepassword"/>
The above config protects the data in transit, while still allowing anybody to access the console. It is recommended both approaches are combined for tighter control over the environment. If socketFactoryProperties contains at least one entry, the agent will switch to HTTPS connections. The jmxAdaptorUrl scheme is not important here, the choice of either HTTP or HTTPS will be made based on the availability of the socketFactoryProperties map. If this config is omitted, it will always use HTTP, even if you specify https:// connection scheme in the jmxAdaptorUrl property.
Property Name
Description
authenticationMethod
Method used to authenticate when login/password is available (since Mule 1.3)
BASIC
jmxAdaptorUrl
URL to expose web console at
http://localhost:9999
name
Name of this JmxAgent
login
Used to authenticate access (since Mule 1.3)
password
Used if login has been provided, can be empty (since Mule 1.3)
cacheXsl
Indicates whether to cache the transformation objects. This speeds-up the process. It is usually set to true, but you can set it to false for easier testing (since Mule 1.3)
Document generated by Confluence on Apr 24, 2008 08:11
Required
Default Value
true
Page 131
xslFilePath
Used to customize adaptor's stylesheet. Determines where to look for xsl files. If the target file is a dir, it assumes that xsl files are located in the dir. Otherwise if it points to a .jar or .zip files, it assumes that the files are located inside. Pointing it to a file system is especially useful for testing (since Mule 1.3)
pathInJar
Used to customize adaptor's stylesheet. Sets the dir in the jar file where xsl files reside (since Mule 1.3)
socketFactoryProperties
A map containing properties for SSL server socket factory configuration. These will be delegated as is to the agent's HTTP/ S adaptor. See mx4j API docs for the list of available properties.
(if xslFilePath points to a jar/zip)
(for HTTPS connections only)
Jdmk Configuration (deprecated) Viewing Statistics Mule traps many different statistics about the running state of a server and number of events processed. With the JMX Management Console you can view the Mule statistics report. To view the statistics report shown below using the above configuration go to the following url http://localhost:9999/
then click on any JMX domain name (except for JMImplementation), or go to 'Statistics' tab and query JMX domain for statistics from there -
Document generated by Confluence on Apr 24, 2008 08:11
Page 132
Other Management Agents Log4J Agent The log4j Agent exposes the configuration of the Log4J instance used by Mule for Jmx management.
All Jmx Agents can be used together if desired and you can register your own custom ones as well. Just ensure the org.mule.management.agents.JmxAgent is registered.
Default JMX Support Agent You can configure all Jmx Agents with a single class called DefaultJmxSupportAgent. It will register your Mule instance with the following agents • • • • • • •
Rmi agent (if necessary) on rmi://localhost:1099 Jmx Registration agent Remote Jmx access on service:jmx:rmi:///jndi/rmi://localhost:1099/server Jmx Notification agent used to receive Server notifications using Jmx Notifications Log4J Jmx Agent (Optional) JDMK Agent - set loadJdmkAgent property to true (since Mule 1.3.1) (Optional) MX4J Agent - set loadMx4jAgent property to true (since Mule 1.3.1)
Just add the following to your configuration
Starting with Mule 1.4, the following properties can be additionally customized:
Document generated by Confluence on Apr 24, 2008 08:11
Page 133
• port - the port to run RMI registry on, also used for remote JMX management (defaults to 1099) • host - host to bind to. Normally one would override this only for multi-NIC servers (defaults to localhost) • credentials - a Map of username/password properties for remote JMX access. The configuration option delegates to the JmxAgent, consult its documentation for more details. The agent does a lot of useful plumbing for JMX, however at the expense of defaulting many parameters. If you find a need to customize some subsystems you could either: 1. Subclass DefaultJmxSupportAgent and override corresponding createXXX() factory methods. 2. Disassemble the services provided by this support agent into separate agents and configure them individually.
Document generated by Confluence on Apr 24, 2008 08:11
Page 134
DefaultJmxSupportAgent This page last changed on Jan 30, 2008 by ross.
Default JMX Support Agent You can configure all Jmx Agents with a single class called DefaultJmxSupportAgent. It will register your Mule instance with the following agents • • • • • • •
Rmi agent (if necessary) on rmi://localhost:1099 Jmx Registration agent Remote Jmx access on service:jmx:rmi:///jndi/rmi://localhost:1099/server Jmx Notification agent used to receive Server notifications using Jmx Notifications Log4J Jmx Agent (Optional) JDMK Agent - set loadJdmkAgent property to true (since Mule 1.3.1) (Optional) MX4J Agent - set loadMx4jAgent property to true (since Mule 1.3.1)
Just add the following to your configuration
Starting with Mule 1.4, the following properties can be additionally customized: • port - the port to run RMI registry on, also used for remote JMX management (defaults to 1099) • host - host to bind to. Normally one would override this only for multi-NIC servers (defaults to localhost) • credentials - a Map of username/password properties for remote JMX access. The configuration option delegates to the JmxAgent, consult its documentation for more details. The agent does a lot of useful plumbing for JMX, however at the expense of defaulting many parameters. If you find a need to customize some subsystems you could either: 1. Subclass DefaultJmxSupportAgent and override corresponding createXXX() factory methods. 2. Disassemble the services provided by this support agent into separate agents and configure them individually.
Document generated by Confluence on Apr 24, 2008 08:11
Page 135
Jdmk Configuration This page last changed on Jan 30, 2008 by ross.
Jdmk Configuration To configure Mule to use the Jdmk Html Adaptor <properties> <property name="jmxAdaptorUrl" value="http://localhost:9998"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 136
Message Routers This page last changed on Apr 18, 2008 by tcarlson.
Message routers are used to control how events are sent and received by components in the system. Mule defines Inbound routers that apply to events as they are received and outbound routers that are invoked when an event is being dispatched.
Quick Reference Inbound Routers
Outbound Routers
Response Routers
Nested Routers
Related
Idempotent Receiver
Filtering Outbound Router
Response Aggregator
Nested Router
Filters
Selective Consumer
Recipient List
Aggregator
Multicasting Router
Resequencer
Chaining Router
Forwarding Consumer
Message Splitter
WireTap Router
Filtering List Message Splitter
Using ReplyTo Endpoints
Filtering Xml Message Splitter Exception Based Router Message Chunking Router Mule provides flexible message routing support for your components. Routing features are based on the enterprise routing requirements described in EIP. There are a few elements to Mule's routing system -
Inbound Routers A single event is received via a endpoint and the router controls how and if this event gets routed into the system.
Outbound Routers Once a message has been processed by a component and outbound router can used to determine which components get the result event.
Response Routers Are used in request/response scenarios where event traffic is triggered by a request and the traffic needs to be consolidated before a response is given. The classic example of this is where a request is made and tasks are executed in parallel. Each task must finish executing and the results processed before a response can be sent back to the callee.
Document generated by Confluence on Apr 24, 2008 08:11
Page 137
Filters Filters provide the logic by which to invoke a particular router. An example would be the XPathFilter, or PayloadTypeFilter. Filters can be combined using the logic filters, AndFilter, OrFilter and NotFilter. Not all routers need to use filters but all routers support them. See Filters for information.
CatchAll Strategies A catch all strategy can be configured on a router and will be invoked if no routing path can be found for the current event. A endpoint can be associated with a catch all strategy so that any events that 'slip through the net' can be caught and routed to a common location.
Configuring Routers Inbound Router configuration Inbound routers can be used to control and manipulate events received by a component. Typically, an inbound router can be used to filter incoming event, aggregate a set of incoming events or re-sequence events when they are received. Inbound routers are also used to register multiple inbound endpoints for a component. You can chain inbound routers together, in this scenario each router is matched before the event is dispatched to a mule component. Inbound routers are different to outbound routers in that the endpoint is already known (as the message has already been recieved) so the purpose of the router is to control how messages are given to the component. You can specify a catch-all strategy which will be invoked if any of the routers do not accept the current event. An Inbound Router can be configured on a mule-descriptor element in the mule-config.xml <endpoint address="jms://failure.queue"/>
There is router configured for this inbound-router. The first is a selective consumer and will accept the event if a nested field in the payload is set to resultcode='success'. If this filter matches, the event will be passed to the component. If either router does not match the Catch all strategy is invoked, which sends all events via its configured endpoint endpoint, in this case a jms queue called 'failure.queue'.
Outbound Router Configuration Outbound routers are used to control which endpoints are used to send events once an UMO component has finished processing. Message Routers are configured on the compoennt and allow the developer to define multiple routing constraints for any given Event. You can specify a catch-all strategy which wil be invoked if none of the routes accept the current event. An example of an Outbound Message Router is given below <endpoint address="jms://default.queue"/> <endpoint address="smtp://[email protected]" transformers="ExceptionToEmail"> <properties> <property name="subject" value="Exception!"/> <property name="fromAddress" value="[email protected]!"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 138
className="org.mule.routing.filters.PayloadTypeFilter"/> <endpoint address="vm://my.component"/>
This outbound router defines two routers. The first checks to see if the payload type is java.lang.exception, and end the messge via the endpoint; in this case over smtp to [email protected]. There is a transformer on this endpoint ExceptionToEmail which will convert the exception into a javax.mail.Message before sending the event. Note the properties on the endpoint, these will be used to override the Smtp Connector behaviour for this endpoint instance. If the event payload is not an Exception, the second router is invoked which checks to see if the payload type is String and then also checks that the payload matches a regular expression. If both filters match the event is routed to a component listening on vm://my.component. If neither routers match the Catch all strategy is invoked which sends all events to a jms queue called 'default queue'.
Matching all Routers It is possible to configure an outbound router to invoke all of the matching routers, rather than just the first. For example, in the situation where you always want to send a confirmation of a deposit back to the original depositor, and, if the deposit was above $100,000, send a notification message to the 'high net worth client manager' for possible follow-up, you can utilise the matchAll property on the router definition as follows: <endpoint address="jms://deposit.queue"/> <endpoint address="endpoints="jms://large.deposit.queue"/>
Here, the first router will always match as there is no filter on it and the second router will only match of the deposit amount is >= $100000 - if this is the case then both routers will be invoked.
Response Router Configuration Response routers can be used to join forked tasks in a request response call. In fact you would only use a response router with components that use synchronous calls (as there is no response when dispatching an event asynchronously). Mule provides a ResponseAggregator router that can be used in conjunction with a Message Splitter or Recipient List router to aggregate events before returning a response. <endpoint address="jms://bank.quotes"/>
The endpoint is the address that responses should be sent to be processed. The router in this case is responsible for aggregating Bank quotes into a single quote for the customer. Consider the LoanBroker component configuration below<mule-descriptor name="LoanBroker"
Document generated by Confluence on Apr 24, 2008 08:11
Page 139
implementation="org.mule.samples.loanbroker.SyncLoanBroker"> <endpoint address="vm://Loan.Requests"/> <endpoint address="jms://Loan.Quotes"/>
Don't worry too much about the filters and routers as these are described in detail below. What this configuration demonstrates is that our Loan Broker will receive requests from vm://Loan.Requests and will dispatch multiple requests to different banks via the outbound router. The bank endpoints are defined in a List called 'recipients' that is a property on the outbound message (See the Loan Broker Example for more information). The important setting on the outbound router is the endpoint, this tells Mule to route all responses to the jms://Loan.Quotes endpoint which is the endpoint that the response router is listening on. When all responses are received the BankQuotesResponseAggregator selects the cheapest quotes and returns it. Mule then handles returning this back to the callee. The Endpoint is applied to the next component invoked, i.e. if component1 dispatches to component2 and component1 has an outbound router with a reply-to endpoint, component2 will send the results of its invocation to the reply-to endpoint.
Response Transformers Sometimes you will want to transform response event without doing any other work on the response. To do this just set the transformers attribute on the response router without any other routing configuration.
Nested Router Configuration Nested routers can be used by components to call out an external service during their workflow stage. Nested router's work principle is based on Java interface binding. The external service to be called should implement an interface. The component should encapsulate a reference to that interface, which is initialised during the bootstrap stage by the Mule configuration builder. The reference will be initialized using a reflective proxy class. public class Invoker { private HelloInterface hello; public String invoke(String s) { return "Received: " + hello.helloMethod(s); } public void setHello(HelloInterface hello) { this.hello = hello; } public HelloInterface getHello() { return hello; } }
Next, the Nested Router is used to bind the aforementioned interface to the external service.
Document generated by Confluence on Apr 24, 2008 08:11
Page 140
<mule-descriptor name="InvokerComponent" implementation="org.mule.foo.Invoker"> <endpoint address="jms://Invoker.in"/> <endpoint address="axis:http://192.168.2.14:81/services/HelloWebComponent?method=helloMethod" remoteSync="true"/> <endpoint address="jms://Invoker.out"/>
Note that the call to the external service is synchronous because component workflow is blocked until the call is finished. Consequently the endpoint bound to the interface should be synchronous (for VM transport "synchronous" attribute should be used instead of "remoteSync").
Mule Inbound Routers The following sections describe each Mule inbound router and how to configure them.
Idempotent Receiver An IdempotentReceiver is an Inbound router that ensures only unique messages are received by a component. It ensures that each message is unique by checking and storing the unique id of each message it receives. Note that this unique id often comes from the underlying technology and that some endpoints do not support unique ids. If the endpoint being used doesn't support unique ids an exception will be thrown. There is a simple Idempotent receiver implementation provided at org.mule.routers.inbound.IdempotentReceiver. The default Implementation uses a simple file-based mechanism for storing message ids, but this class can be extended to use a database to store the ids.
Configuration <properties> <property name="disablePersistence" value="false"/> <property name="storePath" value="./idempotent"/>
disablePersistence - Determines whether received message ids are stored to disk so that the router can remember state between restarts. The default value is false; storePath - Determines where to store the received ids file. The mule working directory is set in the Muleconfiguration.setWorkingDir(...). The default working directory for is ./.mule. The file created will be in the form of muleComponent_. The default value for this property is ./.mule/ idempotent/.
Selective Consumer A selective consumer is an Inbound Router that can apply one or more filters to the incoming event payload. If the filters match the event will get forwarded to the component otherwise the event will get
Document generated by Confluence on Apr 24, 2008 08:11
Page 141
forwarded to the catch-all strategy on the router. If not catch-all is configured the event is ignored and a warning is logged.
Configuration <endpoint address="jms://topic:error.topic"/>
There are no properties associated with this router, however see Filters for more information about the how filters can be used and what filters are available. Note that by default the filter is applied to the event payload after the transformers configured for the inbound endpoint are applied to the event. There may be situations where the developer may need to execute filters on the event payload without any transformation being applied. You can set the transformFirst property on this router to control if transformations are applied. <endpoint address="jms://topic:error.topic"/> <properties> <property name="transformFirst" value="false"/>
Aggregator The Aggregator pattern stipulates that two or more messages are combined into a single result message. Mule provides an abstract implementation that has a template method that actually does the message aggregation. A common use of the aggregator router is to combine the results of multiple requests such as "ask this set of vendors for the best price of X". The Aggregator is based on the Selective Consumer so filters can also be applied to messages.
Configuration
The CorrelationAggregator can be used to match messages with a given CorrelationId. Correlation Ids are set on messages when they are dispatched for certain outbound routers such as the Recipient List and Message Splitter routers. These messages can be aggregated back together again using the CorrelationAggregator router. You can easily write custom Aggregator routers to aggregate on some other criteria if your messages. There is an AbstractEventAggregator that provides a thread-safe implementation for custom Aggregators.
Document generated by Confluence on Apr 24, 2008 08:11
Page 142
Resequencer The Resequencer Router will hold back a set of messages, re-order them and send them to the target component in the correct sequence. A java.util.Comparator is used to sort the events. This router is based on the Selective Consumer which means that filters can be applied to the incoming events.
Configuration <properties> <property name="comparator" value="org.mule.routing.foo.EventPayloadComparator"/> <property name="eventThreshold" value="5"/>
The EventPayloadComparator is used to re-order the events. If a comparator is not set the events will not be resequenced. There is also a CorrelationEventResequencer that will reseguence a group of messages (grouped by their correlation Id) depending on the order the messages were sent. This is useful where you configure a Message Splitter to send out multiple events and then you want to process all the split message parts in a particular order.
There is no need for any further configuration as the router uses standard properties on the MuleMessage.
Forwarding Consumer This router allows for events to be forwarded to an outbound endpoint without first being processed by a component. It essentially acts as a bridge between an inbound and an outbound endpoint. This is useful in situations where the developer does not need to execute any logic on the inbound event but does need to foward it on to a component residing on another destination (i.e. a remote Mule node or application) over the network.
Configuration <mule-descriptor name="FileReader" inboundEndpoint="file:///temp/myfiles/in" outboundTransformer="ObjectToByteArray" outboundEndpoint="tcp://192.168.0.6:12345" implementation="org.mule.components.simple.NullComponent">
When the event is triggered by a file on the local file system becoming availiable the event is automatically forwarded via tcp to 192.168.0.6. Notice that there is a outboundTransfrmer configured. This will be used to transform the event's payload before it is dispatched over tcp. Also, the implementation of this component is the NullComponent. This component doesn't do anything as is just acts as a place holder. However, you could mix and match the routers so that some events are forwarded while others are processed by the component.
Document generated by Confluence on Apr 24, 2008 08:11
Page 143
The Forwarding Consumer extends the Selective Consumer so you can configure filters on this router.
BridgeComponent As of Mule 1.1 the Forwarding consumer can be automatically configured using the BridgeComponent. This is a component that automatically configures the Forwarding consumer and replaces the need for the NullComponent in the above example. The same example using the the BridgeComponent would look like <mule-descriptor name="FileReader" inboundEndpoint="file:///temp/myfiles/in" outboundTransformer="ObjectToByteArray" outboundEndpoint="tcp://192.168.0.6:12345" implementation="org.mule.components.simple.BridgeComponent">
Mule Outbound Routers The following sections describe each Mule outbound router and how to configure them. Outbound routers can be more complex to configure as they allow different routing paths that can be selected depending on the logic defined in one or more filters.
Content Based Router Content based routing is the term used for routing events based on the event contents. Mule currently supports content based routing using the Filtering Outbound Router, but by Mule v1.0 JSR-94 rules based routing will be possible.
Filtering Outbound Router A content based router uses filters to determine whether the content of the event matches a particular criteria and if so will route the event to one or more endpoints configured on the router. All Mule outbound routers extend FilteringOutboundRouter which means you can always apply a filter to an outbound router. A notable exception is the OutboundPassThroughRouter, which obviously does not allow filters.
Configuration <endpoint="jms://error.queue"/> <endpoint address="smtp://[email protected]"/> <endpoint address="jms://string.queue"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 144
The filter is applied to the event payload before any transformers are applied to the event. There may be situations where the developer may need to transform the event before the filter is applied. You can set a transformer on this router that will be applied to the event before the filter. <endpoint address="smtp://[email protected]"/> <properties> <property name="transformer" value="aTransformer"/>
Recipient List the Recipient list router can be used to send the same event to multiple endpoints over the same endpoint or to implement routing-slip behaviour where the next destination for the event is determined from the event properties or payload. Mule provides an abstract Recipient list implementation org.mule.routing.outbound.AbstractRecipientList that provides a thread-safe base for specialised implementations. Mule also provides a Static recipient list that takes a configured list of endpoints from the current event or statically declared on the endpoint.
Configuration <properties> <list name="recipients"> <entry value="jms://orders.queue"/> <entry value="jms://tracking.queue"/>
ReplyTo You can use the reply-to endpoint of the outbound router to ensure all messages sent got sent back to the same destination. <properties> <list name="recipients"> <entry value="jms://orders.queue"/> <entry value="jms://tracking.queue"/>
This configuration will first check that the payload type is a Jms Message and will then send the message to the orders.queue and tracking.queue.
Document generated by Confluence on Apr 24, 2008 08:11
Page 145
Multicasting Router The Multicasting router can be used to send the same event over multiple endpoints. When using this router care must be taken to configure the correct transformers on the endpoints to handle the event source type.
Configuration <endpoint address="jms://test.queue" transformers="StringToJmsMessage"/> <endpoint address="http://10.192.111.11" transformers="StringToHttpClientRequest"/> <endpoint address="tcp://10.192.111.12" transformers="StringToByteArray"/>
Remember that care should be taken to ensure that the message being routed is transformed to a format that the endpoint understands.
ReplyTo Again, you can use the reply-to property of the outbound router to ensure all messages sent got sent back to the same destination. <endpoint address="jms://test.queue" transformers="StringToJmsMessage"/> <endpoint address="http://10.192.111.11" transformers="StringToHttpClientRequest"/> <endpoint address="tcp://10.192.111.12" transformers="StringToByteArray"/>
Exception Based Router The Exception Based router can be used to send an event over an endpoint by selecting the first endpoint that can connect to the transport. This can be useful for setting up retries, when the first endpoint fails the second will be invoked and if that fails it will try the third endpoint, and so on. Note, it will override the endpoint mode to synchronous while looking for a successful send, and will resort to using the endpoint's mode for the last item in the list.
Configuration <endpoint address="tcp://10.192.111.10:10001" /> <endpoint address="tcp://10.192.111.11:10001" /> <endpoint address="tcp://10.192.111.12:10001"/>
Message Splitter A message splitter can be used to breakdown an outgoing message into parts and dispatch those parts over different endpoints configured on the router. Mule provides an abstract implementation of
Document generated by Confluence on Apr 24, 2008 08:11
Page 146
a message splitter org.mule.routing.outbound.AbstractMessageSplitter that provides thread-safe base implementation with the necessary logic for routing the event allowing concrete implementations define how the message is split.
Configuration <endpoint address="vm://component1"/> <endpoint address="vm://component2"/> <endpoint address="vm://component3"/>
Note as with all router configurations you can define properties elements to set bean properties on the router. For example, you may want to define a list of XPath expressions that would be used to extract the different message parts. See Configuring Properties for more information. By default the AbstractMessageSplitter sets a Correlation Id and Correlation Sequence to the outbound events so that inbound routers such as the Aggregator or Resequencer are able to resequence or combine the split messages.
ReplyTo You can use the reply-to property of the outbound router to ensure all messages sent got sent back to the same destination. <endpoint address="vm://component1"/> <endpoint address="vm://component2"/> <endpoint address="vm://component3"/>
Filtering List Message Splitter This router is an implementation of Message Splitter that accepts a list of objects that will be routed to different endpoints. The actual endpoint used for each object in the list is determined by a filter configured on the endpoint itself. If the endpoint's filter accepts the object the endpoint will be used to route the object. The router configuration below expects the message payload to be a java.util.List and will route objects in the list that are of type com.foo.Order, com.foo.Item and com.foo.Customer. The router will allow any number and combination of these objects.
Configuration <endpoint address="jms://order.queue"> <endpoint address="jms://item.queue"> <endpoint address="jms://customer.queue">
Document generated by Confluence on Apr 24, 2008 08:11
Page 147
Note that there is also a filter on the router itself that ensures that the message payload received is of type java.util.List. If there are objects in the list that do not match any of the endpoint filters a warning will be written to the log and processing will continue. To route any non-matching object types to another endpoint just add the endpoint at the end of the list without a filter.
Filtering Xml Message Splitter Analogous to the above, but operating on XML documents. Supported payload types are: • org.dom4j.Document objects • byte[] • java.lang.String If no match is found, it will be ignored (logged at the WARN level). The router will split the payload into nodes based on the splitExpression property. The actual endpoint used for each object in the list is determined by a filter configured on the endpoint itself. If the endpoint's filter accepts the object the endpoint will be used to route the object. The router can optionally perform a validation against an external XML Schema document. Point externalSchemaLocation to XSD file in your classpath. Note in this case you override whatever schema document you declare in XML header. Each part returned is actually returned as a new DOM4J document.
Configuration <endpoint address="vm://order"> <endpoint address="vm://item"> <endpoint address="vm://customer"> <properties> <property name="splitExpression" value="/root/nodes"/> <property name="validateSchema" value="true"/> <property name="externalSchemaLocation" value="/com/example/TheSchema.xsd"/>
Chaining Router The Chaining router can be used to send the event through multiple endpoints using the result of the first invocation as the input for the next. This can be useful where you want to send the results of a synchronous request-response invocation, say, a Web Services call, to a jms queue.
Configuration <endpoint address="axis:http://localhost:8081/services/xyz? method=getSomething"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 148
<endpoint address="jms://something.queue" transformer="SomethingToJmsMessage"/>
Using Replyto Endpoints All outbound routers can have a endpoint that defines where the event should be routed to after the recipient of the event being dispatched has finished with it. The Endpoint is applied to the next component invoked, i.e. if component1 dispatches to component2 and component1 has an outbound router with a reply-to endpoint, component2 will send the results of its invocation to the replyto endpoint. The endpoint can be any valid Mule Endpoint URI and will be sent with the outgoing message. If the underlying transport supports the notion of replyTo, such as Jms, this will be utilised for replyTo endpoints that use Jms.
Document generated by Confluence on Apr 24, 2008 08:11
Page 149
Message Chunking Outbound Router This page last changed on Jan 30, 2008 by ross.
Using the Message Chunking Outbound Router This routing pattern allows you to split a single message into a number of fixed-length messages that will all be routed to the same endpoint. It will split the message up into a number of smaller chunks according to the chunkSize that you configure for the router. If you configure a chunkSize of zero, then the entire message will not be split up and will be routed to the destination endpoint as is. The router splits up the message by first converting it to a byte array and then splitting this array into chunks. If the message cannot be converted into a byte array, a RoutingException is raised. You would use this mechanism if you have bandwidth problems (or size limitations) when using a particular transport. If you want to be able to route different segments of the original message to different endpoints, consider using the Message Splitter router instead. The destination needs to know how to put these items back together again - typically, you would use a Message Chunking Aggregator inbound router for this. Sample Configuration <mule-descriptor name="chunkingService" implementation="org.mule.components.simple.BridgeComponent"> <endpoint address="vm://fromClient"/> <endpoint address="vm://toClient"/> <properties> <property name="chunkSize" value="4"/>
In the example above, any data received on the vm://fromClient is chunked into messages 4 bytes long before being sent along the vm://toClient endpoint. If we sent "The quick brown fox jumped over the lazy dog" to this service, anything listening on vm://toClient will receive the following messages (The spaces have been replaced with underscore signs for ease of reading):
Message #
Contents
1
The_
2
quic
3
k_br
4
own_
5
fox_
6
jump
7
ed_o
8
ver_
9
the_
10
lazy
Document generated by Confluence on Apr 24, 2008 08:11
Page 150
11
_dog
Properties
Name
Description
chunkSize
This property determines the size of each chunk in bytes. It defaults to zero, meaning that the entire original message will be routed as a single chunk.
Document generated by Confluence on Apr 24, 2008 08:11
Page 151
Using the WireTap Inbound Router This page last changed on Jan 30, 2008 by ross.
Using the WireTap Inbound Router The WireTap inbound router allows you to route certain events to a different endpoint as well as to the component.
If you wish to copy all messages that are sent to a specific component, you just need to set the endpoint property of the WireTap router: <endpoint address="vm://FromUser"/> <properties> <property name="endpoint" value= "vm://tapped.channel"/>
In the following scenario, I am merely copying any data from the inbound VM channel to the outbound endpoint using a BridgeComponent. However, I wish to forward some of the input based upon a filter to another component called WireTapReceiver. For simplicities' sake, I have coded this component to do nothing more than pre-pend the message with "INTERCEPTED:" before sending it to the FromTapper VM channel. The code for the WireTapReceiver is as follows: public class WireTapReceiver { public String handleInterceptedData (String aMessage) { //Just Prepend the message with a label return "\nINTERCEPTED: "+aMessage; } }
My Mule configuration file is setup like this: <mule-configuration id="Default" version="1.0"> <description> Experiment to demonstrate how the wiretap router works <properties> <property name="queueEvents" value="true"/> <model name="default"> <mule-descriptor name="StdComp" implementation="org.mule.components.simple.BridgeComponent"> <endpoint address="vm://In"/> <properties>
Document generated by Confluence on Apr 24, 2008 08:11
Page 152
<property name="endpoint" value="vm://ToTapper"/> <endpoint address="vm://ToClient"/> <mule-descriptor name="wiretapper" implementation="org.ricston.experiments.WireTapReceiver"> <endpoint address="vm://ToTapper"/> <endpoint address="vm://FromTapper"/>
Using Filters The StdComp component receives events from the In endpoint. The router passes the event to the component and copies it to the vm://ToTapper endpoint too. The WireTapper component listens on this channel and forwards the event, after processing, to the FromTapper endpoint. The WireTap router is based upon the SelectiveConsumer router and it therefore can take filters. In this example, only messages that match the filter expression are copied to the vm://ToTapper endpoint <properties> <property name="endpoint" value="vm://tapped.channel"/>
Any filter that can be used with the SelectiveConsumer router can be used here too.
Multiple WireTapping You can also have multiple WireTap routers, for the same component: <endpoint address="vm://In"/> <properties> <property name="endpoint" value="vm://ToTapper"/> <properties> <property name="endpoint" value="vm://ToOtherTapper"/>
As you can see input is passed to the component and also copied to one of two destinations depending on the filter.
Document generated by Confluence on Apr 24, 2008 08:11
Page 153
Method Invocation If you are calling the endpoint with a specified method to invoke, for instance, if: • Your inbound endpoint is not vm://In but axis\:http://localhost\:8080/services • Your StdComp is a customized component with a method foo() The web service and its method foo() can be invoked via: • http\://localhost\:8080/services/StdComp?method=foo¶m=bar When this event is wiretapped to the receiving component (in our first example, the component of org.ricston.experiments.WireTapReceiver), Mule might fail with a ComponentException as the receiving component might not have the method foo(). To avoid this and to ensure that the desired method is invoked, you will have to overwrite the method of the event, by specifying: • ?method=methodName, or, • ?method=, so that the onCall() will be called instead For instance, <properties> <property name="endpoint" value="vm://inboundEndpoint3?connector=vm2"> ... <mule-descriptor name="serviceComponent3" implementation="org.mule.components.simple.LogComponent"> <endpoint address="vm://inboundEndpoint3?connector=vm2&method=" synchronous="false"/>
Features The WireTap router supports the following features: • Transactions are supported so the forwarding of events can either start or join a transaction provided that the endpoint supports transactions. • Reply-To can be used to route replies from this endpoint. • The container-property, factory-property, file-property, list, map, system-property and text-property tags can all be used.
Uses The Wiretap router is useful both with and without filtering. If filtered, it can be used to record or take note of particular events or to copy events that require additional processing to a different component. If filters aren't used, you can take a backup copy of all events received by a component. The behaviour here is similar to that of an Interceptor but interceptors can alter the message flow by preventing the message from reaching the component. WireTap routers cannot alter message flow but just copy on demand.
References http://svn.mule.codehaus.org/browse/mule/trunk/mule/tests/integration/src/test/resources/org/mule/ test/integration/routing/wire-tap.xml?r=3468 http://mule.mulesource.org/wiki/display/MULE/Message+Routers
Document generated by Confluence on Apr 24, 2008 08:11
Page 154
Models This page last changed on Jan 30, 2008 by ross.
Mule Models A Mule model manages the runtime behaviour of the service components that a Mule instance hosts. The manner in which these components are invoked and treated is all encapsulated inside the current Mule model. By default, Mule uses the SEDA model but it ships with a number of other models too. You can indicate which model to use for your components by using the type attribute in the <model> tags. You can also have multiple models within a single Mule instance. <model name="mainSection" type="SEDA"> ...
Inside a Mule Model Every Mule Model implements the UMOModel interface. This represents the behaviour of a Mule server and all models implement this interface. The fields and methods that this interface publishes are: • Name - This is a string value that refers to the name of the model and is set as an attribute within the <model> tags. It is required when multiple models exist in a single configuration file. • EntryPointResolver - This refers to a class that implements the UMOEntryPointResolver interface. This class will be used to determine the entry point for any hosted component when a message is received. • ExceptionListener - The exception strategy to use for the entire model. The exception strategy is used to handle any exceptions that occur when a component is processing a message. • lifecycleAdapterFactory - This is used by the model to create lifecycle adapters which are needed to translate Mule lifecycle event into events that UMO components registered with the model understand. • registerComponent() - This method accepts a UMODescriptor and registers that component with the Mule manager. The Mule manager handles constructing the component at run time. There is a complementary method called unregisterComponent() that performs the opposite task and there is a helper method called isComponentRegistered() that checks to see if a component with a particular name is registered or not. • getDescriptor() - returns a UMODescriptor for a specific component. • stopComponent() - stops the specified component from processing. • startComponent() - starts the specified component and allows it to continue processing • pauseComponent() - allows you to temporarily halt a component's processing. Unlike stopComponent(), messages from the inbound endpoints will still be consumed as the inbound flow stage will be able to queue these messages for processing. • resumeComponent() - resumes a component that had been paused. For a complete list of fields and methods, see; http://www.muleumo.org/docs/apidocs/org/mule/umo/ model/UMOModel.html An abstract class that implements this interface and which is the parent for all models is org.mule.impl.model.AbstractModel.
Entry Point Resolver Defined by the org.mule.umo.model.UMOEntryPointResolver interface, an entry point resolver is used to determine what method to invoke on an UMO component when event is received for it's consumption. There is a DynamicEntryPointResolver that is used if no other is configured on the model (see the Configuration Guide for more information). The DynamicEntryPointResolver provides entry point resolution for common usage, the steps it takes are 1. Checks to see if the component implements the org.mule.umo.lifecycle.Callable lifecycle interface, then the onCall(UMOEventContext) method will be used to receive the event.
Document generated by Confluence on Apr 24, 2008 08:11
Page 155
2. If the component has a transformer configured for it, the return type for the transformer will be matched against methods on the component to see if there is a method that accepts the transformer return type. If so this event will be used. Note if there is more than one match, an exception will be thrown. 3. If there is a method on the component that accepts an org.mule.umo.UMOEventContext . If so this event will be used. Note if there is more than one match, an exception will be thrown. 4. The last check determines if there are any methods on the component that accept a java.util.Event. If so this event will be used. Note if there is more than one match, an exception will be thrown. 5. If none of the above find a match an exception will be thrown and the component registration will fail. Of course there are many scenarios where the DynamicEntryPointResolver is suitable. For example, if you are migrating from another framework you may want to restrict (such as org.mule.model.CallableEntryPointResolver that only accepts components that extend org.mule.umo.lifecycle.Callable ) or change the way the entry point is resolved. To implement a custom Entry Point Resolver the org.mule.model.EntryPointResolver must be implemented.
Lifecycle Adapter Defined by the org.mule.umo.lifecycle.UMOLifecycleAdapter interface, the lifecycle adapter is responsible for mapping the mule component lifecycle to the underlying component. The DefaultLifecycleAdapter simply delegates lifecycle events to the component where the component implements zero or more UMO lifecycle interfaces. Clearly this isn't suitable for existing components that you want to be managed by Mule, as they will most likely have their own lifecycle methods that will still need to be invoked in the Mule framework. Luckily, the org.mule.umo.lifecycle.LifecycleAdapter is very simple to implement. Lifecycle adapters are configured using an implementation of org.mule.umo.lifecycle.UMOLifecycleAdapterFactory . The factory is declared in the configuration of the model. A default is provided DefaultLifecycleAdapterFactory.
Mule Models Mule provides the following models: • SEDA is the default model (Staged Event Driven Architecture) • SEDA optimized is similar to the SEDA model but contains certain assumptions that help improve performance. • The Direct model is a very simple one where there is no threading or pooling of components • The Pipeline model is similar to the Direct model but contains certain assumptions that help improve performance. • Streaming allows for the streaming of large amounts of data • Inherited is an indication that you wish to inherit a model from a different configuration file. • Custom means that you will implement your own model
SEDA Optimised Model The org.mule.impl.model.seda.optimised.OptimisedSedaModel model enhances the default SEDA model by assuming that all the components which it hosts implement the Callable interface. This avoids the need for the costly reflection and introspection on hosted beans. If a hosted component does not implement Callable, then a java.lang.IllegalArgumentException is raised. Since this model assumes that SEDA (and therefore asynchronous processing) will be used throughout, both reply-to properties and response-routers are ignored.
The Direct Model The org.mule.impl.model.direct.DirectModel model does not have any of the advantages of the SEDA model. There is no thread management and components are not pooled to service incoming messages, even if the message flow is asynchronous. Parts of this model can be simulated when using the SEDA model; e.g., if you want to eliminate the component pool, you can set a <mule-descriptor>'s singleton attribute to true to make sure that only one instance of your component is loaded at run time.
Document generated by Confluence on Apr 24, 2008 08:11
Page 156
All other features, like the DynamicEntryPointResolver, are inherited from the AbstractModel.
The Pipeline Model The org.mule.impl.model.pipeline.PipelineModel class enhances the Direct model by assuming that all the components which it hosts implement the Callable interface. This avoids the need for the costly reflection and introspection on hosted beans. If a hosted component does not implement Callable, then a org.mule.umo.lifecycle.InitialisationException is raised.
The Streaming Model Streaming allows you to stream data through Mule, or through service components rather than having to read the whole item into memory, leading to more efficient processing of large files or records. This technique is supported across TCP, File, HTTP and SOAP (Xfire) although support for FTP will be available shortly. As of 1.4, "streaming" has been added as a type to the Mule model. Your Mule endpoints will need to understand how to stream data - you can configure this by setting the "streaming" attribute to true for each endpoint.
The Inherited Model The "inherited" type is not really a model but an indication to Mule that the model type was defined in a previous configuration file. Inside the first configuration file, you can define your model and all it's properties, etc. Inside secondary configuration files, you can either declare separate and independent models or else you can simply inherit the model used in the first configuration file. This allows you to split your Mule configuration into multiple files. The root element will still be <mule-configuration> as is shown in the next slide. Note that configuration files are loaded sequentially, so the master configuration has to be passed to the configuration builder class first, e.g., java -cp ... org.mule.MuleServer -config conf/mule-config.xml, conf/mule-component2-config.xml
The Custom Model The "custom" type allows you to use a model of your own, should you wish to implement one of your own. You will need to set the className attribute to point to your model, or you can use the ref attribute if your model is declared inside some other container, like Spring. If you do not set the className attribute, an IllegalArgumentException will be raised. You can implement your own model by inheriting from the AbstractModel class which handles certain default behaviour, or you can code your own and implement the UMOModel interface instead.
Document generated by Confluence on Apr 24, 2008 08:11
Page 157
Mule Agents This page last changed on Jan 30, 2008 by ross.
Agents are services that are associated or used by Mule but not a Mule managed component. For example Mule's Jmx support is implemented and configued using agents. The useful thing about agents is they have the same lifecycle as the Mule instance they are registered with, so you can initialise and destroy resources when the Mule instance starts or is disposed. To write your own agent you need to implement org.mule.umo.UMOAgent and register your agent with the UMOManager. In the Mule xml configuration use the 'agents' element to register an agent
or programmatically UMOAgent agent = new MyAgent(); MuleManager.getInstance().registerAgent(agent);
Document generated by Confluence on Apr 24, 2008 08:11
Page 158
Mule and .NET Webservices FAQ This page last changed on Jan 30, 2008 by ross.
Mule and .NET Web Services FAQ The following is a short FAQ about how to use Mule to communicate with .NET Web Services.
Calling A .NET Web Service How can I call a .NET Web Service from Mule? The request and paramters used to access a .NET Web Service have to be sent as SOAP messages. For this reason you can generally use either Axis or Xfire transports to do so. View the following cookbook entry to view how this can be done. http://mule.mulesource.org/display/MULE/Calling+.NET+web-service+using+Axis http://mule.mulesource.org/display/MULE/Calling+.NET+Web+Services+using+XFire
Authentication and other Security Features: There are 3 ways to secure a Web Service: 1. Via HTTP web server 2. Via authentication tokens in the SOAP header 3. Via WS-Security.
How does mule handle the authentication for each of the described methods above? 1. Via Http Web Server: If you are running Mule on a Web App you could literally configure the web server to use security, i.e. by setting security configuration on the web.xml and in the server's configuration file. Alternatively, to secure a Web Service running on Mule (with Mule being the Server), you could set the HttpBasicAuthenticationFilter on the web service component. Any call made to the web service would have to pass through the filter which delegates the authentication to Acegi. See: http://mule.mulesource.org/display/MULE/Mule+Security Another alternative would be to use Https where certificates are used for authentication. 2. Using Custom SOAP headers: Sending authentication tokens through SOAP headers shouldn't be problematic provided that there is an authentication provider established that is able to understand the headers and perform the authentication. 3. Mule uses Apache's WSS4J classes (and Xfire's adaptations) for WS-Security simply by setting the required handlers on the connector. For more details please look at the doc about how to configure Mule to use WS-Security on the following link: http://mule.mulesource.org/display/MULE/Web+Service+Security\\
Document generated by Confluence on Apr 24, 2008 08:11
Page 159
Does mule provides a facility for NTLM authentication to .NET web services? At the moment it doesn't.
How do I pass authentication information to a web service configured on mule? Method 1: pass them in the URL, eg: *http://name:password@localhost:8080/MyService* Method 2: set the authentication items as properties when using the MuleClient Method 3: create headers containing the authentication items and send them as properties when using the MuleClient
Document generated by Confluence on Apr 24, 2008 08:11
Page 160
Mule Client This page last changed on Jan 30, 2008 by ross.
The Mule Client is a simple interface for java clients to send and receive events from a Mule Server and other applications. The client serves the following functions • • • •
Sending and receiving events to/from a local mule server Sending and receiving events to/from a remote mule server Communicating with other applications using any Mule transport Registering and unregistering components in a Mule server
Using Send and Dispatch In most Mule applications events are triggered by some external occurrence such as a message being received on a queue or file being copied to a directory. The Mule client allows the user to send and receive events programmatically. For example, to send a Jms message to any application, Mule component or otherwise, listening on my.queue MuleClient client = new MuleClient(); client.dispatch("jms://my.queue", "Message Payload" null);
To make a regular client/server synchronous call the send() method can be used MuleClient client = new MuleClient(); UMOMessage result = client.send("tcp://localhost:3456", "Message Payload", null);
Making synchronous calls asynchronously Mule Client allows you to make synchronous calls without blocking using the sendAsync() method. MuleClient client = new MuleClient(); FutureMessageResult result = client.sendAsync("http://localhost:8881", "Message Payload", null); //Do some more stuff here if(result.isready()) { Object payload = result.getMessage().getPayload(); }
The client send(), sendAsync() and dispatch() methods expect 3 arguments 1. The mule url endpoint - This is any valid Mule Endpoint used to determine the transport, endpoint and other information about delivery of the event 2. The event payload - this can be any object 3. Properties - any properties or meta-data to associate with the event
MuleClient as a Web Services Client The Mule client can be used as a web services client to make soap requests using popular soap implementations such as Web Methods Glue and Apache Axis. MuleClient client = new MuleClient(); //Arguments for the addPerson WS method String[] args = new String[]{"Ross", "Mason"}; //Call the web service client.dispatch("axis:http://localhost:38004/PersonService?method=addPerson", args, null); //Call another method to look up the newly added person UMOMessage result = client.send ("axis:http://localhost:38004/PersonService?method=getPerson", "Ross", null);
Document generated by Confluence on Apr 24, 2008 08:11
Page 161
//A person object is returned and all type mapping is handled for you Person person (Person)result.getPayload(); System.out.println(person.toString());
Soap Provider The Mule Soap Provider supports Web Methods Glue and Apache Axis. For more information about Mule Axis support go here, for more information about MUle Glue support go here.
Performing Request-Response calls To receive events the client has a receive method, i.e. MuleClient client = new MuleClient(); UMOMessage result = client.receive("pop3://ross:[email protected]", 5000);
This will attempt to receive a message from a mailbox called ross on mail.muleumo.org and will return after 5 seconds if no message was received. Tip Calling receive() will work for all Mule supported transports, but it is more usual to make request-response calls where there is a store to be queried such as a queue, file directory, or some other repository or where a call will be executed based on the receive and a result returned such as making a soap call.
Sending events to components directly The client also provides a convenient way to send an event directly to a component without needing to use a provider, this can be very useful in testing, but also when triggering events from a Jsp page or script. To dispatch an event directly to your stock quote component called StockManager you would do the following MuleClient client = new MuleClient(); UMOMessage result = client.sendDirect("StockManager", null, "give me the price of XXX", null); StockQuote sq = (StockQuote)result.getPayload();
Note that the call is sendDirect, this tells the client to go directly to the component and not through a provider. As such there will be no transformers configured for this call. You can specify a commaseparated list of transformers to use in the second argument of this call.
The Client Remote Dispatcher The client can connect to, send and receive events from a remote Mule server. using the previous example MuleClient client = new MuleClient(); RemoteDispatcher dispatcher = client.getRemoteDispatcher("tcp://localhost:60504"); UMOMessage result = dispatcher.sendRemote("StockManager", null, "give me the price of XXX", null); StockQuote sq = (StockQuote)result.getPayload();
The Mule client will execute the StockManager component on a remote Mule server, returning the result to the client. Mule handles all the call marshalling. The first null argument is a optional string of comma separated transformers to use on the result message. The second null argument is properties associated with the request. Often you will not want to wait for the result to be returned from the remote server, so you can use the asyncRemote() method that returns a FutureMessageResult. MuleClient client = new MuleClient(); RemoteDispatcher dispatcher = client.getRemoteDispatcher("tcp://localhost:60504");
Document generated by Confluence on Apr 24, 2008 08:11
Page 162
FutureMessageResult result = dispatcher.asyncRemote("StockManager", null, "give me the price of XXX", null); //do some other stuff StockQuote sq = (StockQuote)result.getMessage(1000).getPayload();
The result returned is a placeholder for the real result message when the call returns. By using a future result you can continue with other tasks while the remote call executes. Calling getMessage() will block until the call returns. Optionally you can specify a timeout of how long to wait (shown in the example). You can also check if the call has returned using result.isReady(). By default, the Mule server will listen on tcp://localhost:60504, if you want the client to use a different server location you can specify it when you create the remote dispatcherMuleClient client = new MuleClient(); RemoteDispatcher dispatcher = client.getRemoteDispatcher("http://228.8.9.10:6677");
Configuring the MuleManager When the manager is running asynchronous, making a synchronous client call i.e. client.send(..) the result event will always be null, as internally, Mule will be making all calls asynchronously. You can determine if Mule is running synchronously by calling boolean sync = MuleManager.getConfiguration().isSynchronous();
Associating properties with the Message So far in all the examples we have set the properties argument to null. Properties can be arbitrary, i.e. to pass around custom meta-data with your events or they can be transport specific. The following example demonstrates an asynchronous request/response using Jms and the Jms specific JMSReplyTo property. //create the client instance MuleClient client = new MuleClient(); //create properties to associate with the event Map props = new HashMap(); //Set the JMSReplyTo property, this is where the response message will be sent props.put("JMSReplyTo", "replyTo.queue"); //dispatch our message asynchronously client.dispatch("jms://test.queue", "Test Client Dispatch message", props); //Receive the return message on the replyTo.queue UMOMessage message = client.receive("jms://replyTo.queue", 5000); //This the message sent back from the first component to process our event System.out.println(message.getPayload());
This example demonstrates how to send a mail message using the client and setting the subject and and from address as properties on call. Tip The Mule Client doesn't have to be used to talk to a Mule Server. It doesn't matter what application is receiving requests made by the client. //create the client instance MuleClient client = new MuleClient(); //create properties to associate with the event Map props = new HashMap();
Document generated by Confluence on Apr 24, 2008 08:11
Page 163
//Set the Subject and From address property. These properties are defined by the [Smtp Provider]. props.put("subject", "A message from mule"); props.put("fromAddress", "[email protected]"); //dispatch our message asynchronously client.dispatch("smtp://ross:[email protected]? [email protected]", "Test Client Dispatch message", props);
Or to omit the smtp connection information from the url you can configure an smtp connector in Mule and just use client.dispatch("smtp://[email protected]", "Test Client Dispatch message", props);
Document generated by Confluence on Apr 24, 2008 08:11
Page 164
Mule Configuration Overview This page last changed on Jan 30, 2008 by ross.
Mule's configuration is extensible in that there is no mandate about how the configuration of Mule should be stored or the format of the configuration. The only requirement is that once mule is configured an instance of UMOManager should be available by calling MuleManager.getInstance().
Quick Start To start a Mule instance from the command line or script using a Mule XML configuration file, use the following java -cp ... org.mule.MuleServer -config ../conf/mule-config.xml
This will use the default org.mule.config.MuleXmlconfigurationBuilder to process a configuration file called ../conf/mule-config.xml. The equivalent code example would be MuleXmlConfigurationBuilder builder = new MuleXmlConfigurationBuilder(); builder.configure("../conf/mule-config.xml");
Loading Multiple Configurations Developers can specify a comma-separated list of XML configuration files to load i.e. java -cp ... org.mule.MuleServer -config ../conf/mule-config.xml, ../conf/mule-component1-config.xml,../conf/mule-component2-config.xml
The equivalent code example would be MuleXmlConfigurationBuilder builder = new MuleXmlConfigurationBuilder(); String configs="../conf/mule-config.xml, ../conf/mule-component1-config.xml,../conf/mule-component2-config.xml"; builder.configure(configs);
The configuration files are loaded in sequence so global configuration files should be loaded first. Other Configuration Builders are available, such as Spring and Groovy.
Configuration Builders To configure Mule a Configuration builder is used. This is a simple interface that the Mule server can invoke on start up. You can define your own configuration depending on how you want to configure Mule. Mule currently comes with three configuration builders, the default Mule xml Configuration builder, Spring and Groovybuilders. However, it would be straight forward to implement other builders, say a Pico builder or BeanShell builder. To tell Mule to use a particular builder you must specify the fully qualified class name as a command line argument using the -builder token and define the configuration resources for the builder using the config token. For example to use the Spring builder, you would define your command something like this java -cp ... org.mule.MuleServer -builder org.mule.extras.spring.config.SpringConfigurationBuilder -config ../conf/applicationContext.xml
Mule Xml Configuration By default Mule's configuration is an XML file, usually called mule-config.xml. This file has a corresponding DTD called mule-configuration.dtd which is included in the distribution.
Document generated by Confluence on Apr 24, 2008 08:11
Page 165
The root of all configurable elements in Mule is the UMOManger, which defines a hierarchy of configurable objects. The general structure is described in the figure below, though for a complete picture of Mule configuration refer to the Mule Configuration Reference guide.
Spring Configuration As well as the default Mule XML configuration, a Spring configuration builder is also included with the Mule distribution. This builder enables the developer to configure all Mule elements through Spring, which means any Mule objects can leverage Spring's AOP and transaction interceptors, DAO support, etc. For more information about configuring Mule with Spring see the Spring chapter.
Rolling your own configuration Mule currently comes with two configuration builders, the default Mule XML builder and a Spring builder. Writing your own configuration builder is a simple task of writing an instance of org.mule.config.ConfigurationBuilder. This interface defines a single method public UMOManager configureMule(String configResources) throws ConfigurationException;
where configResources can be anything from a JNDI location, a URL or a filename (or comma separated list of filenames) on the classpath or file system. It's up to the Configuration Builder how it uses the configResources to construct an instance of UMOManager and pass it back to the server. Some future Configuration Builders may include a PicoContainer assembler, a Bean Shell builder and JNDI builder. See also Configuration Options for details about how to configure the actual Mule instance.
Overloading the UMOManager The UMOManager interface defines the central location for all configured objects. Mule defines a default implementation of the UMOManager, the MuleManager. However, it is possible to provide your own implementation of UMOManager. There are two ways to use your own UMOManager 1. Set the VM parameter to a fully qualified class name of the UMOManager you want to use, i.e. Dorg.mule.umo.UMOManager=com.foo.MyManager. 2. Use the MuleManager.setInstance(...) method. This method is useful when defining your own ConfigurationBuilder; this is discussed more in the next section.
Document generated by Confluence on Apr 24, 2008 08:11
Page 166
Mule Endpoint URIs This page last changed on Jan 30, 2008 by ross.
Mule Endpoint URIs are any valid URI and describes how to connect to the underlying transport. Most connectors in Mule can be created from an endpoint uri except where not enough connection information can be expressed clearly in a URI, such as jms connection properties. Endpoint URIs are set on Mule Endpoints which manage other connection instance information such as filters and transactions. Mule Endpoint URIs usually appear in one of the following forms, though other provider implementations can introduce their own schemes.
scheme://[MULE:host][MULE::port]/[MULE:endpoint name]/[MULE:address]? [MULE:params] The scheme must always be set. The host and port are set for endpoints that use unwrapped socket based communications such as the TCP, UDP, HTTP or multicast.
udp://localhost:65432 If host and port are set it is unlikely that a provider would be set, though by setting the provider name would cause a specific provider to be used with the host and port.
tcp://localhost:3212/myTcpEndpoint This would use the pre-configured endpoint "myTcpEndpoint" using tcp://localhost:3212 as the endpoint URI.
scheme://[MULE:endpoint name]/[MULE:address]?[MULE:params] The endpoint name is a pre-configured endpoint to use. Endpoints can be local to the component or global and visible to all components in the container. Endpoints are configuration objects that group a connector, transformers and an endpoint URI together along with filter and transaction information. For more information see Mule Endpoints.
jms://jmsEndpoint/test.queue The URI specifies that a pre-configured endpoint called jmsEndpoint should be used and the address on the endpoint should be set to 'test.queue'. If you want to use the endpoint 'as is' just omit the address but leave the tailing forward slash i.e.
jms://jmsEndpoint/
scheme://[MULE:username][MULE::password]@[MULE:host][MULE::port]? [MULE:params] The user name and password are used to log in to the remote server specified by the host and port params. The pop3 and SMTP connectors use this format or URI.
pop3://ross:[email protected] smtp://ross:[email protected]
Document generated by Confluence on Apr 24, 2008 08:11
Page 167
scheme://[MULE:address]?[MULE:params] Here we only define a protocol and an address. This tells Mule to go and get a connector that handles the specified scheme or create one if needed, create a new endpoint and use the specified address.
vm://my.queue
URI Parameters So far we haven't talked about the "params" part on the URI. There are two types of params that can be set 1. Known Mule params that control the way the endpoint is configured, such as whether to force a connector to be created or to specify transformers for the endpoint. 2. Properties to be set on the connector or to be associated with the provider. This allows you to set properties on a connector used by this endpoint. Additionally, all properties will be associated with the provider, so you can mix connector and provider properties. If you haven't already, I recommend having a look at Mule Endpoints for more information. Known Parameters
Property
Description
createConnector
Determines if the connector for this endpoint should be created. Possible values are* IF_NEEDED - (default) will create the connector if there is none configured on the MuleManager for this protocol * ALWAYS - Always create a new connector for this endpoint * NEVER - do not create a connector and throw a ConnectorFactoryException if there is no connector configured for the URI protocol.
connector
The name of an existing connector to use for this endpoint URI
transformers
Defines a comma separated list of transformers to configure on the endpoint
endpointName
Some endpoints such as file:// cannot use the above notation for specifying a provider name in the path. In such cases this parameter can be used. If an endpoint is generated from a URI with this parameter, the name of the endpoint will be set to this value
address
Specifying an address param will explicitly set the endpoint address to that value and ignore all other info in the URI.
file:///C:/temp?endpointName=myFileEndpoint&transformers=FileToString,XmlToDom udp://localhost:38543?createConnector=ALWAYS jms://jmsEndpoint/topic:my.topic?createConnector=NEVER
Document generated by Confluence on Apr 24, 2008 08:11
Page 168
Other Parameters Any other parameters set on the URI will be set on the connector if a connector is created and also set on the endpoint itself as properties.
Custom Endpoints Each connector can define its own EndpointBuilder. This builder is used by the MuleEndpointURI to compose the URI into an endpoint that the connector understands. There are default EndpointBuilder implementations that most connectors can use, such as socket, resource name and URL builders, plus there are special cases such as file URLs where the provider cannot be expressed in the URI path.
Endpoint Encoding When using XML configuration certain character entities defined in the W3C SGML specification need to be escaped to their SGML code. The most relevant are listed here. Don't forget to remove the space before the ';'. For characters such as > < " % # that notation will be resolved and cause the constructor for the URI to throw an exception. To use one of ><"%#, a user can specify %HEXNUMBER
Text code
Numerical code
What it looks like
Description, extras
%22
#34
"
quotation mark = APL quote, U+0022 ISONEW
& ;
#38
&
ampersand, U+0026 ISOnum
%3C
#60
<
less-than sign, U+003C ISOnum
%3E
#62
>
greater-than sign, U +003E ISOnum
%23
#37
%
percentage sign, U +0023 ISOnum
%25
#35
#
hash sign, U+0025 ISOnum
Document generated by Confluence on Apr 24, 2008 08:11
Page 169
Mule Endpoints This page last changed on Jan 30, 2008 by ross.
Endpoints are used to connect to components in the server and external systems or to each other locally or over the network. An Endpoint is a specific channel through which two parties can communicate. A provider can be used to send or receive events from disparate systems, for example, a purchasing component may receive an order request over Http. Once the order has been processed by the component a Jms message may be sent over a topic to notify an auditing system and response sent back over Http. An Endpoint consists of the following elements 1. Endpoint URI - at the very least an endpoint will have an Endpoint URI; an address that is used to reference a resource or service either locally or remotely. This must be a valid URI. 2. Connector - used to connect to the underlying transport. Often the connector is not explicitly set, instead the connector for the endpoint is found based on the scheme of the Endpoint URI. 3. Filter - a filter to apply to messages being recieved on the endpoint. See the Transports Guide for information about filtering support for a specific transport. 4. Transaction - Transactions can be begun or committed when an event is received or sent. See the Transports Guide for information about transaction support for a specific transport. 5. Properties - These can be set to override certain properties on the connector for this endpoint instance. For example, when using a smtp endpoint you may want to overload the from address. Essentially, an endpoint is a configuration entity used to control how events are sent and received in Mule. Mule also has a notion of 'Transport Providers' or 'Providers' that do the actual work of sending a recieving events over various protocols.
Transport Elements A Transport Provider is in fact a composite of a set of objects used to connect and communicate with the underlying system. The elements of a Transport Provider are • • • •
Connector, is responsible for connecting to the underlying system Message Receiver, is used to receive events from the system. Connector Dispatchers, are responsible for passing data to the system. Transformers are Transport specific transformers used to convert data received and data sent.
The following shows how an endpoint and underlying Transport components fit together. Cannot resolve external resource into attachment.
Endpoint Usage Endpoints can be configured on various objects in Mule • Inbound Routers - configured on Components and allow one or more endpoints to be registered on a component. • Outbound Routers - configured on components and allow one or more outbound endpoints to be configured (with additional logic for controlling which endpoints are used for an event. See Message Routers) • Catch all strategies - allow a single 'catch-all' endpoint to be configured for a router. • Components - for convenience a single inbound and outbound endpoint can be set on the component directly, which is a little eaiser than configuring routers. • Exception Strategies - A single endpoint can be configured on an exception strategy to all events to be sent to an error endpoint.
Endpoints Scope Endpoints can have two scopes; Global scope and local scope.
Document generated by Confluence on Apr 24, 2008 08:11
Page 170
Global Scope An Endpoint is considered to have Global scope when it is registered on the MuleManager instance or set in the Mule configuration as a . Global endpoints can be referenced anywhere in your code. It's important to note that when an endpoint is requested from the UMOManager using the lookupEndpoint() method, Mule actually returns a clone of the Endpoint. This allows client code to change any attibutes on the endpoint without affecting other objects in the system that also use the endpoint. The exception to this is the connector which is not cloned and setting properties on the connector at run-time may cause unpredictable results and is not recommended unless the documentation for the Transport says otherwise.
Local Scope These are endpoints that are configured or set on the objects that have Endpoints, but are not registered with the MuleManager.
More Information For more information about configuring endpoint see Configuring Endpoints. For reference about Transport Provider implementations see the Transports Guide.
Document generated by Confluence on Apr 24, 2008 08:11
Page 171
Mule Security This page last changed on Jan 30, 2008 by ross.
Mule allows you to authenticate requests via endpoints using transport specific or generic authentication methods. It also allows you to control method-level authorisation on your Service Components. This section covers the following topics • Configuring the Security Manager • Configuring Security Filters on Endpoint • Configuring Encryption Strategies Once you've read this page the following will also be of interest for people wanting to enable authorisation on Service components or use security technologies such as JAAS, PGP or CAS • • • • •
Jaas Security PGP Security Acegi Security Component Authorization Using Acegi Setting up LDAP Provider for Acegi
Security Manager The Security Manager responsible for Authenticating requests based on one or more Security Providers configured on the security Manager. A Security Provider can authenticate against a variety of repositories such as Ldap, JAAS, database (dao) and third-party security frameworks such as CAS (Yale Central Authentication Service). Mule has a default security implementation that uses Acegi Security. It provides a number of Security providers out of the box including the ones listed above. Acegi is a Spring-based implementation and also provides interceptors that can enable method-level authorisation on your service components. For spring users this means a unified approach to their application security. For Mule users not using Spring, using Acegi will impose no spring requirements on your application code. All security is provided via the Mule security API, so custom implementations can easily be plugged in.
Configuration The following describes how to configure a single Security provider on Mule, in this case an in-memory DAO. <mule-configuration> <security-manager> <security-provider name="memory-dao" className="org.mule.extras.acegi.AcegiProviderAdapter"> <properties> ....
Note that the 'delegate' property is a container property meaning we need a container to get it from. Here we configure a Spring Container Context to load our Security Providers from. you can set multiple security-provider elements. <properties> <property name="configFile" value="securityContext.xml"/>
The Spring Acegi configuration is where the real Security Provider configuration occurs.
Document generated by Confluence on Apr 24, 2008 08:11
Page 172
<property name="authenticationDao"> <property name="userMap"> ross=ross,ROLE_ADMIN anon=anon,ROLE_ANONYMOUS
Here we have a static DAO Security Provider that allows user credentials to be set in memory with two users; ross and anon.
Encryption strategies The Security Manager can be configured with one or more Encryption strategies that can then be used by encryption transformers, Security filters or secure Transport providers such as ssl or https. These Encryption strategies can greatly simplify configuration for secure messaging as they can be shared across components. <security-manager> <encryption-strategy name="PBE" className="org.mule.impl.security.PasswordBasedEncryptionStrategy"> <properties> <property name="password" value="mule"/>
This strategy can then be referenced by other components in the system such as filters or transformers. <properties> <property name="strategyName" value="PBE"/>
Security Filters Security filters can be configured on an object to either authenticate inbound requests or attach credentials to outbound requests.
Endpoint Security Filter As the name suggests, these types of filters are configured on endpoints. To configure a Http Basic Auth filter on a http endpoint use the following <endpoint address="http://localhost:4567"> <security-filter className="org.mule.extras.acegi.filters.http.HttpBasicAuthenticationFilter"> <properties>
Document generated by Confluence on Apr 24, 2008 08:11
Page 173
<property name="realm" value="mule-realm"/>
When a request is received the Authentication header will be read from the request and authenticated against all Security Providers on the Security Manager. If you only want to validate on certain ones you can supply a comma-separated list of Security Provider names. <endpoint address="http://localhost:4567"> <security-filter useProviders="default,another" className="org.mule.extras.acegi.filters.http.HttpBasicAuthenticationFilter"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 174
Component Authorization Using Acegi This page last changed on Jan 30, 2008 by ross.
This section describes how you can configure method level authorization on your components so that users with different roles can only invoke certain service methods.
Securing Services Components To secure MethodInvocations, developers need to add a properly configured MethodSecurityInterceptor into the application context. The beans requiring security are chained into the interceptor. This chaining is accomplished using Spring's ProxyFactoryBean or BeanNameAutoProxyCreator. Alternatively, Acegi Security provides a MethodDefinitionSourceAdvisor which may be used with Spring's DefaultAdvisorAutoProxyCreator to automatically chain the security interceptor in front of any beans defined against the MethodSecurityInterceptor. Apart from the daoAuthenticationProvider and inMemoryDaoImpl beans configured above, the following beans must be configured: • • • • •
MethodSecurityInterceptor AuthenticationManager AccessDecisionManager AutoProxyCreator RoleVoter
The MethodSecurityInterceptor The MethodSecurityInterceptor is configured with a reference to an: • AuthenticationManager • AccessDecisionManager The following is a Security Interceptor for intercepting calls made to the methods of a component called myComponent. myComponent has an interface (myComponentIfc) that defines two methods: delete and writeSomething. Roles are set on these methods as seen below in the property objectDefinitionSource. <property name="authenticationManager"> <property name="accessDecisionManager"> <property name="objectDefinitionSource"> com.foo.myComponentIfc.delete=ROLE_ADMIN com.foo.myComponentIfc.writeSomething=ROLE_ANONYMOUS
The AuthenticationManager An AuthenticationManager is responsible for passing requests through a chain of AuthenticationProviders. <property name= "providers"> <list>
Document generated by Confluence on Apr 24, 2008 08:11
Page 175
The AccessDecisionManager This bean specifies that a user can access the protected methods if they have any one of the roles specified in the objectDefinitionSource. <property name="decisionVoters"> <list>
The AutoProxyCreator This bean defines a proxy for the protected bean. When an application asks Spring for a myComponent bean it will get this proxy instead. <property name='interceptorNames'> <list> myComponentSecurity <property name='beanNames'> <list> myComponent <property name='proxyTargetClass' value="true"/>
When using BeanNameAutoProxyCreator to create the required proxy for security, the configuration must contain the property proxyTargetClass set to true. Otherwise, the method passed to MethodSecurityInterceptor.invoke is the proxy's caller, not the proxy's target.
The RoleVoter The RoleVoter class will vote if any ConfigAttribute begins with ROLE_. The RoleVoter is case sensitive on comparisons as well as the ROLE_ prefix. • It will vote to grant access if there is a GrantedAuthority which returns a String representation (via the getAuthority() method) exactly equal to one or more ConfigAttributes starting with ROLE_. • If there is no exact match of any ConfigAttribute starting with ROLE_, the RoleVoter will vote to deny access. • If no ConfigAttribute begins with ROLE_, the voter will abstain.
Setting Security Properties on the Security Provider We can put any additional properties we may wish to add to the Security Provider in the securityProperties map. For instance this map can be used to change Acegi's default security strategy into one of the following... MODE_THREADLOCAL which allows the authentication to be set on the current thread (this is the defualt strategy used by Acegi). MODE_INHERITABLETHREADLOCAL which allows authentication to be inherited from the parent thread MODE_GLOBAL which allows the authentication to be set on all threads
Document generated by Confluence on Apr 24, 2008 08:11
Page 176
Securing Components in Asynchronous Systems The use of Acegi's security strategies is particularly useful when using an asynchronous system since we have to add a property on the Security Provider in order for the authentication to be set on more than one thread. In this case we would use the MODE_GLOBAL as seen in the example below. <security-provider name="memory-dao" className="org.mule.extras.acegi.AcegiProviderAdapter"> <properties> <map name="securityProperties"> <property name="securityMode" value="MODE_GLOBAL"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 177
Setting up LDAP Provider for Acegi This page last changed on Jan 30, 2008 by ross.
In the Mule Security page, we discuss about how you can configure an in-memory DAO provider. In this documentation, we will talk about how you can configure an Acegi's LDAP provider, which can be: • Used by Mule, as its security provider via AcegiProviderAdapter • Used by Acegi/Spring to perform Component Authorization • etc.
Declaring the Beans Basically, you will need to setup two beans in Spring, an InitialDirContextFactory and an LdapAuthenticationProvider. The InitialDirContextFactory is the access point for obtaining an LDAP context where the LdapAuthenticationProvider provides integration with the LDAP server. As an example: <property name="managerDn"> cn=root,dc=com,dc=foobar <property name="managerPassword"> secret <property name="userDnPatterns"> <list> uid={0},ou=people ou=groups <property name="groupRoleAttribute"> cn <property name="searchSubtree"> true <property name="rolePrefix"> ROLE_ <property name="convertToUpperCase"> true
Document generated by Confluence on Apr 24, 2008 08:11
Page 178
Configuring Mule Security Provider The AcegiProviderAdapter delegates to an AuthenticationProvider such as the LdapAuthenticationProvider. <security-manager> <security-provider name="acegi-ldap" className="org.mule.extras.acegi.AcegiProviderAdapter"> <properties>
With the above configuration, you can achieve endpoint-level security and other security features in Mule which require one or more security providers.
Configuring MethodSecurityInterceptor The configuration for component authorization is similar with the one that we have discussed in this page. The one worth mentioning is the configuration of ObjectDefinitionSource, e.g. <property name="objectDefinitionSource"> org.mule.components.simple.EchoService.*=ROLE_MANAGERS
The roles are looked up by the DefaultLdapAuthoritiesPopulator which you configured in previous section. By default, a role is prefixed with ROLE_ and its value is extracted (and turned uppercase) from the LDAP attribute defined by the groupRoleAttribute.
Document generated by Confluence on Apr 24, 2008 08:11
Page 179
Mule Server Notifications This page last changed on Jan 30, 2008 by ross.
Mule has an internal notification mechanism which can be used to tap into server notification such as a Component being added, the Model being initialised or the Manager being started. These notifications can be useful to allow custom components such as Agents or Mule managed components to react to change in the server. Don't confuse these notifications with service events that mule manages between your components and external applications. These Server Notifications provide notifications between objects that comprise the Mule Server, where as service events are the business operations that your business services process.
There are currently 12 types of Server Notifications 1. Manager Notification - is fired when state changes on the Mule manager such as initialising, starting and stopping. 2. Model Notification - is fired when state changes on the Mule Model such as initialising, starting and stopping or components being registered or unregistered. 3. Component Notification - is fire when a particular component is started, stopped, paused, resumed. 4. Management Notification - is fired when monitored resources are low (not yet implemented) 5. Custom Notification - can be fired by objects themselves to custom notification listeners, and can be used to customise notifications on Agents, Components, connectors etc. 6. Admin Notification - is fired when requests are received by the Mule Admin agent. These are usually trigged by MuleClient calls using the RemoteDispatcher, which proxies calls to a remote server. 7. Connection Notification - happen when a connector attempts to connect to its underlying resource. Notifications are fired when a connection is made, released or the connection attempt fails. 8. Message Notification - These notifications are fire when an event is sent or received in the system. These are very good for tracing, but are not enabled by default as there is a performance impact when using these. Read below to find out how to enable them. 9. Security Notification - is fired when a request is denied security access. 10. Space Monitor Notification - is fired from space implementations such as JavaSpaces, JCache or the Mule internal space implementation when events are fired into or out of a space. See [MULE:Spaces] for more information. 11. Exception Notification - is fired when an exception is thrown. (since 1.4.2) 12. Transaction Notification - happens during transaction life cycle. Notifications are fired after transaction has begun, committed or rolled back. (since 1.4.2) To become a server event listener objects can implement one of the following interfaces1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12.
org.mule.impl.internal.notifications.ManagerNotificationListener org.mule.impl.internal.notifications.ModelNotificationListener org.mule.impl.internal.notifications.ComponentNotificationListener org.mule.impl.internal.notifications.ManagementNotificationListener org.mule.impl.internal.notifications.CustomNotificationListener org.mule.impl.internal.notifications.AdminNotificationListener org.mule.impl.internal.notifications.ConnectionNotificationListener org.mule.impl.internal.notifications.MessageNotificationListener org.mule.impl.internal.notifications.SecurityNotificationListener org.mule.impl.internal.notifications.SpaceMonitorNotificationListener org.mule.impl.internal.notifications.ExceptionNotificationListener org.mule.impl.internal.notifications.TransactionNotificationListener
these all have a single method public void onNotification(UMOServerNotification notification);
Depending on the listener implemented only certain events will be received, for example the object implements ManagerNotificationListener only events of type ManagerNotification will be received. Objects can implement more than one listener to receive more types of event. Listeners can be registered on the UMOManager -
Document generated by Confluence on Apr 24, 2008 08:11
Page 180
MuleManager.getInstance().registerListener(listener);
Each event has an action code that determines the type of event. The action code can be queried in the onEvent method to determine its type. To have an object do something when the Model initialises MyObject.java public class MyObject implements ModelNotificationListener { public MyObject() { MuleManager.getInstance().registerListener(this); } public void onNotification(UMOServerNotification notification) { if (notification.getAction() == ModelNotification.MODEL_INITIALISED) { system.out.println("The Model is initialised!"); } } }
Enabling MessageNotifications Message Notifications are very useful as they provide a snapshot of all information sent into and out of the the Mule Server. These notifications are fired when ever a message is received or sent. As you can imagine, these additional events will have some impact on performance so they are turned off by default. To enable these events you need to set the enableMessageEvents to true on the <mule-environmentproperties> i.e. <mule-environment-properties enableMessageEvents="true"/>
Firing Custom Notifications Custom Notifications can be fired by objects in Mule to notify custom listeners. For example a discovery Agent might fire a 'Client Found' event when a client connects. To fire a custom event use CustomNotification n = new CustomNotification("Hello"); MuleManager.getInstance().fireNotification(n);
Any objects implementing CustomNotificationListener will receive this event. It's a good idea to extend the CustomNotification and define actions for your custom event type. To use the Discovery Agent example above DiscoveryNotification n = new DiscoveryNotification(client, DiscoveryNotification.CLIENT_ADDED); MuleManager.getInstance().fireNotification(n);
Non-system objects in Mule can only fire Custom notifications through the manager, attempting to fire other events such as ModelNotification will cause an UnsupportedOperationException.
Using Event Subscriptions You can associate a subscription with an event listener so that only events the match the subscription will be passed to the listener. The subscription is a wildcard String expression that will be matched against the 'Resource ID' of the event (see the next section). So to register interest in Component events where the component is called MyService1 you can use MuleManager.getInstance().registerListener(listener, "MyService1");
Document generated by Confluence on Apr 24, 2008 08:11
Page 181
If you wanted to match all components with Service in the name you can use MuleManager.getInstance().registerListener(listener, "*Service*");
Notification payloads All notifications extend java.util.EventObject and the payload of the object can be accessed using the getSource() method. The following table describes the event payloads for each type of event.
Event
Payload Type
Resource ID
Description
ManagerNotification
UMOManager
Manager ID
The UMOManager instance. Equivilent to calling MuleManager.getInstance()
ModelNotification
UMOModel
Model Name
The UMOModel instance on the manager. Equivilent to calling MuleManager.getInstance().getModel
ComponentNotification
UMOComponent
Component Name
The component that caused this event to fire
ManagementNotification
not implemented
CustomNotification
Any object
Any String
The object type is custom to the object firing the event.
AdminNotification
UMOMessage
The request endpoint
The Admin request received
ConnectionNotification
UMOConnectable
.receiver(<endpointor message dispatcher uri>) that was connected
MessageNotification
UMOMessage
Component name
The message sent or received
SecurityNotification
SecurityException
The Exception Message
The security execption that occurred
SpaceMonitorNotification UMOSpace
Space name
The space that fired the notification. If there is a data item it will be available on the Notification using SpaceMonitorNotification.getItem()
ExceptionNotification
Throwable
Component Name
The component that caused this event to fire (since 1.4.2)
TransactionNotification
UMOTransaction
Component Name
The component that caused this event to fire (since 1.4.2)
not implemented
Notification Actions the following describes the actions for each Notification type.
Document generated by Confluence on Apr 24, 2008 08:11
Page 182
ManagerNotification
Action
Description
MANAGER_INITIALISNG
UMOManager.initialise() has been called but not executed
MANAGER_INITIALISED
The UMOManager has been initialised
MANAGER_STARTING
UMOManager.start() has been called but not executed
MANAGER_STARTED
The UMOManager has been started
MANAGER_STOPPING
UMOManager.stop() has been called but not executed
MANAGER_STOPPED
The UMOManager has been stopped
MANAGER_DISPOSING
UMOManager.dispose() has been called but not executed
MANAGER_DISPOSED
UMOManager is disposed
MANAGER_DISPOSING_CONNECTORS
Registered connectors are about to be disposed
MANAGER_DISPOSED_CONNECTORS
Connectors have been disposed
ModelNotification
Action
Description
MODEL_INITIALISING
The UMOModel.initialise() has been called but not executed
MODEL_INITIALISED
The UMOModel has been initialised
MODEL_INITIALISING_LISTENERS
Component Listeners are about to be registered on the connectors
MODEL_INITIALISED_LISTENERS
Component Listeners have been registered
MODEL_STARTING
UMOModel.start() has been called but not executed
MODEL_STARTED
The UMOModel has been started
MODEL_STOPPING
UMOModel.stop() has been called but not executed
MODEL_STOPPED
The UMOModel has been stopped
MODEL_DISPOSING
UMOModel.dispose() has been called but not executed
MODEL_DISPOSED
The UMOModel has been disposed
Document generated by Confluence on Apr 24, 2008 08:11
Page 183
ComponentNotification
Action
Description
COMPONENT_INITIALISED
The component has been initialised
COMPONENT_STARTED
The component has been started
COMPONENT_STOPPED
The component has been stopped
COMPONENT_PAUSED
The component has been paused
COMPONENT_RESUMED
The component has been resumed
COMPONENT_DISPOSED
The component has been disposed
ManagementNotification Not implemented yet CustomNotification
Action
Description
NULL_ACTION
An action has not been set on the event
AdminNotification
Action
Description
ACTION_RECEIVE
Is fired when a remote recieve call is made via the Mule MULE:Admin Agent.
ACTION_DISPATCH
Is fired when a remote asynchronous 'dispatch' call is made via the Mule MULE:Admin Agent.
ACTION_SEND
Is fired when a remote synchronous 'send' call is made via the Mule MULE:Admin Agent.
ACTION_INVOKE
Is fired when a remote call is made directly to a component via the Mule MULE:Admin Agent.
ConnectionNotification
Action
Description
CONNECTION_CONNECTED
Is fired when a connector makes a successful connection to its underlying resource.
CONNECTION_FAILED
Is fired when a make an unsuccessful connection attempt.
Document generated by Confluence on Apr 24, 2008 08:11
Page 184
CONNECTION_DISCONNECTED
Is fired when a connector disconnects from its resource. This could be triggered by network failure, Jmx or the server shutting down.
MessageNotification
Action
Description
MESSAGE_RECEIVED
Is fired when a message is received into the Mule instance.
MESSAGE_DISPATCHED
Is fired when a message is dispatched asynchronously from a Mule instance.
MESSAGE_SENT
Is fired when a message is sent synchronously from Mule instance.
MESSAGE_REQUESTED
Is fired when a message is requested via Mule instance, i.e. calling MuleClient.receive(...)
SecurityNotification
Action
Description
SECURITY_AUTHENTICATION_FAILED
Is fired when a message is received but authentication of the message failed.
SpaceNotificationNotification
Action
Description
SPACE_CREATED
Is fired when a new space is created.
SPACE_DISPOSED
Is fired when a space is disposed.
SPACE_ITEM_ADDED
Is fired when an item is added to the space.
SPACE_ITEM_REMOVED
Is fired when an item is removed from the space.
SPACE_ITEM_EXPIRED
Is fired when an item in a space expires.
SPACE_ITEM_MISS
Is fired when an item is requested from the space byut yeilds no result.
SPACE_LISTENER_ADDED
Is fired when a listener is registered for the space.
SPACE_LISTENER_REMOVED
Is fired when a listener is unregistered for the space.
ExceptionNotification
Action
Document generated by Confluence on Apr 24, 2008 08:11
Description
Page 185
EXCEPTION_ACTION
Is fired when an exception is thrown and handled by org.mule.impl.DefaultExceptionStrategy or its subclasses.
TransactionNotification
Action
Description
TRANSACTION_BEGAN
Is fired after beginning of transaction.
TRANSACTION_COMMITTED
Is fired after transaction committed.
TRANSACTION_ROLLEDBACK
Is fired after transaction rolled back.
Document generated by Confluence on Apr 24, 2008 08:11
Page 186
Object Containers This page last changed on Jan 30, 2008 by ross.
Mule can be configured to use and manage any object from external containers or Naming Directories such as Jndi, Ejb, Spring, Pico, Plexus, or HiveMind.
Supported Containers • Jndi Container - Look up objects in one ore more Jndi contexts. • EJB Session Beans - Manage Ejb Session beans as Mule components. • Spring Container - Use Spring beans as Mule components and to wire bean properties. • Pico Container Use PicoContainer objects as Mule components and to wire bean properties. • Plexus Container - Use Plexus objects as Mule components and to wire bean properties. • HiveMind Container - Use HiveMind objects as Mule components and to wire bean properties.
Configuring Containers You can configure zero or more containers in a single Mule instance using the element. <properties> <property name="java.naming.factory.initial" value="org.foo.jndi.InitialContextFactory"/>
This will configure a Jndi container. By default, when looking up an object Mule will search each of the containers in the order they are configured. Notice the name attribute; this is optional but allows you to reference a particular container when setting a container property (see below). Each type of container has its own default name such as 'jndi', 'ejb', 'spring', 'pico' or 'plexus' . The only time you might want to set the name attribute yourself is if you have 2 jndi containers that contain objects of the same name and you need to distinguish between the two.
Configuring Container Properties Managing Container objects Mule services can be objects configured in an object container. To expose a container objects as a Mule service you need to set the implmenetation attribute of the <mule-descriptor> element to the name of the object to look up. Optionally, You can also set the container attribute to specify which container to load the object from. <mule-descriptor name="MyComponent" implementation="myJndiObject" container="jndi"> ....
Container Properties Any object specifed in Mule Xml that has a <properties> element can reference objects in containers as properties. These are properties that are retrieved from a configured IoC or Naming container, such as Spring, Jndi or EJB. <properties>
Document generated by Confluence on Apr 24, 2008 08:11
Page 187
Attribute
Description
name
specifies the bean property name. If the object has methods setTestProperty(..) and getTestProperty() the property name is testProperty.
reference
The reference name of the object in the container.
required
Determines whether an exception is thrown if the object reference is not found in the container. The default is true.
container
An optional attribute that tells Mule only to look for the object in the specifed container, otherwise Mule will search all containers in the order they are configured.
Document generated by Confluence on Apr 24, 2008 08:11
Page 188
HiveMind Support This page last changed on Jan 30, 2008 by ross.
Now available on MuleForge.
Document generated by Confluence on Apr 24, 2008 08:11
Page 189
JNDI This page last changed on Jan 30, 2008 by ross.
Storing Mule objects in Jndi - How to store Mule instance configuration in a central directory. Jndi Container - How to expose Jndi contexts to Mule for looking up objects.
Document generated by Confluence on Apr 24, 2008 08:11
Page 190
Storing Mule objects in Jndi This page last changed on Jan 30, 2008 by ross.
Document generated by Confluence on Apr 24, 2008 08:11
Page 191
Jndi Container This page last changed on Jan 30, 2008 by ross.
The JndiContainerContext can be used to expose objects stored in Jndi as Mule components. To configure a Jndi container you need to add a element that uses the org.mule.impl.container.JndiContainerContext and set the Jndi environment properties. <properties> <map name="environment"> <property name="java.naming.factory.initial" value="org.foo.jndi.InitialContextFactory"/>
You can also omit specifying environment properties altogether as follows:
In this case a standard JavaSE JNDI lookup mechanism with fallback will be utilised. Components can reference an object stored in Jndi by setting the implementation attribute of a <muledescriptor> to the name of the stored object. <mule-descriptor name="MyComponent" implementation="myJndiObject"> ....
It's also possible to reference any property from JNDI, e.g. inject a DataSource into JdbcConnector: ... <properties> <property name="pollingFrequency" value="1000"/> ...
Document generated by Confluence on Apr 24, 2008 08:11
Page 192
PicoContainer Support This page last changed on Jan 30, 2008 by ross.
Now available on MuleForge.
Document generated by Confluence on Apr 24, 2008 08:11
Page 193
Plexus support This page last changed on Jan 30, 2008 by ross.
Now available on MuleForge.
Document generated by Confluence on Apr 24, 2008 08:11
Page 194
Quartz Scheduler Integration This page last changed on Jan 30, 2008 by ross.
The Quartz integration has been superseeded by the Quartz Provider. This provides many more scheduling options and is independent of Spring. Quartz is an open source job scheduling system that can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs. Mule integrates with Quartz using Spring to provide a simple way to declare mule jobs.
Quartz Provider A Quartz Provider is now available: no dependency on Spring anymore, very simple trigger definitions... The MuleJobBean is an implementation of a Quartz Job that can be used to send or dispatch simple beans into Mule, using Quartz scheduling features. For an example of configuring Quartz for Mule, see the Spring configuration file. Further information on how to configure Quartz from a Spring context, look here. The following properties are available on the MuleJobBean:
Name
Description
Required
Endpoint
The Mule endpoint uri to which send the message
Yes
MuleManager
The url of the remote Mule manager
No
Payload
The payload of the message
Yes
Synchronous
If true the message will be sent instead of beeing dispatched
No
Document generated by Confluence on Apr 24, 2008 08:11
Default
False
Page 195
Rapid Development with Mule This page last changed on Jan 30, 2008 by ross.
• JavaRebel Integration — Develop in regular Java, re-compile and reload on the fly. • Dynamic Scripting in Mule 1.x (TODO) • Dynamic Scripting in Mule 2.x (TODO)
Document generated by Confluence on Apr 24, 2008 08:11
Page 196
JavaRebel Integration This page last changed on Apr 18, 2008 by tcarlson.
Prerequisites • Internet connection • Java 5
Instructions We'll use a Hello Example bundled with Mule to demonstrate the setup. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.
11. 12.
Download Mule 1.4.4-SNAPSHOT from the downloads page. Instructions apply to Mule 2.x as well. Configure JAVA_HOME, MULE_HOME and run Mule for the first time to accept the license. Download JavaRebel 1.0-M3 snapshot from http://www.zeroturnaround.com/download/ Unpack, copy javarebel.jar to $MULE_HOME/bin to keep things simple. Change into $MULE_HOME/examples/hello Generate project files mvn idea:idea (mvn eclipse:eclipse for, right, Eclipse) Change module output path to compile into $MULE_HOME/lib/user Delete mule-example-hello.jar from $MULE_HOME/lib/user. It contains the same classes we're compiling. JavaRebel supports only exploded class reloading currently. Make the project. Start Mule with an extra switch to enable JavaRebel: mule -config hello-config.xml -M-javaagent:../../bin/javarebel.jar -M-noverify Note that we reference the config file as a resource - it's been put on the classpath in lib/user when you built the project. Type your name when prompted, watch the standard reply. Now let's have some fun. Modify org.mule.samples.hello.Greeter#greet() method. Let's make it more rebellious: modify the code to set a new greeing: public Object greet(NameString person) { ... person.setGreeting("Wazzup "); ... }
13.
Make the project. Type Dude when prompted. Enjoy
Tips & Tricks Hey, it works in debug mode as well, including remote. Just add the -debug switch to the Mule start command and connect your debugger on port 5005 (default). Just make sure to say No when you see debugger's prompt to reload classes - let JavaRebel rock debugger plugin, see the troubleshooting section below.
IDEA users may need to get the JavaRebel
Troubleshooting • I get weird exception with strange class names - don't put javarebel.jar in $MULE_HOME/ lib/user. It's easier not to do it, then explain why it may fail for certain cases (complex classloader tricks). • It won't reload! - if nothing else works, then the worst to happen is restarting Mule. • It won't reload Mule core classes! - these instructions apply to custom user classes only. • Debugger never stops at breakpoint in IDEA - This is a known issue, JetBrains and ZeroTurnaround are actively working on it. Doesn't affect Eclipse users (uses different mechanism). Update: this has been resolved now. Download the JavaRebel Debugger plugin from IntelliJ IDEA plugin repo (or go to http://plugins.intellij.net/plugin/?id=1699). These changes might be included in IDEA's core in the future. • I can't compile the code in IDEA - make sure the JDK is properly configured for the project. If you know the name of the JDK as it is listed in IDEA, you can use it during project files generation: mvn idea:idea -DjdkName=1.6 • I get a JVM core dump under JDK 6 Update N - it may or may not work under Java 6. There's a regression in Java 6 Update N, which has been identified and reported. Apparently, something is
Document generated by Confluence on Apr 24, 2008 08:11
Page 197
wrong with their dev process, as they claim to have fixed it in b05 when they haven't in fact. Bug them! It still works with some Java 6 builds, depending on your setup. Java 5 is more stable for such work now.
Document generated by Confluence on Apr 24, 2008 08:11
Page 198
Resource Adapter This page last changed on Jan 30, 2008 by ross.
The Mule resource adapter enables a mule instance to be deployed to a J2EE application server. It can be deployed to any JCA 1.5 compliant container, see J2EE Application Servers for more information about specific App Server configurations. The Resource Adapter can be downloaded 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 SenderEJB <ejb-name>SenderEJB org.mule.samples.ejb.SenderHome org.mule.samples.ejb.Sender <ejb-class>org.mule.samples.ejb.SenderBean <session-type>Stateless Container mule/connectionFactory org.mule.ra.MuleConnectionFactory Container Unshareable
Inbound Configuration the only required property for for your MDB is 'endpoint' is a valid endpoint Uri to receive Mule events. <message-driven> <description>An MDB listening a Tcp socket TcpReceiverMDB <ejb-name>TcpReceiverMDB <ejb-class>org.mule.samples.ejb.SimpleReceiverMessageBean <messaging-type>org.mule.umo.lifecycle.Callable Container endpoint tcp://localhost:12345
Document generated by Confluence on Apr 24, 2008 08:11
Page 199
RMI This page last changed on Jan 30, 2008 by ross.
Managing RMI Objects - How to manage objects stored in RMI as Mule components RMI Transport Provider - Configuring the RMI transport provider. This allows you to fire events to and make requests from objects stored in RMI.
Document generated by Confluence on Apr 24, 2008 08:11
Page 200
Managing RMI Objects This page last changed on Jan 30, 2008 by ross.
The RmiContainerContext can be used to expose Rmi Objects as Mule components. To configure an RMI container you need to add a element that uses the org.mule.impl.container.RmiContainerContext and set the Jndi environment properties. The following example configures a JBoss RMI container context <properties> <map name="environment"> <property name="java.naming.factory.initial" value="org.jnp.interfaces.NamingContextFactory"/> <property name="java.naming.provider.url" value="jnp://localhost"/> <property name="java.naming.factory.url.pkgs" value="org.jboss.naming:org.jnp.interfaces"/> <property name="securityPolicy" value="/projects/foo/classes/wideopen.policy"/> <property name="securityManager" value="java.rmi.RMISecurityManager"/>
Components can reference an RMI Object by setting the implementation attribute of a <mule-descriptor> to the name of the Object stored in Jndi. <mule-descriptor name="RMIComponent" implementation="myRMIObject"> ....
Document generated by Confluence on Apr 24, 2008 08:11
Page 201
Scripting This page last changed on Jan 30, 2008 by ross.
Due to licensing issue, Mule cannot bundle JSR-223 libraries in the distribution. Until this page is updated with detailed instructions, one can check MULE-1168 for steps involved.
Mule Components, transports and configuration can be scripted using any JSR-223 compliant scripting language such as PHP (stateless), Groovy or Rhino (javascript).
Script Components Scripts can be invoked as Mule managed components by using org.mule.components.script.jsr223.ScriptComponent. To use Groovy as an example <mule-descriptor name="GroovyUMO" inboundEndpoint="jms://groovy.queue" implementation="org.mule.components.script.jsr223.ScriptComponent"> <properties> <property name="scriptEngineName" value="groovy"/> return "Received message: " + message.getPayload()
The following properties can be set on the ScriptComponent
Property
Description
scriptText
The script text that will be executed
scriptFile
The location of a script file on the class path of file system
scriptEngineName
The type of script being parsed, i.e. php, groovy or javascript
Interacting with Mule from your scripts When a script is invoked, the JSR-223 api has a notion of a namespace, a collection of objects that are referenceable by name from your script. Mule makes the following objects available.
Name
Description
eventContext
The current UMOEventContext
managementContext
The Mule Manager instance
message
the current UMOMessage. This is also accessible using 'context.getMessage()'
descriptor
The UMODescriptor object that represents this scripting component
componentNamespace
Document generated by Confluence on Apr 24, 2008 08:11
Page 202
A reference to the namespace collection for this script log
The commons Logger instance used by the script component
result
A placeholder 'result' object that can be used to pass back a result to the script component.
Script Configuration Builder The ScriptConfigurationBuilder allows developers to create a mule instance from a JSR-223 compliant script. To load the manager from javascript ScriptConfigurationBuilder builder = new ScriptConfigurationBuilder("javascript"); UMOManager manager = builder.configure("../conf/mule-config.js");
Or to start the server from the command line java -Dorg.mule.script.engine=javascript -cp ... org.mule.MuleServer -builder org.mule.config.builders.ScriptConfigurationBuilder -config ../conf/mule-config.js
For more information about configuring a Mule instance from code or script see Configuring Mule Programmatically.
Script Transformers Script transforms can be used to perform transformations on objects using scripting. The transformers are configuring in the same way as the ScriptComponent. To use Groovy as an example, the configuration for a transformer that converts a comma-separated string of values to a java.util.List would look like <properties> <property name="scriptEngineName" value="groovy"/> <property name="sourceType" value="java.lang.String"/> return src.toString().tokenize(",")
The sourceType property tells the transformer only to accept source objects of type string. This property can be set multiple times to register different source types. The scriptText property specifies the groovy script to invoke. The returnClass attribute on the transformer ensures that we will always get a java.util.List back from this transformer.
Document generated by Confluence on Apr 24, 2008 08:11
Page 203
Security This page last changed on Jan 30, 2008 by ross.
• • • •
Acegi Security Jaas Security PGP Security Web Service Security
Document generated by Confluence on Apr 24, 2008 08:11
Page 204
Acegi Security This page last changed on Jan 30, 2008 by ross.
Acegi is a security framework for Spring. In Mule it provides a simple way of authenticating requests via the Security Manager. There is a simple Mule security provider wrapper that delegates to Acegi, which means you can use any of the Acegi Security Providers such as JAAS, Ldap, Cas (Yale Central Authenication service) and Dao. See Configuring Security for more information about configuring Acegi with Mule.
Document generated by Confluence on Apr 24, 2008 08:11
Page 205
Jaas Security This page last changed on Jan 30, 2008 by ross.
The JaasSimpleAuthenticationProvider is a security provider which provides a way to interact with the Jaas Authentication Service. Configuration: The security provider for Jaas can be configured in a couple of different ways. First of all, it allows you to configure jaas either by passing to the provider a jaas configuration file, which will be discussed below, or by passing the required attributes directly to the JaasSimpleAuthenticationProvider. These two configuration methods are described below. Option 1: Using the Jaas Configuration File The Jaas Configuration File Usually, JAAS authentication is performed in a pluggable fashion, so applications can remain independent from underlying authentication technologies. com.ss.jaasTest{ com.ss.jaas.loginmodule.DefaultLoginModule required credentials="anon:anon;Marie:Marie;" };
The above example was saved in a file called jaas.conf. This file contains just one entry called com.ss.jaasTest, which is where the application we want to protect can be found. The entry specifies the LoginModule that will be used to authenticate the the user. As a login module, you can either use Mule's DefaultLoginModule, one of the LoginModules that come with Sun, or else create your own. In this case, we have opted for Mule's DefaultLoginModule. The "required" flag that follows the LoginModule specifies that the LoginModule must succeed in order for the authentication to be considered successful. There are other flags apart from this. These are: Required - The LoginModule is required to succeed. If it succeeds or fails, authentication still continues to proceed down the LoginModule list. Requisite - The LoginModule is required to succeed. If it succeeds, authentication continues down the LoginModule list. If it fails, control immediately returns to the application. Sufficient - The LoginModule is not required to succeed. If it does succeed, control immediately returns to the application (authentication does not proceed down the LoginModule list). If it fails, authentication continues down the LoginModule list. Optional - The LoginModule is not required to succeed. If it succeeds or fails, authentication still continues to proceed down the LoginModule list. The entry also specifies the credentials, in which we put a string of authorised users together with their passwords. The credentials are put here only when the DefaultLoginModule is going to be used as the method in which the user names and passwords are obtained may vary from one LoginModule to another. The Format of the credentials string must adhere to the following format if the DefaultLoginModule is going to be used: <username>:<password>; The Mule XML configuration <security-provider name="JaasProvider" className="com.ss.jaas.provider.JaasSimpleAuthenticationProvider"> <properties> <property name="loginContextName" value="com.ss.jaasTest"/> <property name="loginConfig" value="jaas.conf"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 206
Note that in the above, the loginContextName contains the same name of the entry in the jaas configuration file discussed above. This will be used for creating the login context as well as to find the complete URL of the jaas.conf file. Option 2: Using passing the credentials directly to the Provider The second option for the configuration of the JaasSimpleAuthenticationProvider is to pass the configuration details which would otherwise be found in the jaas configuration file directly to the provider. <security-provider name="JaasProvider" className="com.ss.jaas.provider.JaasSimpleAuthenticationProvider"> <properties> <property name="loginContextName" value="com.ss.jaasTest"/> <property name="credentials" value="anon:anon;Marie.Rizzo:dragon;" />
In the above configuration, you can note that we removed the property "loginConfig" and we don't need to pass any jaas configuration file. All we need to do is to pass the credentials to the provider (using the same format specified above). Since no LoginModule is specified, the DefaultLoginModule will be used. However, the JaasSimpleAuthenticationProvider also permits you to enter, using this configuration, your own LoginModule. Option 3: Passing a non- default Login Module <security-provider name="JaasProvider"className="com.ss.jaas.provider.JaasSimpleAuthenticationProvider"> <properties> <property name="loginContextName" value="com.ss.jaasTest"/> <property name="loginModule" value="com.sun.security.auth.module.NTLoginModule"/>
In the above configuration, we have added a further property for the loginModule where you can add the LoginModule you wish to use to authenticate the user. Since the NTLoginModule does not require you to input a list of accepted usernames and passwords, the property for the "credentials" was removed. Configuring the security filter on an Endpoint: As a security-filter, the MuleEncryptionEndpointSecurityFilter can be used. <mule-descriptor name="SendStringUMO" implementation="com.ss.jaasTest.SendString"> <endpoint address="vm://localhost/test"> <security-filter className="org.mule.impl.security.filters.MuleEncryptionEndpointSecurityFilter"> <properties> <property name="strategyName" value="PBE"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 207
PGP Security This page last changed on Jan 30, 2008 by ross.
PGP Security This extension adds PGP security on endpoint communication. With PGP you can achieve end-to-end security communication with signed and encrypted messages between parties.
Requirements You need to add these libraries to Mule classpath: • Cryptix OpenPGP • Cryptix JCE Install Policy files If you are running JDK 1.4+ that comes with the Sun JCE by default, or JDK 1.2/1.3 if you have installed Sun JCE 1.2 manually, you have to install the Unlimited Strength Jurisdiction Policy files, which can be downloaded from the following URL (note that they are listed entirely at the bottom of the page, in the Other Dowloads section): http://java.sun.com/j2se/1.4/download.html http://java.sun.com/j2se/1.5.0/download.jsp These files have to be installed in $JAVA_HOME$/jre/lib/security The default distribution of the JCE allows as Sun calls it 'strong, but limited strength cryptography'. This basically means that you cannot use RSA keys bigger than 2048 bits, and no symmetric ciphers that use more than 128 bits. ElGamal is not allowed at all, thus DH/DSS cannot be used for encryption. Useful PGP links How PGP works (intro documentation) GnuPG (freeware implementation) enigmail (extension for Thunderbird)
Configuring PGP filter Using a spring context, we have to define a manager for accessing public and private keys. securityContext.xml
Also we need to know who is the sender of a message. For this example we simply fake the sender using the org.mule.extras.pgp.FakeCredentialAccessor class (from pgp test src, which returns a fixed user name) PGP stores keys in files called keyrings There is a public keyring storing public keys of your trusted parties and a private keyring storing your secret key. In a keyring, keys are referenced by an alias ID (also named key Id). Your secret keyring is encrypted on your disk using a passphrase. Our goal is to define a sample echo application that reads signed (and encrypted) files from a directory (/ temp/signedAndEncryptedFiles/in) and write the decrypted content into /temp/decryptedFiles/out Then comes Mule configuration... <mule-configuration id="Test_Mule_Properties" version="1.0"> <properties> <property name="configFile" value="securityContext.xml"/> <security-manager> <security-provider name="PgpProvider" className="org.mule.extras.pgp.PGPSecurityProvider"> <properties> <encryption-strategy name="KBE" className="org.mule.extras.pgp.KeyBasedEncryptionStrategy"> <properties> <model name="echoTest"> <mule-descriptor name="echo" containerManaged="false" implementation="org.mule.extras.pgp.EchoMsg"> <endpoint address="file:///temp/signedAndEncryptedFiles/in"> <security-filter className="org.mule.extras.pgp.filters.PGPSecurityFilter"> <properties> <property name="strategyName" value="KBE"/> <property name="signRequired" value="true"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 209
reference="pgpKeyManager" /> <endpoint address="file:///temp/decryptedFiles/out" > <security-filter className="org.mule.extras.pgp.filters.PGPSecurityFilter"> <properties> <property name="strategyName" value="KBE"/> <property name="authenticate" value="false"/>
The property signRequired in the inbound security filter controls if we accept unsigned message or not. the property authenticate in the outbound security filter controls if we want to encrypt messages for the receiver ..and they said "free email account"...but I read "free persistent message queue"... – Alessandro Riva
Document generated by Confluence on Apr 24, 2008 08:11
Page 210
Web Service Security This page last changed on Jan 30, 2008 by ross.
Mule with Ws-Security Ws-Security with Xfire Ws-Security with Axis Saml with Ws-Security
The Ws-Security Filter The WsSecurityFilter uses Apache's WSS4J to provide web service security for both Xfire and Axis transports. Its is able to distinguish between the Axis and Xfire transports, depending on which transport the call is coming, and set the appropriate security handlers on the service.
Properties
Property
Description
Default
Required
wsSignatureFile
contains the name of the properties file used for signatures
No
wsDecryptionFile
contains the name of the properties file used for decryption
No
Ws-Security and Properties Files Ws-Security uses certificates to encrypt or sign parts, or all, of the message being sent. Hence valid certificates are a must. Also a must is the properties files that tell the Ws-Security Filter and handlers how to decode the message. The example properties file below demonstrates what the properties file should include. Here we use Apache's crypto provider Merlin as our crypto provider which is available with Apache's WSS4J. Example of a properties file used to decode incoming ws-secured messages: org.apache.ws.security.crypto.provider=org.apache.ws.security.components.crypto.Merlin org.apache.ws.security.crypto.merlin.keystore.type=jks org.apache.ws.security.crypto.merlin.keystore.password=keyStorePassword org.apache.ws.security.crypto.merlin.alias.password=mulePassword org.apache.ws.security.crypto.merlin.keystore.alias=mulealias org.apache.ws.security.crypto.merlin.file=privatestore.jks
The Password Handler Among the properties which should be on an outbound Ws-Security message is the password callback handler which will check whether the password provided matches the one on the public store. You are free to create your own callback handler. If you do not wish to do so, you can use Mule's default MuleWsSecurityCallbackHandler which gets the required passwords from a Spring configuration file. The configuration of the Passwords in the Spring-Config.xml file should be as follows: <props> <prop key="mulealias">mulePassword <prop key="gooduser">goodUserPassword
Document generated by Confluence on Apr 24, 2008 08:11
Page 211
Ws-Security on Xfire Security on Inbound using Xfire When receiving a Ws-Secured message we need to set the WsSecurityFilter on the required endpoint. The proper encryption and signature property files need to be added as properties of the filter to be able to decrypt or verify the signature on the incoming message. <mule-descriptor name="MySecuredUMO" implementation="org.mule.components.simple.EchoComponent"> <endpoint address="xfire:http://localhost:8282"> <security-filter className="org.mule.extras.wssecurity.filters.WsSecurityFilter"> <properties> <property value="in-signed-security.properties" name="wsSignatureFile"/> <property value="in-encrypted-security.properties" name="wsDecryptionFile"/>
The WsSecurityFilter will set the appropriate handlers (the DOMInHandler and the MuleWSSInHandler) on the service and lets WSS4J take care of the security.
Security on Outbound using Xfire By setting the WsSecurityFilter on the outbound endpoint you can secure an outgoing message. Depending on the properties found on the message you can sign or encrypt the message. Don't forget to include the signature/encryption property files as properties of the filter. You can configuring the WsSecurityFilter on the outbound endpoint in exactly the same way as for the inbound endpoint. <mule-descriptor name="BridgeUMO" implementation="org.mule.components.simple.BridgeComponent"> <endpoint address="vm://testin" type="receiver"/> <endpoint address="xfire:http://localhost:8484/MySecuredUMO?method=echo" type="sender"> <security-filter className="org.mule.extras.wssecurity.filters.WsSecurityFilter"> <properties> <property value="out-signed-security.properties" name="wsSignatureFile"/> <property value="out-encrypted-security.properties" name="wsDecryptionFile"/>
By default, the WsSecurityFilter adds the DOMInHandler and MuleWSSInHandler on the inbound and the DOMOutHandler and the WSS4JOutHandler on the outbound. If you want to secure an outbound message but the WS-Security properties are not yet set on the message, then you can set these as properties on the Security Filter and they will be set on your outbound message for the authentication process. <mule-descriptor name="BridgeUMO" implementation="org.mule.components.simple.BridgeComponent">
Document generated by Confluence on Apr 24, 2008 08:11
Page 212
<endpoint address="vm://testin" type="receiver"/> <endpoint address="xfire:http://localhost:8484/MySecuredUMO?method=echo" type="sender"> <security-filter className="org.mule.extras.wssecurity.filters.WsSecurityFilter"> <properties> <map name="addOutboundProperties"> <property name="action" value="UsernameToken"/> <property name="passwordType" value="PasswordDigest"/> <property name="user" value="gooduser"/> <property name="passwordCallbackClass" value="org.mule.extras.wssecurity.callbackhandlers.MuleWsSecurityCallbackHandler"/>
If you require additional Client handlers, you can add these to the connector as shown in the following configuration. <properties> <list name="clientOutHandlers"> <entry value="org.foo.MyOutHandler"/>
Ws-Security on Axis: Although very similar to the Xfire configuration, there are some differences in how the connector is configured. <properties> <property name="clientConfig" value="mule-axis-secure-client-config.wsdd"/> <property name="serverConfig" value="mule-axis-secure-server-config.wsdd"/>
As seen in the configuration above, Axis requires the client and server configurations on which the security considerations will be placed, i.e. required actions, the password callback class, handlers as well as username and password to be used. Below is an example Client config: <deployment xmlns="http://xml.apache.org/axis/wsdd/" xmlns:java="http://xml.apache.org/axis/wsdd/ providers/java"> <requestFlow>
Document generated by Confluence on Apr 24, 2008 08:11
Page 213
The WsSecurityFilter, like with Xfire, places the required properties and handlers (this time the WSDoAllReceiver for the inbound) on the Axis Service. The WsSecurityFilter for Axis is configured in just the same way as it is for Xfire. <mule-descriptor name="MySecuredUMO" implementation="org.mule.components.simple.EchoComponent"> <endpoint address="axis:http://localhost:8282"> <security-filter className="org.mule.extras.wssecurity.filters.WsSecurityFilter"> <properties> <property value="in-signed-security.properties" name="wsSignatureFile"/> <property value="in-encrypted-security.properties" name="wsDecryptionFile"/>
Ws-Security with SAML WSS4J generate and process SAML tokens and consequently Mule is able to support this. The configuration of the filter on the endpoints is exactly the same as those discussed above and works with both Axis and Xfire transports. The only difference lies in the properties passed in the message which must also include a saml.properties file. A typical saml.properties file would look like the following:
org.apache.ws.security.saml.issuerClass=org.apache.ws.security.saml.SAMLIssuerImpl org.apache.ws.security.saml.issuer.cryptoProp.file=out-signed-security.properties org.apache.ws.security.saml.issuer.key.name=mulealias org.apache.ws.security.saml.issuer.key.password=mulePassword org.apache.ws.security.saml.issuer=mulealias org.apache.ws.security.saml.subjectNameId.name=uid=mule,ou=people,ou=saml-demo,o=example.com org.apache.ws.security.saml.subjectNameId.qualifier=www.example.com org.apache.ws.security.saml.authenticationMethod=passwordorg.apache.ws.security.saml.confirmationMethod=senderV
Example of sending Saml Properties with a Mule Message using the MuleClient The following code snippet shows how Saml properties can be sent with a message to mule. The message, below, is sent over Xfire so Xfire's WSHandler properties were used. The SIG_KEY_ID property has to be set to "DirectRefenence" when using Xfire for Saml as the IssuerSerial method is not currently supported. MuleClient client = new MuleClient(); Properties props = new Properties(); // Action to perform : saml token props.setProperty(WSHandlerConstants.ACTION, WSHandlerConstants.SAML_TOKEN_SIGNED); // saml configuration file props.setProperty(WSHandlerConstants.SAML_PROP_FILE, "saml.properties"); // Password type : text or digest props.setProperty(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_DIGEST); // User name to send props.setProperty(WSHandlerConstants.USER, "mulealias");
// Callback used to retrive password for given user. props.setProperty(WSHandlerConstants.PW_CALLBACK_CLASS,"org.mule.extras.wssecurity.callbackhandlers.MuleWsSecur // Configuration for accessing private key in keystore props.setProperty(WSHandlerConstants.SIG_PROP_FILE, "out-signed-security.properties");
Document generated by Confluence on Apr 24, 2008 08:11
Page 214
// Set signature method to DirectReference props.setProperty(WSHandlerConstants.SIG_KEY_ID, "DirectReference"); // Send Message UMOMessage m = client.send("xfire:http://localhost:8282/MySecuredUMO?method=echo","Test",props);
Please note, that when the Ws-Security properties are sent to Mule in this fashion, the DOMInHandler and the MuleWSSInHandler must be configured on the connector as "clientOutHandlers" in order for the message to become secure.
Document generated by Confluence on Apr 24, 2008 08:11
Page 215
Spring This page last changed on Apr 18, 2008 by tcarlson.
Mule and Spring can integrate on different levels. You can can choose as much or little Mule in your Spring application or Spring in your Mule application. The following pages describe in detail how you can use Mule and Spring together. • Using Spring as a Component Factory How to configure the Spring Container with Mule so that Managed components and other Mule objects can be loaded from Spring. • Configuring the Mule Server From a Spring Context A Mule server is just a bunch of beans! How to load a Mule instance from the Spring Container. • Configuring a Spring context using Mule Xml There are lots of reasons why you might want to use Mule and Spring together, but configuring Mule in Spring bean Xml can be a verbose process. Now you can configure it using Mule Xml and mix Spring beans in the configuration. • Mule Events in Spring A really easy way for your beans to send and receive Mule events via the Spring Application Context without any code changes! • MULEINTRO:Spring Events Example Uses a simple restaurant demonstration to show how to send and recieve Mule events using the Spring ApplicationContext without needing to write any Mule specific code or configuration! Sandbox There are currently two Spring-related additions in the MULECDEV:Sandbox. Take a look and if you want to help get them into the main distribution, get involved!
Document generated by Confluence on Apr 24, 2008 08:11
Page 216
Configuring a Spring context using Mule Xml This page last changed on Jan 30, 2008 by ross.
You can configure a Spring context for Mule using Mule Xml. This means you can use Spring to wire together a Mule instance without needing to write all the bean definitions yourself, which can be quite time consuming and difficult to maintain. Plus you get the benefits of configuring Mule in domain-specific Mule Xml. To configure Mule using a Spring context with Mule xml, simply pass the Mule Xml configuration file to the SpringConfigurationBuilder SpringConfigurationBuilder builder = new SpringConfigurationBuilder(); UMOManager manager = builder.configure("mule-config.xml");
This isn't very useful in itself, but what you can do is combine Spring beans in your Mule Xml to take advantage of Springs advanced wiring capabilities. For example, if you wanted to set a property on a Mule component using a factory method, you can use Spring configuration to do this. <mule-descriptor name="test" implementation="testObject"> <properties> cocktail
There are element name clashes between Spring Xml and Mule Xml configuration. As such certain configuration elements in Spring have to be prepended with spring- when being used in Mule Xml. The following table lists the affected tags.
Spring Element
In Mule Xml
<property ...>
<spring-property ...>
<map>
<spring-map>
<list>
<spring-list>
<entry>
<spring-entry>
For example, to add a Spring bean property to a Jms Connector <properties> <spring-property name="jndiContext"> <property name=jndiDestinations" value="true"/>
When using spring elements you can use all the configuration elements that Spring provide. The above configures the jndiContext, connectionFactory and jndiDestinations properties on the JmsConnector. If you want to mix beans in with your Mule Xml (like above) add the following DOCTYPE declaration to your config file
Document generated by Confluence on Apr 24, 2008 08:11
Page 217
The Spring configuration builder uses the DOCTYPE to determine how to load the configuration file. Any Mule configuration files will be transformed into Spring bean xml before being loaded into a Spring context. You can mix any number of configuration files when using the SpringConfigurationBuilder just so long as the DOCTYPE declaration uses one of the following dtds.
DTD
Type
mule-configuration.dtd
Standard Mule xml, no Spring bean definitions
mule-spring-configuration.dtd
Mule Xml and Spring Xml combined
spring-beans.dtd
Spring beans configuration only
So if you had three different xml configuration files and each one used a different configuration format, defined by the dtds, you could load all of them using the SpringConfigurationBuilder and they can be on the classpath or the file system. SpringConfigurationBuilder builder = new SpringConfigurationBuilder(); UMOManager manager = builder.configure("spring-beans.xml,mule-configuration.xml, mule-spring-configuration.xml);
Document generated by Confluence on Apr 24, 2008 08:11
Page 218
Configuring the Mule Server From a Spring Context This page last changed on Jan 30, 2008 by ross.
There is now no need to write Spring Bean configurations for Mule yourself as Mule can auto-generate Spring Bean XML from Mule XML. See Configuring a Spring context using Mule Xmlfor more information. It is still possible to configure Mule in the ways described below and this page is left here for reference. Better yet, MULE-659describes how you can bootstrap Mule from Spring. The elements will work without an element. The MuleManager can be created directly from a Spring context. This means you can distribute your MuleManager as a Spring applicationContext.xml file. Mule provides a Spring FactoryBean for creating the MuleManager instance, where there are two implementations 1. org.mule.extras.spring.config.UMOManagerFactoryBean. It expects that every bean for the MuleManager to be wired explicitly in the Spring configuration. (The factory Bean is deprecated) 2. org.mule.extras.spring.config.AutowireUMOManagerFactoryBean. It expects that all beans such as connectors, providers, component descriptors are declared in the configuration, but will then 'autowire' the MuleManager together based on what is available in the application context. This FactoryBean is more useful than the other as it can be a bit of an effort to wire the MuleManager together manually. Many objects in Mule, such as connectors, transformers and managed components have a unique name attribute that must be set. Most of the time the Spring bean ID will be the same as the name for the Mule object so you can get Spring to set the bean ID's to Mule object names by declaring the MuleObjectNameProcessor bean in the container
Using AutowireUMOManagerFactoryBean In order to use the AutowireUMOManagerFactoryBean you must define a muleManager bean as an instance of org.mule.extras.spring.config.AutowireUMOManagerFactoryBean. The name of the bean is not important to Mule. This factory bean is responsible for determining the instance type of UMOManager to create then delegate configuration calls to that instance depending on what is available in the container.
Apart from removing the need to explicitly wire the MuleManager instance together there is another advantage to using the AutowireUMOManagerFactoryBean. There is no need to declare a UMOModel instance in the configuration. If the factory doesn't find a UMOModel implementation it creates a default one of type org.mule.impl.model.MuleModel. The model is automatically initialized with a SpringComponentResolver using the current applicationContext and defaults are used for the other model properties. If you want to override the defaults, such as define your own exception strategy, (which you will most likely want to do) simply declare your exception strategy bean in the container and it will automatically be set on the model. Mule requires a manager ID be available if JMX management is in use (since Mule 1.3.1). You can set the managerId property on this factory bean to configure it. Most Mule objects have explicit types and can be autowired, however some objects cannot be autowired, such as a java.util.Mapof endpoints for example. For these objects Mule defines standard bean names that will be looked for in the container during start up. muleEnvironmentProperties A map of properties to set on the MuleManager. Accessible from your code using AutowireUMOManagerFactoryBean.MULE_ENVIRONMENT_PROPERTIES_BEAN_NAME. muleEndpointMappings A Map of logical endpoint mappings accessible from your code using AutowireUMOManagerFactoryBean.MULE_ENDPOINT_MAPPINGS_BEAN_NAME. muleInterceptorStacks
Document generated by Confluence on Apr 24, 2008 08:11
Page 219
A map of interceptor stacks, where the name of the stack is the key and a list of interceptors is the value. Accessible from your code using AutowireUMOManagerFactoryBean.MULE_INTERCEPTOR_STACK_BEAN_NAME. An example interceptor stack configuration might look like this <list> <map> <entry key="default">
Using UMOManagerFactoryBean Configuration with the UMOManagerFactoryBean is more involved but is sometimes useful when testing as you explicitly control what objects are configured on the MuleManager. In order to use it you must define a muleManager bean as an instance of org.mule.extras.spring.UMOManagerFactoryBean. Again, the name of the bean is not important. This is a factory bean that creates a MuleManager instance (or deriving type) and then delegates configuration calls to that instance. Each of the dependencies of the MuleManager must be defined explicitly in the configuration.
Some of the properties of the bean have local references to java.util.List and java.util.Map beans in the container, if you do not want these collection objects floating around in your container you can always declare each property as a <list> or <map> and add the bean refs inline. For example, the endpoints are declared 'inline' negating the need to declare a endpointList bean in your applicationContext.xml. <property name="configuration"> <property name="messageEndpoints"> <property name="connectors"> <property name="transformers"> <property name="endpoints"> <list> <property name="interceptorStacks"> <property name="model">
For more information about configuring the Spring Application Context you can go to the Spring web site.
Document generated by Confluence on Apr 24, 2008 08:11
Page 220
Configuring Mule objects in Spring By default, Spring creates all bean instances as singletons, that is only one bean instance is created and the same instance is returned for each request of that bean. This is fine for most of the Mule server objects but there are three important exceptions 1. Objects that are managed by Mule. Mule managed objects cannot be singletons because components are pooled and each pooled instance is expected to be different. 2. Mule endpoints. Endpoints are mutable and can be global, meaning that more than one component can reference the same instance. It is feasible that users of the same endpoint might want to update the endpoint or properties as runtime. Initializing the endpoints as a singleton would mean those changes would affect all other components referencing the same endpoint. 3. Mule Transformers. For the same reasons as endpoints, transformers should not be singletons.
Mule Component Configuration Configuring a Mule managed component in Spring is very similar to configuring a component in the Mule Xml configuration. Notice here that the implementation attribute of the testComponent bean is set to myPojo value> and not to . This is because at runtime Mule will look up a bean in the context with the name 'myPojo' and may do so several times depending on the component pooling settings. <property name="name">testComponent <property name="inboundEndpoint> vm://test.queue <property name="outboundEndpoint"> vm://out.queue <property name="implementation">myPojo <property name="interceptors"> <list> <property name="messageRouter">
Configuration Example Below is a simple but complete configuration for Mule. It defines a single managed component 'orderProcessor' and an inbound and outbound JMS endpoint, a couple of JMS transformers and some endpoint mappings. This example uses the AutowireUMOManagerFactoryBean and no model is defined so a default one will be created. Notice that the orderProcessorDescriptor and endpoints are not singletons.
Document generated by Confluence on Apr 24, 2008 08:11
Page 221
<property name="acknowledgementMode">1 <property name="connectionFactoryJndiName"> JmsQueueConnectionFactory <property name="jndiProviderProperties"> <map> <entry key="java.naming.factory.initial"> org.exolab.jms.jndi.InitialContextFactory <entry key="java.naming.provider.url"> tcp://localhost:3035 <property name="returnClass">javax.jms.TextMessage <property name="doCompression">true <property name="returnClass">java.lang.String <property name="doCompression">true <map> <entry key="Orders Queue">customer.orders.in <entry key="Feedback Queue">customer.feedback.out <property name="connector"> <property name="endpointURI"> jms://test.queue <property name="transformers">JmsMessageToString <property name="type">receiver <property name="connector"> <property name="endpointURI"> jms://feedback.queue <property name="transformers">StringToJmsMessage <property name="type">sender
Document generated by Confluence on Apr 24, 2008 08:11
Page 222
<property name="inboundEndpoint"> <property name="outboundEndpoint"> <property name="implementation"> orderProcessor
Overloading the MuleManager in Spring By default, the Spring Mule factories create an instance of org.mule.MuleManager. You can override the type of manager created by setting the org.mule.umo.UMOManager system property to a fully qualified class name to use. -Dorg.mule.umo.UMOManager=com.foo.MyMuleManager
or from code before you configure the MuleManager System.setProperty("org.mule.umo.UMOManager", "com.foo.MyMuleManager"); SpringConfigurationBuilder builder = new SpringConfigurationBuilder(); MyMuleManager manager = (MyMuleManager)builder.configure("applicationContext.xml");
Note that com.foo.MyMuleManager would need to implement org.mule.umo.UMOManager or extend org.mule.MuleManager and that to access your instance of UMOManager you still call MuleManager.getInstance(). Here is a sample configuration for starting Mule from Spring posted to the users list by Conal Markey: I start Mule from Spring in the following way. I have a file called muleContext.xml with the following entries;
I then added this context file to the appropriate context parameter in the web.xml. (If its not a web app you have then you should be able to just add this to the list of config files you give the relevant application context builder). <param-name>contextConfigLocation <param-value> classpath:com/.../.../config/muleContext.xml
The autowire manager then picks up all the other classes in my context files of mule types.
Document generated by Confluence on Apr 24, 2008 08:11
Page 223
One thing to watch, I had significant problems with the instance of MuleClient being created before the MuleManger because I was injecting this to other beans, (the depends-on attribute I have in the config above doesn't do what it suggests). I had to remove the references to the MuleClient from other context files to get round this. Hope this helps
Document generated by Confluence on Apr 24, 2008 08:11
Page 224
Sending and Receiving Mule Events From the Spring Context This page last changed on Apr 18, 2008 by tcarlson.
Spring Events Overview Spring provides a simple mechanism for sending and receiving events between beans. To receive an event, a bean implements ApplicationListener, which has a single method ApplicationListener.java public void onEvent(ApplicationEvent event);
To publish events to listeners you call the publishEvent() method the ApplicationContext. This will publish the same event to every listener in the context. In Spring 1.1 it is possible to plug in custom Event Handlers into the application context, which is good news for Mule.
Mule Events in Spring The latest Mule release includes an Event Multicaster that can be plugged into Spring so that Spring beans can send and receive Mule events.
Quick Start All you need to do to start receiving Mule Events is add the MuleEventMulticaster bean to your applicationContext and one or more endpoints on which to receive events
Now any emails recieved for [email protected] or any JMS messages sent to my.queue will be received by all Spring event listeners. That's it! you're now receiving events in Spring from Mule. The inbound endpoints can be any valid Mule Endpoint so you can receive JMS messages, SOAP requests, files, HTTP and servlet requests, TCP, multicast, etc. If you are using JMS you will also need to add a Mule JMS connector bean to your application context. To use ActiveMQ add the following <property name="specification"> 1.1 <property name="connectionFactoryJndiName"> ConnectionFactory <property name="jndiInitialFactory"> org.codehaus.activemq.jndi.ActiveMQInitialContextFactory
For more information about using other JMS servers see Configuring Jms.
Document generated by Confluence on Apr 24, 2008 08:11
Page 225
Adding Bean Subscriptions It is often more useful to have beans subscribe only to the events they are interested in. The MuleSubscriptionEventListener adds two new methods for getting and setting an array of endpoints that the bean will receive events on. TestSubscriptionBean.java public class TestSubscriptionBean implements MuleSubscriptionEventListener { private String[] subscriptions; public void onEvent(ApplicationEvent e) { //Get the event payload, in this case string contents of a file String contents = (String)e.getSource(); } public String[] getSubscriptions() { return subscriptions; } public void setSubscriptions(String[] subscriptions) { this.subscriptions = subscriptions; } }
The bean is configured in the spring context like any other bean. <property name="subscription"> <list> file:///tmp/inbound
Publishing Events to Mule Publishing events is just as easy are receiving them. You use the standard publishEvent() method on the application context. Your bean can get a reference to the application context by implementing ApplicationContextAware or by querying the MuleApplicationEvent. //Create a new MuleEvent. Object message = new String("This is a test message"); MuleApplicationEvent muleEvent = new MuleApplicationEvent( message, "jms://processed.queue"); //Call publish on the application context, Mule will do the rest :-) applicationContext.publishEvent(muleEvent);
If you would like to see more there is a MULEINTRO:Spring Events Example.
What About Non-Mule Events The MuleEventMulticaster does not interfere with normal Spring event behaviour. If an applicationEvent (non-mule) is sent via the ApplicationContext all beans registered to receive events will still get the event.
Document generated by Confluence on Apr 24, 2008 08:11
Page 226
Spring Remoting This page last changed on Jan 30, 2008 by ross.
The SpringInvokerComponent Allows Mule transports to be used to invoke Spring Remoting objects or for Mule services to invoke spring remoting objects. As the class names may change a bit before the Mule 1.3 final release we're holding of the documentation investment However, its very easy to set up and there is a test case configuration file that you can view here.
Document generated by Confluence on Apr 24, 2008 08:11
Page 227
Using Spring as a Component Factory This page last changed on Jan 30, 2008 by ross.
Mule separates the container in which components are created and the Mule model in which they are managed. This means developers can plug-in a container such as Spring or PicoContainer to construct the components that Mule manages. This section will describe how to do this with the Spring container, though the approach is very similar for other containers. For our example we are going to use 2 beans; a RestaurantWaiter bean that receives orders, logs the order and then passes it to the KitchenService bean which receives orders and does 'something' with them. Our beans look something like this 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; } }
Setting up Spring The first thing to do is define your Spring application context. This context will contain our RestaurantWaiter and KitchenService beans <property name='kitchenService'>
So we now have two beans called restaurantWaiter and kitchenService that will be created by Spring. Notice the resturantWaiter bean is not declared as a singleton (by default, all beans in Spring are singletons unless specified otherwise). This is important as Mule will pool your components and telling Spring not to create a singleton ensures that each pooled instance will be a unique instance.
Configuring a Mule Component Once you have defined the Spring context configuration you can create you reference to myBean in the Mule XML configuration. Components managed by Mule are defined by using a <mule-descriptor> element. We will create a descriptor that will enable restaurantWaiter to receive events from JMS. <mule-descriptor name="Restaurant Waiter" implementation="restaurantWaiter"> <endpoint address="vm://order.queue"/>
What is important here is the implementation attribute; this is used to identify the bean in the container at run-time.
Document generated by Confluence on Apr 24, 2008 08:11
Page 228
Configuring the Container The final thing we need to do is tell Mule where to find the Spring application context. The Mule manager has the notion of a container context that can be set to obtain components at runtime and to wire container objects in the Mule XML configuration. Out of the box, Mule comes with a PicoContainerContext and SpringContainercontext. If these don't suit your needs the UMOContainerContext interface is extremely simple if you want to roll your own. Once the Spring container context is configured on the Mule Manager, Mule will automatically check the value of the mule-descriptor implementation attribute for objects in the container. To configure the Spring Container Context, declare the following within the root Mule XML configuration. <mule-configuration> .... <properties> <property name='configFile' value='../conf/applicationContext.xml'/> ....
The configFile property specifies the location of the applicationContext.xml file. It is possible to specify a classpath resource or a local file path.
What Happens Next? Now we are ready to try it out. When the Mule server starts the Container context is also loaded. Each of the mule-descriptor elements are loaded and the implementation attribute is used to look up a bean in the container. The bean is then added to the Mule managed container. When an event is received on the vm://orders.queue, an Order object is passed to the takeOrder() method on the RestaurantWaiter, which then logs the order and passes it to the KitchenService.
Loading dependent objects from the container As well as using the container context to load a mule-descriptor object implementation, it can be used to resolve dependent objects on any object configured on the Mule server such as endpoints transformer, connectors or agents. To reference a container managed object use the element. <mule-descriptor name='Restaurant Waiter' implementation='restaurantWaiter'> <endpoint address="vm://myBean.queue"/> <properties>
Here the name attribute refers to the bean mutator method on the managed component 'restaurantWaiter', the reference denotes the bean name in the container and the required attributed determines whether or not an exception is thrown if the reference is not found. See Configuring Properties for more information about configuring Mule objects.
Document generated by Confluence on Apr 24, 2008 08:11
Page 229
Streaming This page last changed on Jan 30, 2008 by ross.
Since version 1.4 Mule has supported streaming endpoints. This enables efficient processing of large data objects such as Files, documents and records by streaming the data through Mule rather than reading the thing into memory. Large data can be streamed through components via endpoints that support streaming. Currently transports that support streaming are • • • • • • •
File FTP / SFTP (added in 1.4.1; see MULE-1639) SSL HTTP HTTPS TCP SOAP (XFire)
A full list of capabilities for transports can be seen here.
Why Streaming • • • • •
Allows services to consume very large events in an efficient way Event payloads are not read into memory Simple routing rules based on event meta-data still possible Can combine Streaming and non-streaming endpoints Support for Streaming Transformers... on the to do list MULE-1635
Using Streaming in Mule In order to enable streaming in Mule you need to use the new Streaming Model. This is configured using <model name="main" type="streaming">
All components configured in this model will have to be streaming components. If you want to mix and match processing models just add more <model> elements to your configuration file. Streaming works very differently to the usual SEDA event-driven processing model that most Mule users are already familiar with. Streaming components need to implement the org.mule.impl.model.streaming.StreamingService interface public interface StreamingService { void call(InputStream in, OutputStream out, UMOEventContext context) throws Exception; }
• InputStream in - The data being recived by the inbound endpoint • OutputStream out - The stream to write processed data to • UMOEventContext content - Meta information about this stream event including properites, session info and origin information. Note that routers can be configured to router to different outbound streaming endpoints based on information in the event context. So manipulating the event context can change where the Outputstream out actually writes to.
Use Case 1 - File to Tcp The following examples demonstrates how to configure a simple usecase where the contents of a file are streamed directly to a socket. <model type="streaming" name="main">
Document generated by Confluence on Apr 24, 2008 08:11
Page 230
<mule-descriptor name="fileTcpBridge" implementation=org.mule.components.simple.StreamingBridgeComponent"> <endpoint address="file://${mule.working.dir}/in" streaming="true"/>
Notice that the <model> type is 'streaming' and that each of the <endpoint> elements have their 'streaming' attribute set. Finally, there is a org.mule.components.simple.StreamingBridgeComponent component that can be used to bridge streaming endpoints.
Streaming Model with Multiple Outbound Routers By default the Streaming model uses the InboundPassThroughRouter when no router is specified. Unfortunantely this router does not enable the use of the OutboundRouterCollection, and in turn the matchall or multiple endpoints are not enabled. To be able to use the Mule Streaming Model with multiple outbound routers or with the Chaining router, you have to set the ForwardingConsumer router on the inbound endpoint.
Use Case 2 - The Streaming Model with the Chaining Router <model name="Model" type="streaming"> <mule-descriptor name="Test" implementation="org.mule.components.simple.StreamingBridgeComponent"> <endpoint address="file://${mule.working.dir}/in"streaming="true"> <endpoint address="file:///temp/" streaming="true"> <properties> <property name="outputPattern" value= "${ORIGINALNAME}-${DATE}.done"/> <endpoint address="stream://System.out" streaming= "true"/>
Please notice the use of the ForwardingConsumer router set on the inbound-router.
Document generated by Confluence on Apr 24, 2008 08:11
Page 231
Suggested Reading This page last changed on Jan 30, 2008 by ross.
ESB ESB Introduction Part 1 This first article in this series described the basic concepts and role of the Enterprise Service Bus (ESB). It focuses on describing scenarios and issues for ESB deployment to support a Service-Oriented Architecture (SOA). One or more of these scenarios might apply to the SOA and ESB needs of your organization. - by Rick Robinson ESB Introduction Part 2 In Part 2 of this series on the Enterprise Service Bus (EBS), the author describes and analyzes some commonly observed scenarios in which ESBs and other Service-Oriented Architecture (SOA) solutions are implemented. - by Rick Robinson ESB Introduction Part 3 In the third installment of this series, the author examines possible solutions for the various scenarios outlined in Part 2. The ideas on the role of the Bus as explained in Part 1 provide the foundation for the scenarios. - by Rick Robinson Take the Enterprise Service Bus - by Lee Sherman The ESB Learning Guide - everything you want to know about ESB is here.
Enterprise Integration Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions - by Gregor Hohpe, Bobby Woolf Provides a consistent vocabulary and visual notation framework to describe large-scale integration solutions across many technologies. It also explores in detail the advantages and limitations of asynchronous messaging architectures.
SEDA SEDA SEDA is an acronym for staged event-driven architecture, and decomposes a complex, event-driven application into a set of stages connected by queues. This design avoids the high overhead associated with thread-based concurrency models, and decouples event and thread scheduling from application logic. Mule uses ideas from SEDA to provide a highly scalable server. Introduction to Staged Event-Driven Architecture (SEDA) - by Matt Welsh
JBI Java Business Integration - by Steve Vinoski 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 The Cathedral and the Bazaar by Eric Raymond Quality Improvement in Volunteer Free and Open Source Software Projects: Exploring the Impact of Release Management by Martin Michlmayr
Document generated by Confluence on Apr 24, 2008 08:11
Page 232
Open Source Java The Server Side
Document generated by Confluence on Apr 24, 2008 08:11
Page 233
Test Compatability Kit This page last changed on Jan 30, 2008 by ross.
The Mule TCK is a set of abstract testcases that test the common functionality of a component within the Mule framework. Using the Mule TCK is beneficial for the following reasons 1. Components tested with a tck testcase ensures that the common behaviour of the component is compatible with the Mule framework. 2. Using a tck testcase allows the developer to concentrate on writing tests for specific behaviour of their component. 3. Where testing of a method in the UMO API cannot be tested by the tck testcase, the testcase provides an abtract method for the test, ensuring the developer tests all areas of the component. 4. The TCK provides a default test model that is a simple set of test classes. The developer doesn't need to worry about writing new test classes for their testcases each time. 5. The TCK abstract testcases use JUnit TestCase so they are compatible with other testcases The following describes the supplied testcases and where to use them.
Testing Component
Description
AbstractMuleTestCase
This is not so much a TCK testcase, but a helper testcase providing methods for creating test and mock object types, such as • • • •
MuleProviderDescriptor MuleEvent MuleSession MuleDescriptor
It's a good idea to extend this testcase when testing mule components.|
AbstractProxyPoolTestCase
Mule uses a ProxyPool implementation to pool Mule proxies. There is an implementations provided; commons-pool. If you want to write your own this TCK testcase will test the default behaviour is compatible with the Mule framework.
AbstractConnectorTestCase
This testcase is used to test the common behaviour of a UMOConnector. This tests dispaching and sending events using mock objects. Further test cases are required to test the actual behaviour of the Connector.
AbstractMessageAdapterTestCase
This testcase provide tests for all the standard methods defined in the UMOMessageAdapter interface. It's usually enough to just extend this test case without writing any further tests.
AbstractMessageReceiverTestCase
This testcase is used to test the common behaviour of a UMOMessageReceiver. This tests receiving events using mock objects. Further test cases are required to test the actual behaviour of the MessageReceiver.
AbstractComponentResolverTestCase
This testcase is used to test implementations of UMOComponentResolver and UMOContainerContext, which are used to resolve object from external object containers. Mule currently supports Spring and PicoContainer
AbstractEntryPointResolverTestCase
Document generated by Confluence on Apr 24, 2008 08:11
Page 234
This testcase is used to test implementations of UMOEntryPointResolver. These are used to resolve the entry point method on an object to invoke when an event is received for it. Mule comes with a couple of implementatios suitable for many scenarios. AbstractTransformerTestCase
This testcase is used to test any transformers that extend AbstractTransformer. This transformer allows the developer to specify two transformers; one for converting from a particular object and one for converting it back.
Fruit Test Model
The fruit test model provides a set of simple objects that interact in a common way to provide an object model to test with. It can be found in the org.mule.tck.testmodels.fruit.
Document generated by Confluence on Apr 24, 2008 08:11
Page 235
Transaction Management This page last changed on Jan 30, 2008 by ross.
Mule's transaction framework is agnostic to the underlying transaction manager. The transaction could be a JDBC transaction, XA transaction or a JMS transaction or message acknowledgment. Whatever type the transaction is it can be handled the same way. Mule transactions are configured on inbound endpoints, where an endpoint can be configured to start a new transaction or join an existing one. The outbound endpoints will automatically enlist in the current transaction, provided that the managed resource is compatible with the transaction. Transactions are configured on a endpoint using a which maps to org.mule.umo.transaction.UMOTransactionConfig class. This defines what action an endpoint should take when it receives an event and the transaction factory to use to create transactions.
Single resource transactions Single resource transactions are transactions that are provided by the underlying resource: a jdbc transaction or a jms transaction. These kind of transactions can only be used to receive and/or send messages using a single resource. Example inbound endpoint configuration might look like <endpoint name="myInboundEndpoint" type="receiver" address="jms://test.In">
The configuration defines a JMS message endpoint that sends on a 'test.out' queue. The factory attribute is a fully qualified path to a TransactionFactory which Mule will use when creating transactions for this endpoint. The action attribute tells Mule what to do for each event, in this case a new transaction will be created for every event received. Possible values for action on the element are • NONE - Never participate in a transaction. • ALWAYS_BEGIN - Always start a new transaction when receiving an event. An exception will be thrown if a transaction already exists • BEGIN_OR_JOIN - If a transaction is already in progress when an event is received, join the transaction, otherwise start a new transaction • ALWAYS_JOIN - Always expects a transaction to be in progress when an event is received, if there is no transaction an exception is thrown. • JOIN_IF_POSSIBLE - Will join the current transaction if one is available otherwise no transaction is created. The outbound endpoint has no particular configuration: <endpoint name="myOutboundEndpoint" type="sender" address="jms://test.Out" />
The outbound endpoint will use the resource enlisted in the current transaction, if one is running. In this case, it will use the same jms session that has been used to receive the event. So when the inbound endpoint will have routed the message to the outbound endpoint, the transaction will be commited or rollbacked. You can send multiple message using the recipient list router and all messages will be sent in the same transaction.
XA transactions XA transactions can be used if you want to enlist multiple managed resources within the same transaction. The inbound endpoints are configured in the same manner as for single resource transactions, but the connectors need to be configured to use xa-enabled resources. If you run mule outside an application server, you can use Jotm transaction manager to configure an embedded transaction manager or read the next section. Currently, only three providers can be configured to be used in xa transactions:
Document generated by Confluence on Apr 24, 2008 08:11
Page 236
• VM provider • JDBC provider • JMS provider
XA Configuration Example The following uses a single transaction to read from a Jms Queue and write to a database. <mule-descriptor name="JmsToJdbc" implementation="org.foo.MyComponent"> <endpoint address="jms://my.queue?reuseSession=false"> <endpoint address="jdbc://writeTest?type=2" />
Because the inbound Jms Endpoint has an XATransactionFactory configured on it any outbound endpoints for the component will also become part of the XA transaction providing that the transport type supports XA transactions (XA enabled transports are listed above). For this configuration to work you will need to configure a Jms connector that uses a Jms XA Connection Factory and a Jdbc connector that is configured to use an XA DataSource.
Transaction Manager Lookup Mule uses javax.transaction.TransactionManager for managing transaction spanning multiple resources (XA). If you need the SUSPEND semantics for your transactions (i.e. this is what EJB's RequiresNew Tx attribute value does), then you have to use the transaction manager. Contrast this to a more typical javax.transaction.UserTransaction, which is just a thin handle to a transaction manager with limited (though in most cases sufficient) functionality. Particularly, it will not let you suspend the current transaction, otherwise it's merely the same. Depending on your server, you can run Mule either standalone or embedded in the application server. This is not only your choice, but a requirement for some products, as one server will expose the transaction manager in JNDI, the other will not, and yet another will grant you access only via proprietary APIs. This is unfortunate, but still in line with Java EE 1.4 specification, which does not consider the transaction manager a public API. Thus, you are left to the mercy of your application server vendor. The following table summarizes some common Java EE servers:
Application Server
Remote
Embedded
Common Location
Lookup class
JBoss
java:/ org.mule.transaction.lookup.JBo TransactionManager
Weblogic
javax.transaction.TransactionManager org.mule.transaction.lookup.We
WebSphere
Proprietary API call
Resin
java:comp/ org.mule.transaction.lookup.Res TransactionManager
JRun
java:/ org.mule.transaction.lookup.JRu TransactionManager
Document generated by Confluence on Apr 24, 2008 08:11
org.mule.transaction.lookup.We
Page 237
Other
specified via a jndiName property
org.mule.transaction.lookup.Ge
E.g. to use Weblogic's transaction manager:
Transaction Coordination Transaction demarcation is controlled by endpoints. The actual management of transactions is handled by the Mule TransactionCoordinator. Its important to note that any transacted event flows will be synchronous. The TransactionCoordinator is a singleton manager that looks after all the transactions for a Mule instance and provides methods for binding and unbinding transaction and retrieving the current transaction state.
Document generated by Confluence on Apr 24, 2008 08:11
Page 238
Jotm Transaction Manager This page last changed on Jan 30, 2008 by ross.
Jotm is a transaction manager that can be embeded in standalone applications. It can be used to configure XA transactions. To configure an instance of Jotm within mule, just put the following code in your mule xml config file:
Document generated by Confluence on Apr 24, 2008 08:11
Page 239
Transaction Manager Lookup This page last changed on Jan 30, 2008 by ross.
Mule uses javax.transaction.TransactionManager for managing transaction spanning multiple resources (XA). If you need the SUSPEND semantics for your transactions (i.e. this is what EJB's RequiresNew Tx attribute value does), then you have to use the transaction manager. Contrast this to a more typical javax.transaction.UserTransaction, which is just a thin handle to a transaction manager with limited (though in most cases sufficient) functionality. Particularly, it will not let you suspend the current transaction, otherwise it's merely the same. Depending on your server, you can run Mule either standalone or embedded in the application server. This is not only your choice, but a requirement for some products, as one server will expose the transaction manager in JNDI, the other will not, and yet another will grant you access only via proprietary APIs. This is unfortunate, but still in line with Java EE 1.4 specification, which does not consider the transaction manager a public API. Thus, you are left to the mercy of your application server vendor. The following table summarizes some common Java EE servers:
Application Server
Remote
Embedded
Common Location
Lookup class
JBoss
java:/ org.mule.transaction.lookup.JBo TransactionManager
Weblogic
javax.transaction.TransactionManager org.mule.transaction.lookup.We
WebSphere
Proprietary API call
Resin
java:comp/ org.mule.transaction.lookup.Res TransactionManager
JRun
java:/ org.mule.transaction.lookup.JRu TransactionManager
Other
specified via a jndiName property
org.mule.transaction.lookup.We
org.mule.transaction.lookup.Ge
E.g. to use Weblogic's transaction manager:
Document generated by Confluence on Apr 24, 2008 08:11
Page 240
Transports Guide This page last changed on Jan 30, 2008 by ross.
This page contains a list of known Provider Transports for Mule. If you have written a provider for mule and would like to submit it to the project, please contact us. If you only think of writing a provider, look no further than at Writing Transports. For introduction to providers see Mule Endpoints and for more information about configuration of transports in Mule see Configuring Endpoints. See General Transport Configuration for information about how Transports are configured at runtime. Take a look at the Transports Feature Matrix.
Mule Core Transports
AS400 DQ Provider
Connectivity to IBM AS400 Data Queue messaging server.
Ejb Provider
Allows Ejb invocations to be made using outbound endpoints.
Email Provider
This Provider supplies various email connectivity options.
File Provider
This connector allows files to be read and written to directories on the local file system. The connector can be configured to filter the file it reads and the way files are written, such as whether binary output is used or the file is appended to.
Ftp Provider
Allows files to be read / written to a remote ftp server.
Http Provider
This provider supplies Http and Https transport of mule events between applications and other Mule servers.
Imap Provider
Connectivity to Imap mail folders including IMAPs (secure) support.
Jdbc Provider
A Mule provider for Jdbc Connectivity.
Jms Provider
A Mule provider for Jms Connectivity. Mules itself is not a Jms server but can use the services of any Jms 1.1 or 1.02b compliant server such as ActiveMq, OpenJms, Joram, JBossMQ and commercial vendors such as WeblogicMQ, WebspereMQ, SonicMQ, SeeBeyond, etc.
Multicast Provider
Allows your components to receive an send events via IP multicast groups.
Pop3 Provider
Connectivity to POP3 inboxes including POP3s (secure) support.
Quartz Provider
Provides scheduling facilities with cron / interval definitions and allows Mule events to be sheduled/ rescheduled.
Rmi Provider
Document generated by Confluence on Apr 24, 2008 08:11
Page 241
Enables event to be sent and received over rmi via jrmp. Servlet Provider
Provides connectivity to the Mule server via servlets. provides facilities for Mule components to listen for events received via a servlet request. There is also a servlet implementation that uses the Servlet provider to enable REST style services access. Note this transport is now bundled with the Http transport.
Smtp Provider
Connectivity to Smtp servers including SMTPs (secure) support.
Soap Provider
Enables your components to be exposed as web services and to act as soap clients. The Soap provider supports XFire, Web Methods Glue and Apache Axis.
Ssl Provider
Provides secure socket-based communication using SSL or TLS.
Stream Provider
This provider allows connectivity to Streams such as System.in and System.out and is useful for testing.
Tcp Provider
Enables events to be sent and received over tcp sockets.
Udp Provider
Enables events to be sent and received as datagram packets.
Vfs Provider
Enables access to and from various protocols such as WebDav, Samba, File System, Jar/Zip and more.
Vm Provider
A Mule provider that enables event sending and receiving over VM or embedded memory or persistent queues.
WSDL Provider
The WSDL transport provider can be used to for invoking remote web services by obtaining the service WSDL. Mule will create a dynamic proxy for the service then invoke it.
Xmpp Provider
A Mule provider for connectivity over Xmpp (Jabber) instant messaging protocol
Document generated by Confluence on Apr 24, 2008 08:11
Page 242
AS400 DQ Provider This page last changed on Jan 30, 2008 by ross.
This provider is now available on MuleForge
Document generated by Confluence on Apr 24, 2008 08:11
Page 243
BPM Connector This page last changed on Jan 30, 2008 by ross.
Available since Mule 1.4
BPM Connector The BPM connector allows Mule events to initiate and/or advance processes in a Business Process Management System (BPMS) a.k.a. Process Engine. It also allows executing processes to generate Mule events.
Overview For a high-level introduction to Business Process Management with Mule and the concepts involved, see the presentation from MuleCon 2007. To see the BPM Connector in action (with JBoss jBPM), take a look at the LoanBroker BPM example (available in the full Mule distribution). Javadocs for this transport are available here: BPM Transport
Features • Incoming Mule events can launch new processes, advance or terminate running processes. • A running process can generate synchronous or asynchronous Mule events. • Endpoints of type "bpm://MyProcess" are used to intelligently route process-generated events within Mule. • Synchronous responses from Mule are automatically fed back into the running process. • Mule can interact with different running processes in parallel. BPEL The connector can only integrate with BPM engines that provide a Java API. If you have a requirement to integrate with a BPEL engine that only exposes SOAP endpoints (i.e., "a black box"), you will need to use standard web services. See an example of this here.
Usage Sending events to the BPMS The basic URI is bpm://ProcessType
(for a new process) or bpm://ProcessType/ProcessID
(for a running process) Initiate a new process of type "MyBigProcess" bpm://MyBigProcess
Advance an already running process with ID = 4561 bpm://MyBigProcess?processId=4561&action=advance
or just
Document generated by Confluence on Apr 24, 2008 08:11
Page 244
bpm://MyBigProcess/4561
(advance is the default action for an already-running process) Update process variables (without advancing the process) bpm://MyBigProcess/4561?action=update
Abort a running process (this might not be supported by every BPMS) bpm://MyBigProcess/4561?action=abort
In a real system, you will most likely want to set the "processId" dynamically as a property on the message.
Incoming messages to the BPMS When a message is received by the BPMS, two things automatically happen: • The message payload is stored in a process variable named "incoming" • The endpoint on which the message was orginally received by Mule is stored in a process variable named "incomingSource" These process variables may then be used to drive the logic of the running process.
Generating events from the BPMS The actual syntax for generating events from a running process will depend on the BPMS used. Messages generated by a running process will be received by Mule on the best-matching endpoint available. For example, let's suppose a Mule message is generated by the running process called "MyBigProcess" with ID = 4561. The incoming message would preferably be received by this endpoint: bpm://MyBigProcess/4561
and if not, then by this endpoint: bpm://MyBigProcess
and finally, if the "allowGlobalReceiver" property is true, by this endpoint: bpm://*
The new message will then be routed from the component on which it is received (unless the connector's "allowGlobalDispatcher" property is true). If the message is synchronous, the response will automatically be sent back to the generating process.
Configuration Connector Properties
Property
Description
bpms
The underlying BPMS, must implement the org.mule.providers.bpm.BPMS interface
yes
processIdField
This field will be used to correlate messages with processes.
no
Document generated by Confluence on Apr 24, 2008 08:11
Default
processId
Required
Page 245
allowGlobalReceiver
The global receiver allows an endpoint of type "bpm://*" to receive any incoming message to the BPMS, regardless of the process. If this is false, the process name must be specified for each endpoint, e.g. "bpm://MyProcess" will only receive messages for the process "MyProcess".
false
no
allowGlobalDispatcher
If false, any message generated by the process is routed from the component on which it is received. If true, a process can send messages to any endpoint on any component.
false
no
Property
Description
Default
Required
processType
The name of the process
yes
processId
The unique ID of the running process
yes, unless action = "start"
action
Action to perform on the BPMS: "start" / "advance" / "update" / "abort"
transition
Transition to take if more than one exit path is available for the current process state
Message Properties
"advance" if processId exists, otherwise "start"
no
no
Example config A simple config snippet might look like the following: <properties> <model name="bpm_example"> <mule-descriptor name="ToBPMS" implementation="org.mule.components.simple.LogComponent"> <endpoint address="Incoming1"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 246
<endpoint address="Incoming2"/> <endpoint address="bpm://MyProcess" synchronous="false" /> <mule-descriptor name="FromBPMS" implementation="org.mule.components.simple.LogComponent"> <endpoint address="bpm://MyProcess" /> <endpoint address="Outgoing1"/> <endpoint address="Outgoing2"/> <endpoint address="Outgoing3"/>
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, however, there is no standard JEE spec. to enable this. JSR-207 was one attempt but has made no progress. BPEL has also tried to solve this, but like JBI, is exclusive to SOAP web services and XML which defeats Mule's flexibility principle. Therefore, until such a spec. 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); }
Any BPM engine which then implements this simple interface ( org.mule.providers.bpm.BPMS ) can "plug in" to Mule via the BPM Transport. So far, the only engine available with Mule out-of-the-box is JBoss jBPM, but I'm sure the Mule community will soon be submitting others, right?
Integration with JBoss jBPM For general information on jBPM and how to configure it, refer to http://docs.jboss.com/jbpm/v3/ userguide
Document generated by Confluence on Apr 24, 2008 08:11
Page 247
The class which implements the BPMS interface for jBPM and needs to be set as the "bpms" property on your connector is org.mule.providers.bpm.jbpm.Jbpm You can browse the rest of the Javadocs for Mule's jBPM integration here: jBPM Integration Configuration The recommended way to configure jBPM with Mule is using Spring and Spring's jBPM Module <mule-configuration id="Mule_BPM" version="1.0"> <properties> <spring-property name="bpms"> <spring-property name="jbpmConfiguration"> <spring-property name="sessionFactory"> <spring-property name="configuration"> jbpm.cfg.xml <spring-property name="createSchema">false <spring-property name="dataSource"> <spring-property name="mappingLocations"> classpath*:/org/jbpm/**/*.hbm.xml <spring-property name="typeDefinitions"> <spring-property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect <prop key="hibernate.c3p0.min_size">1 <prop key="hibernate.c3p0.max_size">3 <prop key="hibernate.show_sql">false <prop key="hibernate.query.substitutions">true 1, false 0 <prop key="hibernate.jdbc.batch_size">0 <prop key="hibernate.hbm2ddl.auto">update
Document generated by Confluence on Apr 24, 2008 08:11
Page 248
<spring-property name="typeName">string_max <spring-property name="typeClass">org.jbpm.db.hibernate.StringMax <spring-property name="driverClassName">org.hsqldb.jdbcDriver <spring-property name="url">jdbc:hsqldb:mem:.;sql.enforce_strict_size=true <spring-property name="username">sa <spring-property name="password">
If you wish to configure jBPM without using Spring, you just need to create the org.mule.providers.bpm.jbpm.Jbpm wrapper based on your jBPM instance and set it as the "bpms" property on the BPM connector: ProcessConnector connector = new ProcessConnector(); BPMS bpms = new org.mule.providers.bpm.jbpm.Jbpm(yourJbpmInstance); connector.setBpms(bpms); MuleManager.getInstance().registerConnector(connector);
Generating a Mule message from jBPM Use the org.mule.providers.bpm.jbpm.actions.SendMuleEvent ActionHandler to generate a Mule message from your jBPM process: <process-definition name="sendMessageProcess"> <description>Generates a simple Mule event. <start-state name="start"> <state name="sendMessage"> <event type="node-enter"> <endpoint>file:///tmp <payload>Message in a bottle. <synchronous>false <end-state name="end" />
jBPM Action Handlers for Mule The primary way of adding custom functionality to jBPM is via ActionHandlers. The BPM transport provides a few such ActionHandlers which are useful for integrating your jBPM process with Mule. SendMuleEvent - Sends a Mule message to the specified endpoint. If the message is synchronous, the response from Mule will be automatically stored in the "incoming" process variable. more info... org.mule.providers.bpm.jbpm.actions.SendMuleEvent StoreIncomingData - Stores the incoming message payload into the specified variable. more info... org.mule.providers.bpm.jbpm.actions.StoreIncomingData
Document generated by Confluence on Apr 24, 2008 08:11
Page 249
ValidateMessageSource - Throws an exception if the message's source is not as expected. more info... org.mule.providers.bpm.jbpm.actions.ValidateMessageSource ValidateMessageType - Throws an exception if the incoming message's class is not as expected. more info... org.mule.providers.bpm.jbpm.actions.ValidateMessageType
Document generated by Confluence on Apr 24, 2008 08:11
Page 250
Ejb Provider This page last changed on Jan 30, 2008 by ross.
The Ejb connector allows Ejb session beans to be invoked as part of an event flow. Components can be given an ejb outbound endpoint which will invoke the remote object and optionally return a result. The javadoc for this transport provider can be found here. And the Source Xref can be found here.
Ejb Connector Properties Property
Description
Default
Required
securityPolicy
The security policy file to be used
jndiInitialFactory
The Jndi factory used to access the Ejbs
(for JBoss) Yes org.jnp.interfaces.NamingContextFactory
jndiUrlPkgPrefixes
List of package prefixes to use when loading in URL context factories.
(for JBoss) Yes org.jboss.naming:org.jnp.interfaces
Yes
For example <properties> <property name="securityPolicy" value="wideopen.policy"/>
Endpoints Rmi endpoints are described as socket-based endpoints in the form of ejb://localhost:1099/[MULE:remote home name]?method=[MULE:method to invoke]
Using Rmi Connector Note that only outbound endpoints can use the Ebj transport. For a given endpoint, the following informationwill have to be written in the uri (uri path and parameter) : • • • •
registry host registry port romote home name remote method name
these values will be used to establish dispatcher connection. <endpoint address="ejb://localhost:1099/SomeService?method=remoteMethod">
If the remoteMethod can take 1 or more input arguments then they should be configured on the endpoint as list properties. This is the syntax that is proved to work in version 1.4.3, a list of comma-separated values into the property methodArgumentTypes. <properties> <list name="methodArgumentTypes"> <entry value="java.lang.String,java.lang.String,java.math.BigInteger"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 251
Multiple arguments are passed in as an array of objects as the payload of the Mule event.
Transformers There are no specific transformers required for Ejb.
Document generated by Confluence on Apr 24, 2008 08:11
Page 252
Email Provider This page last changed on Jan 30, 2008 by ross.
The email provider can be used to connect to Pop3 and Imap mailboxes and for sending events over smtp using the javax.mail api. For each of the protocol, SSL is supported and is enabled using pop3s, imaps and smtps respectively. The email connectors can be used to send and recieve event payloads over Mail protocols and support protocol features such as attachments, replyTo, CC and BCC addresses, binary content types and custom headers. The javadoc for the Mail connectors can be found here. For information about configuring specific endpoints follow the links below • Smtp and Smtps • Pop3 and Pop3s • Imap and Imaps
Document generated by Confluence on Apr 24, 2008 08:11
Page 253
File Provider This page last changed on Jan 30, 2008 by ross.
The file connector allows files to be read and written to and from directories on the local file system. The connector can be configured to filter the file it reads and the way files are written, such as whether binary output is used or the file is appended to. The javadoc for this transport provider can be found here . And the Source Xref can be found here .
File Connector Properties Property
Description
Default
moveToDirectory
The directory path where the file should be written once it has been read. if this is not set the file read is deleted.
No
writeToDirectory
The directory path where the file should be written on dispatch. This path is usually set as the endpoint of the dispatch event, however this allows you to explicitly force a single directory for the connector.
No
pollingFrequency
The frequency in milliseconds that the read directory should be checked. Note that the read directory is specified by the endpoint of the listening component.
filenameParser
Is an implementation of org.mule.providers.file. org.mule.providers.file.FilenameParser SimpleFilenameParser and is used to control how filename patterns are used to generate file names. The file provider has a default implementation called org.mule.providers.file.SimpleFilenameParser that understands the following patterns:
1000
Required
Yes
Yes
• ${DATE} - the current date in the
Document generated by Confluence on Apr 24, 2008 08:11
Page 254
•
•
•
•
•
format dd-MMyy_HH-mm-ss.SS ${DATE:yy-MMdd} - 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
outputPattern
The pattern to use when writing a file to disk. This can use the patterns supported by the filenameParser configured for this connector
${DATE} (If default is used)
Yes
moveToPattern
The pattern to use when moving a read file to an new location determined by the moveToDirectory property. This can use the patterns supported by the filenameParser configured for this connector
${DATE} (If default is used)
Yes
outputAppend
Determines whether the file being written should append to an existing file if one exists.
false
No
serialiseObjects
Determines whether objects should be serialized to the file or not. If not the raw bytes or text is written.
false
No
binary
Determines if the connector is reading or writing binary files
false
No
autoDelete
By default, when a file is received it is read into a String or byte[]. The file is moved if the moveToDirectory is set, otherwise it is deleted.
true
No
Document generated by Confluence on Apr 24, 2008 08:11
Page 255
To access the File object set this property to false and specify a NoActionTransformer transformer for the connector. Mule will not delete the file, so it's up to the component to delete it when it's done. If the moveToDirectory is set, the file is first moved, then the File object of the moved file is passed to the component. It is recommended that a moveToDirectory is specified when turning autoDelete off. fileAge
Will not process the file unless it's older than the specified age in milliseconds.
comparator
Sort incoming files using this comparator. This property contains class name (the class must implement java.util.Comparator interface). since 1.4.4
reverseOrder
set reverse order for comparator
0
No
No
false
No
File Endpoints File endpoints are expressed using standard File URI syntax file://<path>[MULE:?params]
For example, to connect to a directory called /temp/files Unix file:///temp/files
Note the extra slash to denote a path from the root (absolute path). Windows file:///C:/temp/files
The Unix style will still work in Windows if you map to a single drive (the one Mule was started from). To specify a relative path use file://./temp or file://temp (note only 2 slashes for protocol, so it's a relative path, the above syntax is preferred for readability) or
Document generated by Confluence on Apr 24, 2008 08:11
Page 256
file://?address=./temp
Windows network URIs To connect to a windows network drive use file:////192.168.0.1/temp/
Filename Filters Filters can be set on the endpoint to control what files are received by the endpoint. The filters are expressed in a comma-separated list. To set up a filter to only read .xml and .txt files the following can be used. <endpoint address="file:///inbound/myfiles">
Property Overrides You can override certain properties when defining a File receiver endpoint to control the way that particular receiver behaves. the properties that can be set on the individual endpoint are moveToDirectory, moveToPattern, pollingFrequency and autoDelete. <endpoint address="file:/./temp/myfiles"> <properties> <property name="pollingFrequency" value="30000"/> <property name="moveToDirectory" value="./temp/myfiles/done"/>
Or to specify the same Endpoint using an URI file:/./temp/myfiles?pollingFrequency=1000&moveToDirectory=./temp/myfiles/done
For more information about configuring Endpoint go here.
Transformers Transformers for the File provider can be found at org.mule.providers.file.transformers.
Transformer
Description
FileToByteArray
Reads the contents of a file as a byte array
FileToString
Reads a file's contents into a string.
The FileToByteArray is used if no other transformers are specified. It could also return the byte array as a String if the component request it.
Comparators Class
Description
org.mule.providers.file.comparator.OlderFirstComparator comparing files for equality based on their modification dates <endpoint address="file://./.mule/in"> <properties>
Document generated by Confluence on Apr 24, 2008 08:11
Page 257
<property name="comparator" value="org.mule.providers.file.comparator.OlderFirstComparator"/> <property name="reverseOrder" value="true"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 258
Ftp Provider This page last changed on Jan 30, 2008 by ross.
The FTP connector allows files to be read and written to and from remote FTP servers. The javadoc for this transport provider can be found here. And the Source Xref can be found here.
Ftp Connector Properties Property
Description
Default
Required
pollingFrequency
The frequency in milliseconds that the read directory should be checked. Note the read directory is specified by the endpoint of the listening component.
1000
Yes
filenameParser
Is an implementation of org.mule.providers.file. org.mule.providers.file.FilenameParser SimpleFilenameParser and is used to control how filename patterns are used to generate file names. The file provider has a default implementation called org.mule.providers.file.SimpleFilenameParser that understands the following patterns:
Yes
• ${DATE} - the current date in the format dd-MMyy_HH-mm-ss.SS • ${DATE:yy-MMdd} - 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 outputPattern
The pattern to use when writing a file to disk. This can use the patterns supported by the filenameParser
Document generated by Confluence on Apr 24, 2008 08:11
${DATE} (If default is used)
Yes
Page 259
configured for this connector passive
Whether to use FTP passive mode (allows to go through firewalls)
true
No
binary
Whether to use BINARY or ASCII file types for transfer
true
No
validateConnections
Whether to validate FTP connections before use. This takes care of a failed (or restarted) FTP server at the expense of an additional NOOP command packet being sent, but increases overall availability.
true
No
connectionFactoryClass
Custom FTP connection factory. This must be an instance of a standard FtpConnectionFactory. @since 1.4.1
org.mule.providers.ftp.FtpConnectionFactory No
FTP Endpoints FTP endpoints are expressed using standard FTP URI syntax ftp://<username>:<password>@/[MULE:address]
for example ftp://joe:[email protected]/~
This will connect to the FTP server at mycompany.com with a user name of joe with password 123456 and will work on Joe's home directory.
Filename Filters Filters can be set on the endpoint to control what files are received by the endpoint. The filters are expressed in a comma-separated list. To set up a filter to only read .XML and .TXT files the following can be used. <endpoint address="ftp://joe:[email protected]/ftp/incoming">
Property Overrides You can override certain properties when defining FTP endpoints to control the endpoint's configuration. These properties can be set on the endpoint or the current event.
Property
Document generated by Confluence on Apr 24, 2008 08:11
Description
Page 260
filename
When dispatching events using an FTP endpoint the filename property can be used to set the outbound filename.
outputPattern
This can be set to an output file pattern using the variables supported on the FilenameParser for this connector (see Connector Properties). If the filename property is set, this will be ignored.
pollingFrequency
Controls the polling frequency of the inbound endpoint. This can only be set on the endpoint and will be ignored if set on the event.
passive
FTP passive mode is honoured on an endpoint level as well.
binary
BINARY / ASCII file type.
For example, to set the output pattern <endpoint address="ftp://joe:[email protected]/ftp/done"> <properties> <property name="outputPattern" value="FtpFile-${DATE}.done"/>
Or to specify the same endpoint using an URI ftp://joe:[email protected]/ftp/done?outputPattern=FtpFile-${DATE}.done
For more information about configuring endpoints go here.
Document generated by Confluence on Apr 24, 2008 08:11
Page 261
Http Provider This page last changed on Jan 30, 2008 by ross.
The HTTP connector can be used to send and receive Mule events over HTTP. It has a HTTPS connector used for HTTP communication over SSL. The javadoc for this transport provider can be found here. And the Source Xref can be found here
HTTP Connector Properties See Tcp Provider for extra properties inherited by this connector.
Property
Description
Default
Required
secure
determines if the connector is using HTTPS.
false
No
proxyHostname
If access to the web is through a proxy, this holds the server address.
No
proxyPort
The port the proxy is configured on.
No
proxyUsername
If the proxy requires authentication supply a username.
No
proxyPassword
The password for the proxyUsername.
No
timeout
The socket read timeout
5000
Yes
buffersize
the buffer size used to read and write data
64*1024
Yes
HTTPS Connector Properties In addition to the above properties for the HTTP connector you can also configure server and client certificate information. You will need to use the org.mule.providers.http.HttpsConnector in your XML config file when configuring the connector.
Property
Description
Default
Required
keyStore
The location of the server keystore used to create a secure server socket
.keystore
Yes
keyPassword
The password used to check integrity and unlock the key store
Yes (if keyStore is set)
storePassword
The password for the server keystore
Yes
Document generated by Confluence on Apr 24, 2008 08:11
Page 262
keystoreType
The type of keystore being used
KeyStore.getDefaultType()Yes
keyManagerAlgorithm
The Key Manager algorithm to use
Depends on the JDK vendor, automatically discovered.
Yes (if keyStore is set)
trustManagerAlgorithm
The Trust Manager algorithm to use
The same as keyManagerAlgorithm
No
protocolHandler
The value used for Depends on the JDK java.protocol.handler.pkgsvendor, automatically discovered.
Yes
requireClientAuthenticationWhether clients should be authenitcated when connecting
true
Yes
provider
The sercurity provider object to register with the java Security manager
Depends on the JDK vendor, automatically discovered.
Yes (if keyStore is set)
clientKeyStore
The location of the client keystore. This value is used to set javax.net.ssl.keyStore
Yes (if connector is being used by a client)
clientKeyStorePassword
The password for the client keystore. This value is used to set javax.net.ssl.keyStorePassword
Yes (if clientKeyStore is set)
trustStore
The location of the trust keystore. This value is used to set javax.net.ssl.trustStore
No
trustStorePassword
The password for the trustStore. This value is used to set javax.net.ssl.trustStorePassword
trustStoreType
The type of the truststore being used
KeyStore.getDefaultType()No
explicitTrustStoreOnly
Whether to use the clientKeyStore details as the trustStore details if a trustStore hasn't been explicitly set
false
keyManagerFactory
The KeyManager factory to use. You woundn't normally set this as the KeyManagerFactory is determined based on the keyManagerAlgorithm
No
trustManagerFactory
The TrustManager factory to use.
No
Document generated by Confluence on Apr 24, 2008 08:11
(use clientKeystore)
Yes (if trustStore is set)
No
Page 263
Normally determined based on the trustManagerAlgorithm
Endpoints Http endpoints are described as socket-based endpoints in the form of http://localhost:1234
To use HTTPS instead you need to change the endpoint URI protocol and set the necessary certificate information listed above https://localhost:1234
Unlike HTTP endpoints you can't use HTTPS endpoints without having a connector declared in your configuration. The HTTPS connector class is org.mule.providers.http.HttpsConnector. The javadoc for this transport provider can be found here
Endpoint Properties Any HTTP Response Header values can be added as endpoint properties. The following is a short list of some of the most useful properties.
Property
Description
Default
http.status
This specifies the status code of the reply, for example 200 would mean that the request was successful
200
Content-Type
This specifies the type of payload being sent in the Http Response
text/plain
Location
This property needs to be set if we what to make use of redirection, since here we define the address where the client will be redirected. See MULECB:Http Redirection for more details.
The following is a short example, depicting how to set these properties on the endpoint. <endpoint address="http://localhost:8080/mine" synchronous="true"> <properties> <property name="Content-Type" value="text/html"/> <property name="Location" value="http://mule.codehaus.org/"/> <property name="http.status" value="307"/>
In this case, the type of the payload is that of text/html & we are also instructing the client to redirect ('http.status' being set to 307 = temporary redirection) to "http://mule.codehause.org".
Security If you want to secure requests to your Http endpoint the http connector supports Http Basic/Digest authentication methods (as well as the Mule generic header authentication). If you want to configure Http Basic you need to configure a Security Endpoint Filter on a http endpoint. <endpoint address="http://localhost:4567">
Document generated by Confluence on Apr 24, 2008 08:11
Page 264
<security-filter className="org.mule.extras.acegi.filters.http.HttpBasicAuthenticationFilter"> <properties> <property name="realm" value="mule-realm"/>
You'll need to configure a security manager on the Mule instance for this security filter to authenticate against. For information about security configuration options and examples see Mule Security. For general information about Endpoint configuration see Mule Endpoints.
Sending Credentials If you want to make a Http request that requires authentication, you can set the credentials on the endpoint http://user:[email protected]/secure
Polling Http Services The Http transport supports Polling a Http URL, this is useful to grab periodic data from a page that changes of to invoke a REST service such as polling an Amazon Queue. To configure the Http Polling receiver you must include a HttpConnector configuration in your MuleXml. <properties> <map name="serviceOverrides"> <property name="message.receiver" value=" org.mule.providers.http.PollingHttpMessageReceiver"/>
To use the connector in your endpoints use http://anothercompany.com/services?connector=pollingHttp&pollingFrequency=30000
The equivalent explicit endpoint configuration would look like <endpoint address="http://anothercompany.com/services" connector="pollingHttp"> <properties> <property name="pollingFrequency" value="30000"/>
Transformers The following transformers are available for use. Their javadoc can be found here
Transformer
Description
HttpClientMethodResponseToObject
Transforms an HTTP client response to an object, specifically, a Mule Message.
HttpResponseToString
Transforms an HTTP client response to a string.
UMOMessageToHttpResponse
Transforms an object that implements UMOMessage to an HTTP Response
Document generated by Confluence on Apr 24, 2008 08:11
Page 265
If you're writing your own transformer which changes the length of HTTP Post request, don't forget to set correct Content-Length header or remove this header at all (it will be set automatically).
Handling HTTP Content-Type and Encoding Sending HTTP (since Mule 1.3 RC2) This is both for sending POST request bodies as a client and when returning a response body: If we have a String, char[], Reader or similar: If the endpoint has an encoding explicitly set, use that Otherwise take it from the MuleMessage's property Content-Type If none of these are set, use the MuleManager's configuration default. For Content-Type, send the MuleMessage's property _Content-Type_but with the actual encoding set. (and splice it with the Content-Type, if need be) • If Content-Type property is set, send text/plain (or perhaps auto-detect XML?) • • • •
For binary content, encoding is not relevant. Content-Type is set as follows: • If the "Content-Type" property as set on the message, send that. • Send "application/octet-stream" as Content-Type if none is set on the message.
Receiving HTTP (since Mule 1.3 RC2) This is both for receiving POST requests (as server) and when getting the response bodies as a client: If Content-Type header is received: • Set on the message's property Content-Type • For text content (starts with "text/"), decode the payload to a String, using the specified encoding. • If no encoding is set, use ISO-8859-1 as is default in HTTP for text content, unless the encoding is explicitly on the endpoint. If the Content-Type header is not present: • Don't set the "Content-Type" property. • Load as byte oriented payload.
Document generated by Confluence on Apr 24, 2008 08:11
Page 266
Imap Provider This page last changed on Jan 30, 2008 by ross.
The IMAP transport provider can be used to for receiving messages from IMAP inboxes and connecting to IMAP mailboxes using SSL (IMAPs) using the javax.mail api. The javadoc for this provider can be found here. org.mule.providers.email.ImapConnector.
Imap Connector Properties Property
Description
Default
Required
mailboxFolder
The remote mailbox folder to connect to.
INBOX
Yes
backupEnabled
Copy messages to backupFolder (below)?
No
No
backupFolder
This refers to a file system folder to backup consumed mail messages to. This is really only for audit purposes.
<Mule's workdir>/mail/
No
checkFrequency
Determines how often the Pop3 mailbox is polled for new messages. the value is represented in milliseconds.
60000
Yes
authenticator
Is used when setting up a Mail session. By default Mule handles authentication by creating a default Authenticator if there are user credentials set on the Pop3 endpoint (see below). Users can customise the authenticator if needed by setting this to their own authenticator implementation. Authenitcators must implement javax.mail.Authenticator
deleteReadMessages
whether to delete messages once they have been read. Otherwise they are marked as SEEN. The bahaviour of different mail servers differs and on some mail servers setting the SEEN flag
Document generated by Confluence on Apr 24, 2008 08:11
No
true
No
Page 267
seems to have no effect.
Server Credentials The host, port and user credentials as set on the imap:// endpoint. If no port is specifed the default port will be used.
Imaps Connector Properties The Imaps Connector enables Imap over SSL using the javax.mail APIs. It supports all the properties of the Imap connector and has some additional properties for setting up an SSL connection.
Property
Description
Default
Required
socketFactory
The SSL socket factory to use
javax.net.ssl.SSLSocketFactory No
socketFactoryFallback
Whether to enable fallback
false
trustStore
The flie location of a trust store
No
trustStorePassword
The password for the trust store
No
No
When using the Imaps Connector the default port is set to 993.
Imap(s) Endpoints Imap endpoints describe details about the connecting to a Imap mailbox. Imap URIs use the following syntax imap://<user:password>@[MULE::port]/<mail folder>[MULE:?params]
The format is the same for IMAPs imaps://<user:password>@[MULE::port]/<mail folder>[MULE:?params]
Escape your credentials Sometimes you'll have illegal (for URI) characters in your login/password. Use the standard escape syntax your browser would use, e.g. the username user@mule would become user %40mule. For example, imaps://joe:[email protected]/mail?checkFrequency=30000
This will log into the imap.mycompany.com server with username joe using password 123456 (using default IMAPs port) and open the mail folder. It will check the mailbox for new messages every 30 seconds. To set additional properties on the endpoint, you can set them as parameters on the URI but we recommend you set them as endpoint properties to make it easier to read and maintain the configuration. <endpoint address="imaps://username:[email protected]/mail"> <properties> <property name="checkFrequency" value="120000"/> <property name="trustStore" value="./trustore"/> <property name="trustStorePassword" value="trustNoOne"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 268
Filters Filters can be set on an endpoint to filter out any unwanted messages. The Mail transport provider has a couple of Email filters that can either be used directly or extended to implement custom filtering rules.
Filter
Description
org.mule.providers.email.filters. AbstractMailFilter
A base filter implementation that must be extended by any other mail filter.
org.mule.providers.email.filters. MailSubjectRegExFilter
Will filter messages based on their subject matching a regex filter.
Configuring Filters The following demonstrates to only accept messages where the email subject starts with [MULE:mule] <endpoint address="imaps://username:[email protected]/lists"> <properties> <property name="checkFrequency" value="120000"/> <property name="trustStore" value="./trustore"/> <property name="trustStorePassword" value="trustNoOne"/>
Transformers There are a couple of transformers provided with the Email transport that are useful for converting javax.mail.Message to Mule event payloads. These transformers will extract the message body and properties (including headers) and handle attachments too. If you need to customise the behaviour of these transformers it is recommended that you extends the existing transformers rather than reimplement them.
Transformer
Description
org.mule.providers.email.transformers. EmailMessageToString
Converts a javax.mail.Message to String message payload. This transformer doesn't support attachements and is deprecated in favour of the MimeMessageToObject transformer
Converting a MimeMessage to a UMOMessage
The MessageAdapter for Pop3 is responsible for decomposing a MimeMessage to a UMOMessage. the first body part is used as the payload and all subsequent parts are added as attachments. The mimEMessage headers are added to the UMOMessage properties.
Document generated by Confluence on Apr 24, 2008 08:11
Page 269
Jdbc Provider This page last changed on Apr 16, 2008 by quoc.
The Jdbc provider can be used to connect to relational databases using jdbc. It supplies reads and writes to simple tables with acknowledgement of read rows. The javadoc for this transport provider can be found here. And the Source Xref can be found here
Jdbc Connector properties Property
Description
jndiContext
The JNDI context to use. This can be set on the connector directly, else it will be created using the jndiInitialFactory, jndiProviderUrl and providerProperties properties
No
jndiInitialFactory
Defines the initial context factory to use when retriving objects, such as DataSource from your JNDI context.
Yes (if using jndi)
jndiProviderUrl
Your JNDI provider url.
Yes (if using jndi)
providerProperties
Any other properties to pass to the initialial context. properties such as java.naming.username and java.naming.password can be set here.
No
dataSourceJndiName
The name of the JNDI configured data source to use.
Yes (if using jndi)
dataSource
The Jdbc data source to use. This can be set on the connector directly so that Jndi properties are not needed. When using XA transactions, an XADataSource object must be provided.
No (if using jndi)
pollingFrequency
The delay in milliseconds that will be used during two subsequent polls to the database
No
queries
A map specifying preconfigured sql queries.
No
Document generated by Confluence on Apr 24, 2008 08:11
Default
Required
Page 270
These queries can also be set on endpoints. (see below) resultSetHandler
A fully qualified class name of the ResultSetHandler used to pass back query results. For more information about this object see the examples.
org.apache.commons.dbutils.handlers. No MapListHandler
queryRunner
A fully qualified class name of the QueryRunner to use when executing a Query. For more information about this object see the examples.
org.apache.commons.dbutils.QueryRunner no
Jdbc Endpoint properties Property
Description
queries
A map specifying preconfigured sql queries for this endpoint. These will override any configured queries on the connector.
Default
Required No
Configuring queries Sql queries are used by endpoints and should be configured on the connector or the endpoint. Queries are stored in a map and keyed by their name. This name will be retrieved from the address of the endpoint. There are three types of queries: • read queries: these are select statements • ack queries: for each row read this query will be executed and can be an update or a deletestatement. These queries are associated with a read query. The ack query corresponding to a given read query is identified by the name of the read query followed by a .ack suffix. • write queries: these are usually insert statements that can be used on outbound endpoints The queries can be parameterized using a simple syntax. Parameters can be enclosed in a ${...} pattern. When the query is executed, each parameter will be looked for in the following way: • check if the given parameter has been included as a parameter in the endpoint uri • if there is an input (ack and write queries), evaluate the expression as a java bean property on the input For ack queries, the input is defined as the payload that will be sent as an UMOMessage. If you want to access a specific column that has been read, you can thus use the expression ${myColumn} which will be evaluated on the message. For write queries, the input is defined as the UMOMessage itself. If you want to access to the whole payload, you can thus use the expression ${payload} which will be evaluated on the message.
Document generated by Confluence on Apr 24, 2008 08:11
Page 271
A special expression ${NOW} can be used to create a timestamp based on the current date and time.
Using unnamed queries Sql statements can also be executed without configuring queries. For a given inbound endpoint, the query to execute can be specified as the address of the URI. UMOMessage msg = eventContext.receiveEvent("jdbc://SELECT * FROM TEST", 0);
Using the jdbc connector Creating the connector To use the jdbc connector, you must first configure the connector in the mule xml configuration file. If you use a dataSource configured in spring for example <properties>
DataSources can be easily created in spring using xapool: <property name="driverName">org.hsqldb.jdbcDriver <property name="url">jdbc:hsqldb:file:db/test
else, to retrieve the dataSource from a jndi repository, you would use <properties> <property name="jndiInitialFactory" value="..."/> <property name="jndiProviderUrl" value="..."/> <property name="dataSourceJndiName" value="..."/>
Alternatively, you can use the Jndi Container to simplify configuration.
Creating queries Sql queries used by endpoints should be configured on the connector or the endpoint. <map name="queries"> <property name="getTest" value="SELECT ID, TYPE, DATA, ACK, RESULT FROM TEST WHERE TYPE = ${type} AND ACK IS NULL"/> <property name="getTest.ack" value="UPDATE TEST SET ACK = ${NOW} WHERE ID = ${id} AND TYPE = ${type} AND DATA = ${data}" /> <property name="writeTest" value="INSERT INTO TEST(ID, TYPE, DATA, ACK, RESULT) VALUES(NULL, ${type}, ${payload}, NULL, NULL)" />
Creating components For a receiver,
Document generated by Confluence on Apr 24, 2008 08:11
Page 272
<mule-descriptor name="..." implementation="..." inboundEndpoint="jdbc://getTest?type=1" outboundEndpoint="..."/>
For a dispatcher <mule-descriptor name="..." implementation="..." inboundEndpoint="..." outboundEndpoint="jdbc://writeTest?type=1" />
Document generated by Confluence on Apr 24, 2008 08:11
Page 273
Jms Provider This page last changed on Jan 30, 2008 by ross.
This is a standard Jms 1.0.2b and 1.1 connector. This connector exposes all features defined in the 1.0.2b/1.1 Specification. The javadoc for this transport provider can be found here. And the Source Xref can be found here.
Property
Description
acknowledgementMode
Determine the type 1 of acknowledegement made when a message is received. The Jms Specification identifies 4 possible values Session.TRANSACTED (0) The acknowledgement mode is ingored by the session. This constant was introduced in Jms 1.1 but the value is valid in Jms 1.0.2b. Session.AUTO_ACKNOWLEDGE (1) - the session automatically acknowledges a client's receipt of a message either when the session has successfully returned from a call to receive or when the message listener on the session has called to process the message successfully returns. Session.CLIENT_ACKNOWLEDGE (2) - the client acknowledges a consumed message by calling the message's acknowledge method. Session.DUPS_OK (3) instructs the session to lazily acknowledge the delivery of messages.
No
persistentDelivery
Determines whether the underlying JMS provider will store a message to a persistent storage as part of the send operation. There is a performance overhead in persisting messages, so it should only be used in situations where the receiving application will have problems if the message is not
No
Document generated by Confluence on Apr 24, 2008 08:11
Default
false
Required
Page 274
delivered. Setting this value to true will enable persistent delivery, false to disable it. honorQosHeaders
Determines whether JmsMessageDispatcher will copy QoS headers (JMSPriority, JMSDeliveryMode) from the original message to the outgoing one. If inbound endpoint is not JMS endpoint, then outgoing message will have default QoS headers. Note that in the last case delivery mode will be determined by persistentDelivery property. (since Mule 1.4.2)
false
No
specification
The jms specification supported by your jms server. This can either be 1.0.2b or 1.1
1.0.2b
No
durable
If a client needs to receive all the messages published on a topic, including the ones published while the subscriber is inactive, it uses a durable TopicSubscriber. The JMS provider retains a record of this durable subscription and insures that all messages from the topic's publishers are retained until they are acknowledged by this durable subscriber or they have expired. Setting this value to true will ensure that all topic subscribers that use this connector will be durable (unless durable properties are overriden on the endpoint. See below)
false
No
clientId
Used to uniquely identify the client for this connection. It must be set when using durable subscribers. Often the jms provider will set this, but for
Document generated by Confluence on Apr 24, 2008 08:11
Yes (if using durable)
Page 275
some jms servers you may need to set this yourself. If the value you set is not unique to the Jms Server a javax.jms.InvalidClientIDException is thrown. noLocal
The subscriber noLocal attribute allows a subscriber to inhibit the delivery of messages published by its own connection.
false
No
jndiInitialFactory
Defines the initial context factory to use when retriving objects, such as JmsConnectionFactory from your JNDI context. If you set the connectionFactory
Yes (if using jndi)
jndiProviderUrl
Your JNDI provider url.
Yes (if using jndi)
jndiProviderProperties
Any other properties to pass to the initial context. Properties such as java.naming.username and java.naming.password can be set here.
No
connectionFactoryProperties Any properties to be passed to the javax.jms.ConnectionFactory, e.g. to set some vendor-specific properties.
No
connectionFactoryJndiName The name of the JNDI configured connection factory to use.
Yes (if using jndi)
connectionFactory
The Jms connection factory to use. This can be set on the connector directly so that Jndi properties are not needed.
No (if using jndi)
connectionFactoryClass
Native connection factory class name (e.g. for standalone WebSphere MQ, Sun Message Queue), when no JNDI or IoC container is being used. (since Mule 1.3)
No
jndiDestinations
Determines if jndi destinations are being
Document generated by Confluence on Apr 24, 2008 08:11
false
No
Page 276
used. this will casue jms queues and topics to be loaded from the jndi context. If the destination is not found a default nonjndi destination will be created. forceJndiDestinations
This property in conjunction with the jndidestinations property causes an exception to be thrown if a jndi destination is not found when set to true
username
The username used when creating a connection
No
password
The password used when creating a connection
No
maxRedelivery
When a message is rolled back to the destination it was consumed from the JMSRedelivered flag is set on the message. Mule will then reconsume the message and attempt to process it again. This property defines how many times Mule will try processing the message before throwing an exception to be processed by the connectors exception handler (where the message can be logged and/or forwarded to an error queue)
redeliveryHandler
Developers can org.mule.proivders.jms. No override the default DefaultRedeliveryHandler redelivery behaviour by implementing the interface org.mule.providers.jms.RedeliveryHandler and then setting this property to the fully qualified classname of their handler implementation.
recoverJmsConnections
A flag telling Mule if JMS connection recovery should be attempted. The only
Document generated by Confluence on Apr 24, 2008 08:11
false
0
true
No
No
No
Page 277
reason you would want to disable it is to play nicely with some JMS in-container implementations restricting you (e.g. WebSphere Embedded MQ). @since Mule 1.3
Using Topics, Queues or both When specifying a destination name and JndiDestinations are not being used the default destination created is a Queue. For example the Jms endpoint jms://my.destination
will manifest itself as a Jms Queue called my.destination. To make this a topic you must prepend the destination name with topic:jms://topic:my.destination
If you are using a Jms 1.1 compliant server you can use the same JmsConnector for queues and topics. If you are using a Jms 1.0.2b server and you want to use both queues and topics in your Mule configuration, you will need to create 2 JmsConnectors; one with a jndiConnectionfactory that references a QueueConnectionFactory and the other that references a TopicConnectionfactory. Then each Jms endpoint will need to reference the correct connector depending on whether the destination is a topic or a queue. To specify the conector on a jms endpoint you need to add the connector parameter jms://my.destination?connector=jmsQueueConnector or jms://topic:my.destination?connector=jmsTopicConnector
Specifying Credentials Client connections may need to supply a username and password when creating a connection. This information can be specified on the URI. jms://ross:[email protected]?createConnector=ALWAYS or jms://ross:secret@topic:my.destination?createConnector=ALWAYS
Note that the 'createConnector' param is set to 'ALWAYS'. This ensures that a new connection is made with the user credentials. When creating JmsConnectors more information is is needed such as ConnectionFactory Jndi details. This can be set as parameters on the URI, but this can get difficult to manage not to mention messy. It is possible to set default properties for connectors when they are created. For more information see this Jms cookBook entry. See Mule Endpoint URIs for more general information about configuring endpoint URIs.
Jms Selectors You can set a Jms selector as a filter on an endpoint. The JmsSelectorFilter simply sets the filter expression on the consumer. <endpoint address="jms://important.queue">
Document generated by Confluence on Apr 24, 2008 08:11
Page 278
Below is the old way of setting a Jms selector on an endpoint, but is still supported for backward compatibility. Also, setting the selector as a URI param can still be useful. To set it on an explicitly configured endpoint as a property of that endpoint <endpoint address="jms://important.queue"> <properties> <property name="selector" value="JMSPriority=9"/>
Or to specify the same provider using a uri jms://important.queue?selector=JMSPriority=9
Durable Subscribers Durable subscribers can be used by setting the durable property on the JmsConnector, this tells it to make all topic subscribers durable. Only Topic subscriptions can be durable. When a durable subcriptions a durableName is needed by the Jms server to identfy this subscriber. By default, Mule generates a durableName in the following form mule..
However, if you want to set the durableName yourself, you can do so on the endpoint by setting the durableName property. <endpoint address="jms://topic:durable.topic"> <properties> <property name="durableName" value="myDurableSubscription"/> or the equivilent
-
jms://topic:durable.topic?durableName=myDurableSubscription
You can also specify certain endpoints to be durable while others are not by setting the durable property on the JmsConnector to false and then setting the durable property on the individual endpoints. <endpoint address="jms://topic:durable.topic"> <properties> <property name="durable" value="true"/> or the equivilent
-
jms://topic:durable.topic?durable=true
Overloading Jms behaviour Some Jms servers require a different sequence of calls when creating Jms resources, for example Oracle's Advanced Queuingrequires that the connection is started before listeners can be registered. In this scenario the user can overload the JmsSupport class to customise the way Jms resources are initialised. Configuring this customisation requires that you tell the JmsConnector to use a custom JmsSupport class. <properties> <property-factory name="jmsSupport" value="org.foo.jms.CustomJmsSupport"/> ...
For more information about configuring different Jms Servers go here. For more information about configuring providers go here.
Document generated by Confluence on Apr 24, 2008 08:11
Page 279
Jms Transformers Transformers for the JMS provider can be found at org.mule.providers.jms.transformers
Transformer
Description
JMSTransformer
This is a base class that provides general JMS message transformation support. If want you can extend this for your own specialised Jms Transfromers but usually the defaults are sufficient.
JMSMessageToObject
Will convert a javax.jms.Message or sub-type into an object by extracting the message payload. Users of this transformer can set different return types on the transform to control the way it behaves. javax.jms.TextMessage - java.lang.String javax.jms.ObjectMessage - java.lang.Object javax.jms.BytesMessage - Byte[]. Note that the transformer will check if the payload is compressed and automatically uncompress the message. javax.jms.MapMessage - java.util.Map javax.jms.StreamMessage - java.util.Vector of objects from the Stream Message.
ObjectToJMSMessage
Will convert any object to a javax.jms.Message or sub-type into an object. One of the 5 types of JMS message will be created based on the type of Object passed in. java.lang.String - javax.jms.TextMessage byte[] - javax.jms.BytesMessage java.util.Map - javax.jms.MapMessage java.io.InputStream - javax.jms.StreamMessage javalang.Object - javax.jms.ObjectMessage
Jms Header Properties When the message is received and transformed all the message properties are still available via the UMOMessage object. To access sandard Jms properties such as JMSCorrelationID and JMSRedelivered simply use the property name i.e. String corrId = (String)umoMessage.getProperty("JMSCorrelationID"); boolean redelivered = umoMessage.getBooleanProperty("JMSRedelivered");
any custom header properties on the message can be accessed the same way.
Document generated by Confluence on Apr 24, 2008 08:11
Page 280
Multicast Provider This page last changed on Jan 30, 2008 by ross.
The multicast connector can be used to send and receive mule events via multicast groups. The javadoc for this provider can be found here.
Multicast Connector Properties Property
Description
Default
Required
timeout
The socket read timeout
5000
Yes
bufferSize
the buffer size used to read and write data
64*1024
Yes
retryCount
The number of times to try and connect a listener to a socket
2
Yes
retryFrequency
The number of milliseconds to wait beween retries
2000
Yes
loopback
Enable local loopback of multicast datagrams. The option is used by the platform's networking code as a hint for setting whether multicast data will be looped back to the local socket.
false
No
Transformers The following transformers are used by default for this connector unless a transformer is explicitly set on the provider.
Transformer
Description
ByteArrayToString
Converts a byte array to a String
StringToByteArray
Converts a String to a byte array
Document generated by Confluence on Apr 24, 2008 08:11
Page 281
Pop3 Provider This page last changed on Jan 30, 2008 by ross.
The Pop3 transport provider can be used to for receiving messages from POP3 inboxes and connecting to POP3 mailboxes using SSL (POP3s) using the javax.mail api. The javadoc for this provider can be found here. org.mule.providers.email.Pop3Connector.
Pop3 Connector Properties Property
Description
Default
Required
backupEnabled
Copy messages to backupFolder (below)?
No
No
backupFolder
This refers to a file system folder to backup consumed mail messages to. This is really only for audit purposes.
checkFrequency
Determines how often the Pop3 mailbox is polled for new messages. the value is represented in milliseconds.
authenticator
Is used when setting up a Mail session. By default Mule handles authentication by creating a default Authenticator if there are user credentials set on the Pop3 endpoint (see below). Users can customise the authenticator if needed by setting this to their own authenticator implementation. Authenitcators must implement javax.mail.Authenticator
deleteReadMessages
whether to delete messages once they have been read. Otherwise they are marked as SEEN. The bahaviour of different mail servers differs and on some mail servers setting the SEEN flag seems to have no effect.
Document generated by Confluence on Apr 24, 2008 08:11
No
60000
Yes
No
true
No
Page 282
Server Credentials The host, port and user credentials as set on the pop3:// endpoint. If no port is specifed the default port will be used.
Pop3s Connector Properties The Pop3s Connector enables Pop3 over SSL using the javax.mail APIs. It supports all the properties of the Pop3 connector and has some additional properties for setting up an SSL connection.
Property
Description
Default
Required
socketFactory
The SSL socket factory to use
javax.net.ssl.SSLSocketFactory No
socketFactoryFallback
Whether to enable fallback
false
trustStore
The flie location of a trust store
No
trustStorePassword
The password for the trust store
No
No
When using the Pop3s Connector the default port is set to 995.
Pop3(s) Endpoints Pop3 endpoints describe details about the connecting to a Pop3 mailbox. Pop3 URIs use the following syntax pop3://<user:password>@<pop3 server>[MULE::port][MULE:?params]
The format is the same for POP3s pop3s://<user:password>@<pop3 server>[MULE::port][MULE:?params]
Escape your credentials Sometimes you'll have illegal (for URI) characters in your login/password. Use the standard escape syntax your browser would use, e.g. the username user@mule would become user %40mule. For example to connect to a Google gmail box you need to use POP3s, pop3s://muletestbox:[email protected]?checkFrequency=30000
This will log into the muletestbox mailbox on pop.gmail.com using password 123456 (using default POP3s port) and will check the mailbox for new messages every 30 seconds. To set additional properties on the endpoint, you can set them as parameters on the URI but we recommend you set them as endpoint properties to make it easier to read and maintain the configuration. <endpoint address="pop3s://username:[email protected]"> <properties> <property name="checkFrequency" value="120000"/> <property name="trustStore" value="./trustore"/> <property name="trustStorePassword" value="trustNoOne"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 283
Filters Filters can be set on an endpoint to filter out any unwanted messages. The Mail transport provider has a couple of Email filters that can either be used directly or extended to implement custom filtering rules.
Filter
Description
org.mule.providers.email.filters. AbstractMailFilter
A base filter implementation that must be extended by any other mail filter.
org.mule.providers.email.filters. MailSubjectRegExFilter
Will filter messages based on their subject matching a regex filter.
Configuring Filters The following demonstrates to only accept messages where the email subject starts with [MULE:mule] <endpoint address="pop3s://username:[email protected]"> <properties> <property name="checkFrequency" value="120000"/> <property name="trustStore" value="./trustore"/> <property name="trustStorePassword" value="trustNoOne"/>
Transformers There are a couple of transformers provided with the Email transport that are useful for converting javax.mail.Message to Mule event payloads. These transformers will extract the message body and properties (including headers) and handle attachments too. If you need to customise the behaviour of these transformers it is recommended that you extends the existing transformers rather than reimplement them.
Transformer
Description
org.mule.providers.email.transformers. EmailMessageToString
Converts a javax.mail.Message to String message payload. This transformer doesn't support attachements and is deprecated in favour of the MimeMessageToObject transformer
Converting a MimeMessage to a UMOMessage
The MessageAdapter for Pop3 is responsible for decomposing a MimeMessage to a UMOMessage. the first body part is used as the payload and all subsequent parts are added as attachments. The mimEMessage headers are added to the UMOMessage properties.
Document generated by Confluence on Apr 24, 2008 08:11
Page 284
Quartz Provider This page last changed on Mar 11, 2008 by yuenchi.lian.
Quartz provider supplies scheduling features to Mule. This provider is based on the great scheduler Quartz from OpenSymphony. The javadoc for this transport provider can be found here. And the Source Xref can be found here
Quartz Connector properties Property
Description
Default
Required
factoryClassName
The class name of the scheduler factory. You will usually not change this property.
org.quartz.impl.StdSchedulerFactory No
factoryProperties
a Properties object used to customize the scheduler factory.
No
factory
You can give here an instance of org.quartz.SchedulerFactory if you have one.
No
scheduler
The scheduler property can be set to an existing scheduler.
No
Quartz Endpoint properties Property
Description
cronExpression
The cron expression to schedule events at specified dates / times.
One of cron or repeatInterval
repeatInterval
The number of milliseconds between two events
One of cron or repeatInterval
repeatCount
The number of events to be scheduled. This value defaults to -1 which means that the events will be scheduled indefinitely.
-1
No
startDelay
The number of milliseconds that will elapse before the first event is fired.
0
No
groupName
The group name of the scheduled job
mule
No
mule
No
jobGroupName
Document generated by Confluence on Apr 24, 2008 08:11
Default
Required
Page 285
The job group name of the scheduled job Additionally, other properties need to be set depending on the type of Job being used. The following describes the standard Mule Jobs and how to configure them.
Jobs Mule provides a number of default Job implementations that help orchestrate scheduled events • Mule Receiver Job - An inbound endpoint job that schedules events to a Mule component • Delegating Job - And outbound endpoint job that will schedule a job that is attached to the Mule Event. • Mule Client Dispatch Job - An outbound endpoint job that will dispatch the event on a given endpoint URI. • Mule Client Receiver Job - An outbound endpoint job that will perform a receive on an endpoint and then will dispatch the result over a different endpoint. The following describes the configuration of each.
Mule Receiver Job This is the Job used when an inbound quartz endpoint is configured on a component. It triggers an event to be received by the component based on the endpoint configuration. A simple endpoint can be configured this way: <endpoint address="quartz:/myService"> <properties> <property name="repeatInterval" value="1000" /> <property name="payloadClassName" value="com.foo.bar.Payload" />
The same endpoint can also be expressed as a simple URI <endpoint address="quartz:/myService?repeatInterval=1000&payloadClassName=com.foo.bar.Payload" />
Configuring the Payload of the Event The payload can be set on the endpoint using the following mutually exclusive properties -
Property
Description
payload
The value of this property will be used
payloadRef
A reference name to an object in a container context such as Jndi, Spring or Classloader container.
If neither of these properties are set an org.mule.providers.NullPayload will be used.
Mule Delegating Job Extracts the Job object to invoke Mule Event that was dispatched to the quartz endpoint. The job can either be set as a property on the event (this property can be a container reference or the actual job object) or the payload
Document generated by Confluence on Apr 24, 2008 08:11
Page 286
of the event can be the Job, in which case when the job is fired the resulting event will have a org.mule.providers.NullPayload payload. The following properties can be set on the MuleEvent before the event is dispatched to quartz -
Property
Description
jobObject
An instance of the Job to be invoked.
jobRef
A reference name to a Job object in a container context such as Jndi, Spring or Classloader container.
If the Job is set as the payload of the event, these properties will be ignored and the DelegatingJob will be used automatically. To explicitly configure the Delegating Job, you need to configure an outbound endpoint <endpoint name="schedulerEndpoint" address="quartz:/myService"> <properties> <property name="jobClass" value="org.mule.providers.quartz.jobs.DelegatingJob"/> <property name="jobRef" value="com.foo.MyQuartzJob"/> <property name="repeatInterval" value="10000"/>
Mule Client Dispatch Job Can be used to schedule a one-off or repeated message dispatch to a Mule endpoint. To Configure this Job you add an outbound endpoint with the following configuration <endpoint name="schedulerEndpoint" address="quartz:/myService"> <properties> <property name="jobClass" value="org.mule.providers.quartz.jobs.MuleClientDispatchJob"/> <property name="jobDispatchEndpoint" value="vm://service.X"/> <property name="repeatInterval" value="10000"/> <property name="repeatCount" value="5"/>
The additional properties set are -
Property
Description
jobClass
The job class to schedule for execution.
jobDispatchEndpoint
This is a property required by the org.mule.providers.quartz.jobs.MuleClientDispatchJob and specifies where to send the dispatch event
The event payload dispatched with be the same event that triggered the sheduling of the job. The payload will also be the same for each execution of the job. Usually, this Job will be used for one-off execution, to delay event delivery to a later date/time.
Mule Client Receive Job Is similar to the MuleClientDispatchJob but will first perform a receive on an endpoint before doing a dispatch. The dispatch will not happen if the receive yielded null. <endpoint name="schedulerEndpoint" address="quartz:/myService"> <properties>
Document generated by Confluence on Apr 24, 2008 08:11
Page 287
<property name="jobClass" value="org.mule.providers.quartz.jobs.MuleClientReceiveJob"/> <property name="jobReceiveEndpoint" value="jms://queue.X"/> <property name="jobReceiveTimeout" value="10000"/> <property name="jobDispatchEndpoint" value="vm://service.X"/> <property name="repeatInterval" value="10000"/>
The configuration is the same as for MuleClientDispatchJob except there a couple of new parameters -
Property
Description
jobReceiveEndpoint
The endpoint URI (or endpoint identifier) that will be used to receive the event payload before doing a dispatch.
jobReceiveTimeout
The number of milliseconds to wait on the receive before timing out the request and returning null.
Cron Expressions A cron endpoint can be configured this way <endpoint address="quartz:/myService"> <properties> <property name="cronExpression" value="0 0 2 * * ?" /> ....
The cronExpression property syntax is detailed here.
Quartz Scripting Example Here is an example of using Quartz in conjunction with Groovy (thanks to Glenn Murry!) <mule-configuration id="Script_Sample" version="1.0"> <description> This Mule sample config shows how to use the Quartz provider to schedule a script. <endpoint name="quartz.in" address="quartz:/myService"> <properties> <property name="repeatInterval" value="2000" /> <property name="repeatCount" value="4" /> <property name="startDelay" value="3000" /> <property name="payloadClassName" value="" /> <model name="sample"> <mule-descriptor name="scriptRunner" implementation="org.mule.components.script.jsr223.ScriptComponent">
Document generated by Confluence on Apr 24, 2008 08:11
Page 288
<properties> <property name="scriptEngineName" value="groovy"/> println "Yo!"
Document generated by Confluence on Apr 24, 2008 08:11
Page 289
Rmi Provider This page last changed on Jan 30, 2008 by ross.
The rmi connector can be used to send and receive mule events over jrmp. *However, currently only dispatcher operation is being implemented
Rmi Connector Properties Property
Description
securityPolicy
The security policy file to be used
Default
Required Yes
Endpoints Rmi endpoints are described as socket-based endpoints in the form of rmi://localhost:1099
Using Rmi Connector TODO incomplete usage guide
For a dispatcher: For a given endpoint (outbound), several info will have to be written in the uri (uri path and parameter) : • • • •
registry host registry port service name (jndi object name) remote method name
these values will be used to establish dispatcher connection. <endpoint address="rmi://localhost:1099/SomeService?method=remoteMethod">
If remoteMethod can take 1 or more input arguments then they should be configured on the endpoint as list properties. <properties> <list name="methodArgumentTypes"> <entry value="java.lang.String"/> <entry value="java.lang.String"/>
Transformers There are no specific transformers for Rmi at the moment.
Document generated by Confluence on Apr 24, 2008 08:11
Page 290
SalesForce Connector This page last changed on Jan 30, 2008 by ross.
SalesForce Connector Now available on MuleForge.
Document generated by Confluence on Apr 24, 2008 08:11
Page 291
Servlet Provider This page last changed on Apr 18, 2008 by tcarlson.
The servlet connector is really just facade to a Sevlet implementation. The implementing servlet does the work of receiving a request, the connector can then hand-off the request to any receivers registed with it. There is no notion of a dispatcher for this connector, it is triggered by a request and may or may not return a response. Mule provides a REST style service implementation that uses the servlet connector. For more information see MULE:Mule REST. The javadoc for this transport provider can be found here . And the Source Xref can be found here . The connector class name is org.mule.providers.http.servlet.ServletConnector .
Servlet Connector Properties Property
Description
servletUrl
The full Url that the MuleReceiverServlet is mapped to.
Default
Required Yes
For more information about using Mule with Servlet containers, see MULEINTRO:Embedding Mule in a Webapp.
Document generated by Confluence on Apr 24, 2008 08:11
Page 292
SFTP Connector This page last changed on Jan 30, 2008 by ross.
SFTP Connector Now available on MuleForge.
Document generated by Confluence on Apr 24, 2008 08:11
Page 293
SFTP Connector Example This page last changed on Jan 30, 2008 by ross.
Background This example demonstrates sending and receiving a file message from an SFTP service, using the Mule SFTP Connector. This is a simple example that accepts text input from the console, then dispatches that text input as a file to an SFTP service. Then, the same file is received from the SFTP service and printed to the console.
Running the SFTP Connector Sample Note: Please make sure you have completed all the steps of the SFTP Connector Installation before proceeding. The starting directory for this sample is the "examples" directory, found in either your SFTP Connector zip directory if you installed from binary, or your Subversion workspace if you built from source. 1. Open conf/mule-sftp-examples-config.xml in a text editor. Change the sftp endpoint URIs to match your sftp service (there are 2 of them, so make sure to change them both). For this example, use the same directory for both the inbound and outbound sftp endpoints. <endpoint address="sftp://user:password@host/path/to/dir" connector="sftpConnector" />
For most Unix/Linux sftp services, ~/path/to/dir above would translate to the absolute path of /path/to/dir. Using FreeSSHd on Windows, you set the base path for all users, so /path/ to/dir would be relative to that base. | Make sure the user has permissions to access the directory specified. 3.Start your Mule 1.3.3 server with the configuration we edited in Step 1: sftp.bat (Windows) or sftp.sh (Linux/Unix)
4. After startup, you should see something like this in the console:
********************************************************************** * Mule ESB and Integration Platform version Not Set * * Not Set * * For more information go to http://mule.mulesource.org * * * * Server started: Monday, March 19, 2007 1:17:21 AM PDT * * Server ID: SFTP_TEST * * JDK: 1.5.0_11 (mixed mode) * * OS: Windows XP - Service Pack 2 (5.1, x86) * * Host: QMULE (192.168.1.101) * * * * Agents Running: * * Mule Admin: accepting connections on tcp://localhost:60504 * ********************************************************************** INFO 2007-03-19 01:17:22,734 [MULE:WrapperSimpleAppMain] org.mule.MuleServer: Mule S erver initialized. =====SFTP Demo.
Enter file contents to be routed to SFTP service .=====
5. By entering text to the console at the prompt above, Mule will dispatch a file message to the SFTP service specifed in Step 1. You will then see the following (linebreaks added for readability):
Document generated by Confluence on Apr 24, 2008 08:11
Page 294
=====SFTP Demo. Enter file contents to be routed to SFTP service .===== This is a mule message INFO 2007-03-19 01:52:18,078 [MULE:SystemStreamConnector.endpoint.stream.System.in.r eceiver.1] org.mule.providers.sftp.SftpMessageDispatcher: Successfully connected t o: sftp://mule:test123@localhost/files/sftp-target INFO 2007-03-19 01:52:18,078 [MULE:SystemStreamConnector.endpoint.stream.System.in.r eceiver.1] org.mule.providers.sftp.SftpMessageDispatcher: Writing file to: sftp:// mule:test123@localhost/files/sftp-target/
The INFO logging tells you that Mule was able to connect and write to the resource sftp:// mule:test123@localhost/files/sftp-target. 6. The SFTP Connector uses a PollingMessageReceiver to retrieve files from an SFTP. Since we configured the polling frequency to be 10 seconds, you should see the following in the console in 10 s (linebreaks added for readability):
INFO 2007-03-19 01:52:21,187 \[MULE:sftpConnector.endpoint.sftp.mule.test123.localhos t.files.sftp.source.receiver.1\] org.mule.providers.stream.StreamMessageDispatche r: Successfully connected to: stream://System.out This is a mule message
You should see the same message you entered in Step 5. We used the "InputStreamToByteArray" transformer in this example (see "mule-sftpexamples-config.xml"). If your files are large, then you don't want to use this transformer, and instead handle the stream yourself in a Service Component or a streaming Message Dispatcher. Please see the SFTP Connector User Guide for more details.
Document generated by Confluence on Apr 24, 2008 08:11
Page 295
SFTP Connector Installation Instructions This page last changed on Jan 30, 2008 by ross.
SFTP Connector Installation Instructions Prerequisites Pre-Requisite
Version
Notes
JDK
1.4.x
$JAVA_HOME environment set $PATH includes $JAVA_HOME/ bin 1.5.x needed for buiding from source
Mule
1.3.3 distribution
will not work with latest snapshots (1.4+)
Subversion
any
only needed for building from source
Maven
2.0.5+
only needed for building from source
Winzip/Gzip
any
Installing the Binary 1. Install Mule 1.3.3 to your machine, if not already installed. When done, set your $MULE_HOME environment variable to where you installed Mule, for example c:/mule/mule-1.3.3. Also, add $MULE_HOME/bin to your $PATH. 2. Download the MULE:SFTP Connector zip and unpack it to a directory, say $VFS_DIST. From $VFS_DIST, copy mule-transport-vfs-*.jar to $MULE_HOME/lib/user. 3. Copy $VFS_DIST/lib/*.jar directory to $MULE_HOME/lib/user. 4. Proceed to Running the SFTP Connector Examples.
Installing from Source 1. Install Mule 1.3.3 to your machine, if not already installed. When done, set your $MULE_HOME environment variable to where you installed Mule, for example c:/mule/mule-1.3.3. Also, add $MULE_HOME/bin to your $PATH. 2. Download Maven 2.0.5 or higher and add the $MAVEN_HOME/bin to your $PATH 3. Check out the latest SFTP connector code from Subversion at: https://svn.codehaus.org/mulecontrib/transports/sftp For this example, let's say your Subversion workspace is $WS. 4. cd to $WS 5. Run "mvn -Dmaven.test.skip=true install" at the command prompt. This builds the SFTP connector. Running unit tests is not recommended unless you understand the SFTP Connector Unit Tests section in the SFTP Connector User Guide. 6. Deploy the SFTP connector by copying $WS/target/mule-transports-sftp-*.jar to $MULE_HOME/lib/ user. 7. There are 3rd party libraries needed by the VFS library. Copy the jars in the "Library Dependencies" section below to $MULE_HOME/lib/user 8. Proceed to Running the SFTP Connector Examples.
Document generated by Confluence on Apr 24, 2008 08:11
Page 296
Library Dependencies The following libraries are needed by the SFTP Connector. They are copied to you M2_REPO location during the build: $M2_REPO/com/jcraft/jsch/0.1.29/jsch-0.1.29.jar Note: The $M2_REPO location on Linux/Unix the location is ~/.m2 by default. On Windows it's usually c:/ Documents and Settings/<user>/.m2.
Document generated by Confluence on Apr 24, 2008 08:11
Page 297
SFTP Connector User Guide This page last changed on Jan 30, 2008 by ross.
The SFTP connector allows files to be read and written to and from directories over SFTP. Unlike the VFS Connector, it can handle large files because it uses a non-materializing InputStream as the message payload. The 1.3.3 version of the SFTP connector is based on the JSCH 0.1.29 library. Installation Instructions and Examples are also available. MULE:#Unit Tests section below.
More examples can be found in the
Currently, the SFTP connector will only work on Mule 1.3.3. Support for 1.4 is underway.
SFTP Connector Properties Property
Description
Default
Required
pollingFrequency
The frequency in milliseconds that the read directory should be checked. Note that the read directory is specified by the endpoint of the listening component.
30000
No
filenameParser
Is an implementation of org.mule.providers.file. org.mule.providers.file.FilenameParserand SimpleFilenameParser is used to control how filename patterns are used to generate file names. The file provider has a default implementation called org.mule.providers.file.SimpleFilenameParser that understands the following patterns:
Yes
• ${DATE}- the current date in the format dd-MMyy_HH-mm-ss.SS • ${DATE:yy-MMdd}- 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
Document generated by Confluence on Apr 24, 2008 08:11
Page 298
read from another location • ${COUNT}An incremental counter outputPattern
The default pattern to use when writing a file to the VFS filesystem. This can use the patterns supported by the filenameParser configured for this connector. You can also override this pattern by explicitly setting a property on the Mule message (use the key SftpConnector.PROPERTY_FILENAME).
Yes
autoDelete
Determines whether to delete the file in the read directory after it has been processed
No
true
SFTP Endpoints SFTP endpoints are expressed using the standard URI of: sftp://<username>:<password>@/path/to/dir For example, and SFTP endpoint could be configured as follows:sftp://mule:[email protected]/tmp/ mule-vfs This endpoint would connect over SFTP to myhost.com as mule/test123, then read or write to ~/tmp/ mule-vfs.
Transformers
Transformer
Description
org.mule.providers.sftp.transformers.InputStreamByteArray Materializes an InputStream into a byte array This transformer makes it possible to use the SFTP Message Receiver with non-streaming Service Components or Message Dispatchers. Typical usage is to add this transformer to an SFTP receiving endpoint, so that downstream Service Components or Message Dispatchers can deal with a byte[] instead of InputStream. Note however that materializing an InputStream for a large file will cause OOM errors, so this transformer should not be used if large files are expected.
Unit Tests
JUnit Class
Document generated by Confluence on Apr 24, 2008 08:11
Description
Page 299
org.mule.providers.sftp.LargeFileReceiveFunctionalTestCase Tests ability of the SftpMessageReceiver to receive a large file. The file is received by a Service Component (ReceiveLargeFileTestHelperComponent) which streams the file to the /tmp directory. org.mule.providers.sftp.LargeFileSendFunctionalTestCase Tests ability of the SftpMessageDispatcher to send a large file. The file is streamed from /tmp/ big.zip on the local machine. org.mule.providers.sftp.SendReceiveFunctionalTestCase Tests a round trip send/receive of multiple files.
Document generated by Confluence on Apr 24, 2008 08:11
Page 300
Smtp Provider This page last changed on Jan 30, 2008 by ross.
The Smtp transport provider can be used to for sending messages over Smtp and Smtps (secure) using the javax.mail api. The implementation supports CC/BCC/ReplyTo addresses, attachments, custom Header properties and customisable authentication. It also provides support for javax.mail.Message transformation. The javadoc for this provider can be found here , org.mule.providers.email.SmtpConnector org.mule.providers.email.SmtpsConnector
Smtp Connector Properties Property
Description
Default
Required
subject
A default subject for the outbound message if one is not set.
(no subject)
No
fromAddress
The from address to set on the outgoing message.
Yes
ccAddresses
A comma separated list of email addresses to carbon copy to.
No
bccAddresses
A comma separated list of email addresses to blind carbon copy to.
No
replyToAddresses
A comma separated list of email addresses that will receive replies to the mail message sent from this connector
No
customHeaders
A Map of custom header properties that will be set on the outgoing message. Property variables can be used in the headers to be resolved at runtime, i.e. ${my.variable}. These properties are resolved against the MuleManager properties and any properties set on the current event and endpoint.
No
authenticator
Is used when sending authenticated Smtp requests. By default Mule handles
No
Document generated by Confluence on Apr 24, 2008 08:11
Page 301
authentication by creating a default Authenticator if there are user credentials set on the Smtp endpoint (see below). Users can customise the authenticator if needed by setting this to their oun authenticator. Authenitcators must implement javax.mail.Authenticator contentType
Sets the default Mime content type for outgoing message
text/plain
No
Server Credentials The host, port, and user credentials are set on the smtp:// endpoint and the additional properties on the connector act as defaults if the same properties are not set on the endpoint.
Smtps Connector Properties The Smtps Connector enables Smtp over SSL using the javax.mail APIs. It supports all the properties of the Smtp connector and has some additional properties for setting up an SSL connection.
Property
Description
Default
Required
socketFactory
The SSL socket factory to use
javax.net.ssl.SSLSocketFactory No
socketFactoryFallback
Whether to enable fallback
false
trustStore
The flie location of a trust store
No
trustStorePassword
The password for the trust store
No
No
When using the Smtps Connector the default port is set to 465.
Smtp(s) Endpoints Smtp endpoints describe details about the Smtp server and the recipients of messages sent from the Smtp endpoint. Smtp URIs use the following syntax smtp://[user:password@]<smtp server>[MULE::port]?address=
The format is the same for Smtps smtps://[user:password@]<smtp server>[MULE::port]?address=
Escape your credentials
Document generated by Confluence on Apr 24, 2008 08:11
Page 302
Sometimes you'll have illegal (for URI) characters in your login/password. Use the standard escape syntax your browser would use, e.g. the username user@mule would become user %40mule. For example, smtp://muletestbox:[email protected][email protected]
Will send mail using smtp.mail.yahoo.co.uk (using default smtp port) to the address [email protected]. The Smtp request is authenticated using username muletestbox and password 123456. You will probably want to set other information such as subject and fromAddress. These can be set as parameters on the URI but we recommend you set them as endpoint properties to make it easier to read and maintain the configuration. <endpoint address="smtp://muletestbox:[email protected]? [email protected]"> <properties> <property name="fromAddress" value="[email protected]"/> <property name="ccAddresses" value="[email protected],[email protected]"/> <property name="subject" value="Please verify your ebay account details"/>
So far, all configurations has been static in that you define all the information in the configuration of the endpoint. However, you can set the following properties on the MuleMessage to control the settings of the outgoing Smtp Message. These properties will override the endpoint properties -
Constant
Name
Description
MailProperties.TO_ADDRESSES_PROPERTY toAddresses
comma-separate list of addresses
MailProperties.CC_ADDRESSES_PROPERTY ccAddresses
comma-separate list of addresses
MailProperties.BCC_ADDRESSES_PROPERTY bccAddresses
comma-separate list of addresses
MailProperties.REPLY_TO_ADDRESSES_PROPERTY replyToAddresses
comma-separate list of addresses
MailProperties.FROM_ADDRESS_PROPERTY fromAddress
single email address
MailProperties.SUBJECT_PROPERTYsubject
The email subject string
MailProperties.CUSTOM_HEADERS_MAP_PROPERTY customHeaders
A Map of string header properties
MailProperties.CONTENT_TYPE_PROPERTY contentType
The Mime content type of the message
If you always want to set the email address dynamically, you can leave out the address parameter on the Smtp endpoint.
Transformers There are a couple of transformers provided with the Email transport that are useful for converting Object payloads to javax.mail.Message types. These transformers adhere to the rules listed above and handle attachments too. If you need to customise the behaviour of these transformers it is recommended that you extends the existing transformers rather than re-implement them.
Document generated by Confluence on Apr 24, 2008 08:11
Page 303
Transformer
Description
org.mule.providers.email.transformers. StringToEmailMessage
Converts a String message payload to a javax.mail.Message. This transformer doesn't support attachements and is deprecated in favour of the ObjectToMimeMessage transformer
org.mule.providers.email.transformers. ObjectToMimeMessage
Converts an Object message payload to a javax.mail.Message. Supports attachments.
Document generated by Confluence on Apr 24, 2008 08:11
Page 304
Soap Provider This page last changed on Jan 30, 2008 by ross.
The soap provider can be used to publish and invoke services using either Apache Axis, XFire or WebMethods Glue. The SOAP transport in Mule allows soap endpoints to be defined as -
soap:http://localhost:1234/MyService
and the actual SOAP stack used to execute this service will be discovered based on the first SOAP stack available on the class path. For more information about using Web services and Mule see • Axis • XFire • Glue The javadoc for this provider can be found here .
Document generated by Confluence on Apr 24, 2008 08:11
Page 305
Ssl Provider This page last changed on Jan 30, 2008 by ross.
The Ssl connector can be used for secure socket communication using ssl or tls. The javadoc for this transport provider can be found here. And the Source Xref can be found here
SSL Connector Properties See Tcp Provider for extra properties inherited by this connector.
Property
Description
Default
Required
timeout
The socket read timeout
5000
Yes
bufferSize
The buffer size used to read and write data
64*1024
Yes
keyStore
The location of the server keystore used to create a secure server socket
Yes (if connector is being used as a server)
keyPassword
The password used to check integrity and unlock the key store
Yes (if keyStore is set)
storePassword
The password for the server keystore
Yes (if keyStore is set)
keystoreType
The type of keystore being used
KeyStore.getDefaultType()Yes (if keyStore is set)
keyManagerAlgorithm
The Key Manager algorithm to use
Depends on the JDK vendor, automatically discovered.
Yes (if keyStore is set)
trustManagerAlgorithm
The Trust Manager algorithm to use
The same as keyManagerAlgorithm
No
protocolHandler
The value used for Depends on the JDK java.protocol.handler.pkgsvendor, automatically discovered.
Yes
requireClientAuthenticationWhether clients should be authenticated when connecting
true
Yes (if keyStore is set)
provider
The sercurity provider object to register with the java Security manager
Depends on the JDK vendor, automatically discovered.
Yes (if keyStore is set)
clientKeyStore
The location of the client keystore. This value is used to set javax.net.ssl.keyStore
Yes (if connector is being used by a client)
clientKeyStorePassword
Document generated by Confluence on Apr 24, 2008 08:11
Page 306
The password for the client keystore. This value is used to set javax.net.ssl.keyStorePassword
Yes (if clientKeyStore is set)
trustStore
The location of the trust keystore. This value is used to set javax.net.ssl.trustStore
No
trustStorePassword
The password for the trustStore. This value is used to set javax.net.ssl.trustStorePassword
trustStoreType
The type of the truststore being used
KeyStore.getDefaultType()No
explicitTrustStoreOnly
Whether to use the clientKeyStore details as the trustStore details if a trustStore hasn't been explicitly set
false
keyManagerFactory
The KeyManager factory to use. You woundn't normally set this as the KeyManagerFactory is determined based on the keyManagerAlgorithm
No
trustManagerFactory
The TrustManager factory to use. Normally determined based on the trustManagerAlgorithm
No
(use clientKeystore)
Yes (if trustStore is set)
No
Endpoints SSL endpoints are described as socket-based endpoints in the form of ssl://localhost:1234
To use TLS instead of SSL you just need to change the endpoint URI protocol tls://localhost:1234
Transformers The following transformers are used by default for this connector unless a transformer is explicitly set on the provider.
Transformer
Description
ByteArrayToString
converts a byte array to a String
StringToByteArray
Converts a String to a byte array
Document generated by Confluence on Apr 24, 2008 08:11
Page 307
Stream Provider This page last changed on Jan 30, 2008 by ross.
The Stream Provider allows the reading and writing of streaming data. Typically, this is used as the interface to Java's System.out and System.in objects for debugging via the System Stream Provider. A typically use of the System Stream Provider for getting data via System.in is like this: <mule-descriptor name="test" implementation="org.mule.components.simple.PassThroughComponent"> <endpoint address="stream://System.in?promptMessage=Enter something: />
Note that no definition is required per se: use of the stream endpoint tells Mule to use the SystemStreamConnector. However, if you need to define it explicitly, you can do so like this: <properties> <property name="promptMessage" value="Enter something: "/> <property name="messageDelayTime" value="1000"/>
A typically use of the System Stream Provider for sending data to the console via System.out is like this: <endpoint address="stream://System.out" transformers="JMSMessageToObject"/>
In this example, the output is a JMS message which is sent to System.out. The transformer converts the JMS message to something readable.
Stream Connector Properties The following properties are defined for this connector:
Property
Description
promptMessage
An optional prompt message to ask the user for input
messageDelayTime
How long to delay before asking for input
outputMessage
resourceBundle
Default
Required
Applies to
No
System.in
No
System.in
An optional output message to print before any data
No
System.out System.err
Used for loading the message prompts from a resource bundle. This parameter specifies the resource bundle prefix. See below.
No
System.in
3 seconds
Document generated by Confluence on Apr 24, 2008 08:11
Page 308
promptMessageCode Used for loading the message prompts from a resource bundle. This parameter specifies the resource message id for the prompt message (see below).
No
System.in
outputMessageCode Used for loading the message prompts from a resource bundle. This parameter specifies the resource message id for the output message (see below).
No
System.in
Stream Endpoints System Stream endpoints are defined using this syntax: stream://[MULE:stream name]
"stream name" can be one of: 1. System.in - input stream 2. System.out - output stream 3. System.err - error output stream
Property Overrides You can override certain properties when defining a System Stream endpoint to control the way that particular receiver or dispatcher behaves. The properties that can be set on the individual endpoint are promptMessage and outputMessage.
Transformers There are no built-in transformers for the Stream Provider.
Internationalising Messages If you are internationalising your application as described here, you can also internationalise the promptMessages and outputMessages for the SystemStreamConnector. (This assumes that you have already created a resource bundle that contains your messages as described on that page.) To internationalise, you must specify both the resourceBundle parameter and the promptMessageCode and/or outputMessageCode parameters. The resourceBundle parameter will contain the key to the resource bundle itself. The promptMessageCode provides the key to the message in the bundle for the prompt message. In the snippet below, the "hello-example" resource bundle means that the prompt message "3" will be expected in the bundle META-INF/services/org/mule/i18n/hello-examplemessages.properties: <properties> <property name="promptMessageCode" value="3"/> <property name="resourceBundle" value="hello-example"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 309
<property name="messageDelayTime" value="1000"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 310
Tcp Provider This page last changed on Jan 30, 2008 by ross.
The tcp connector can be used to send and receive mule events over tcp. The javadoc for this transport provider can be found here. And the Source Xref can be found here
Tcp Connector Properties Property
Description
Default
Required
receiveTimeout
The socket read timeout (SO_TIMEOUT) when used as a server.
Socket Default
No
sendTimeout
The socket read timeout (SO_TIMEOUT) when used as a client.
Socket Default
No
timeout
This is a shorthand property setting both read/write timeouts. Use either this or a dedicated send/receive timeout property.
Socket Default
No
bufferSize
the buffer size used to read and write data
Socket Default
No
backlog
Maximum Queue length for a ServerSocket. Only applies to inbound connections.
ServerSocket Default
No
tcpProtocol
An implementation of TcpProtocol interface
tcpProtocolClassName
The class name of the TcpProtocol interface.
org.mule.providers.tcp.protocols.DefaultProtocol No
keepSendSocketOpen
Whether to keep the socket open for multiple dispatches. Only applies to outbound connections.
false
No
keepAlive
Enables SO_KEEPALIVE behaviour on open sockets. This automatically checks socket connections which are open but unused for long periods and closes them if the connection becomes unavailable.
false
No
maxRetryCount
Removed: A Connection Strategy should be used to manage connection
-
-
Document generated by Confluence on Apr 24, 2008 08:11
No
Page 311
retry behaviour o n the connector. validateConnections
1
reuseAddress
Whether the socket should be quickly opened and closed to check the port on first use.
true
No
Whether the socket can be efficiently re-used
false
No
Endpoints Tcp endpoints are described as socket-based endpoints in the form of tcp://localhost:1234
Transformers The following transformers are used by default for this connector unless a transformer is explicitly set on the provider.
Transformer
Description
ByteArrayToString
converts a byte array to a String
StringToByteArray
Converts a String to a byte array
Protocols When transfering data with other applications, it may be necessary to use custom application level protocols. This is also useful when transfering large amount of data (or when using slow connections) so that the data are not split. This protocol is handled with the TcpProtocol interface. If your protocol implementation does not need configuration, you can use <properties> <property name="tcpProtocolClassName" value="org.mule.providers.tcp.protocols.LengthProtocol"/>
or you can use a bean from a container <properties>
Protocol
Description
org.mule.providers.tcp.protocols.DefaultProtocol
reads data until no more is momentarily available 3
in the buffer (unsafe ) org.mule.providers.tcp.protocols.LengthProtocol
Document generated by Confluence on Apr 24, 2008 08:11
prefixes the byte stream with a length and writes/ reads the specified number of bytes
Page 312
org.mule.providers.tcp.protocols.SafeProtocol
org.mule.providers.tcp.protocols.EOFProtocol
2
1
as LengthProtocol, but includes initial token to detect mis-use reads all data until the stream is closed (ie for single message transport)
org.mule.providers.tcp.protocols.MuleMessageProtocol writes/reads the complete Mule Message object (not just the payload), preserving metadata 3
information like correlation IDs (unsafe ) org.mule.providers.tcp.protocols.MuleMessageEOFProtocol combines MuleMessageProtocol with EOFProtocol 1,2
org.mule.providers.tcp.protocols.MuleMessageLengthProtocol combines MuleMessageProtocol with 2 LengthProtocol org.mule.providers.tcp.protocols.XmlMessageProtocolseparates messages by the
documents or when the buffer empties (unsafe ) org.mule.providers.tcp.protocols.XmlMessageEOFProtocol separates messages by the
Cannot be used in Remote Request-Response pattern, because this requires the socket to be open until response is received 2
Version 2.0 onwards (some may be available in later 1.4 versions too)
3
TCP does not guarantee grouping of data and/or signal the "gap" between "writes", so it is possible that data within a single message will be received in more than one "chunk". Unsafe protocols cannot handle such fragmented messages.
Document generated by Confluence on Apr 24, 2008 08:11
Page 313
Transports Feature Matrix This page last changed on Jan 30, 2008 by ross.
The following table shows the different messaging characteristics that each of the Mule providers support. For example some transports a only support event dispatching such as RMI. The column heads are described below.
Transport Type
AS400 DQ
Messaging
Ejb
Remoting
Email
Record
File
Record
Ftp
Record
Http
Socket
Imap
Messaging
Jdbc
Record
Receive
Send (sync)
Dispatch(async) Request/ Remote Response Sync
Transactions Streaming
Jdbc, Xa
Jms
Messaging
Jms, Ack, Xa
Multicast Socket Pop3
Messaging
Quartz
Repository
Rmi
Remoting
Servlet
Socket
Smtp
Messaging
Soap: Axis
Messaging
Soap: XFire
Messaging
Soap: Glue
Messaging
WSDL
Messaging
Ssl
Socket
Document generated by Confluence on Apr 24, 2008 08:11
Page 314
Stream
Socket
Tcp
Socket
Udp
Socket
Vm
Messaging
Vm, Xa
Xmpp
Messaging
Heading Descriptions Transport - The name/protocol of the transport Type - Whether the transport is a lower level socket-based or higher-level messaging or remoting or if the interacts with a record store such as a file system or database. Receive - Whether the transport can receive events and can be used for an inbound endpoint Send (sync) - Whether events can be send synchronously (in the same thread as the request) using the transport Dispatch(async) - Whether events can be send aynchronously Request/Response - Whether this endpoint can be queried directly with a request and return a response (Imlementation of the receive() method in UMOMessageDispatcher) Remote Sync - Whether this transport support remoteSynchronous. This where Mule uses as back channel automatically to receive a response from a remote host. Transports such as Http support this implicitly others such as Jms will set up a Temporary ReplyTo Queue to receive a response. This allows you to chain request/response calls over two or more remote hosts. Transactions - Whether transactions are supported by the transports. Transports that support (/)A transactions can be configured in a distributed 2 Phase Commit (Distributed) transaction. Streaming - Able to work with the Streaming Model and stream data between endpoints. This allows for very efficient processing of large data.
Document generated by Confluence on Apr 24, 2008 08:11
Page 315
Udp Provider This page last changed on Jan 30, 2008 by ross.
The udp connector can be used to send and receive mule events as datagram packets. The javadoc for this provider can be found here.
Udp Connector Properties Property
Description
Default
Required
timeout
The socket read timeout
5000
Yes
bufferSize
the buffer size used to read and write data
64*1024
Yes
retryCount
The number of times to try and connect a listener to a socket
2
Yes
retryFrequency
The number of milliseconds to wait beween retries
2000
Yes
Transformers The following transformers are used by default for this connector unless a transformer is explicitly set on the provider.
Transformer
Description
ByteArrayToString
Converts a byte array to a String
StringToByteArray
Converts a String to a byte array
Document generated by Confluence on Apr 24, 2008 08:11
Page 316
Vfs Provider This page last changed on Jan 30, 2008 by ross.
Enables access to and from various protocols such as WebDav, Samba, File System, Jar/Zip and more. This transport is currently available on MuleForge
Comments The VFS Provider is nowadays in mule-contrib. Subversion at http://svn.codehaus.org/mule-contrib/ Posted by anajavi at Mar 02, 2007. .....................................................................................................................................................................
Document generated by Confluence on Apr 24, 2008 08:11
Page 317
Vm Provider This page last changed on Jan 30, 2008 by ross.
The VM connector is used for intra-VM communication between components managed by Mule. The connector provides options for configuring VM transient or persistent queues. The javadoc for this provider can be found here.
VM Connector Properties Property
Description
Default
Required
queueEvents
determines if queues should be set up for listeners on the connector. If this is false the connector simply forwards events to components via the Mule server. It's not necessary to set this attribute. If it is set then the queues are configured using the queuing profile configured on the MuleConfiguration. Here you can specify if the queues should be persistent
false
No
Using VM Queues When using a synchronous VM endpoint events are delivered in memory from one component to another (asynchronous endpoints introduce an event queue that threads can consume from). However, when the 'queueEvents' property is set, events can be stored in arbitrary memory queues and consumed later by clients or components. Furthermore these queues can be persistent and XA transactional (see below). To use VM Queues the 'queueEvents' property must be set on the connector and all VM endpoints that should queue events must use a VM connector that has queueEvents enabled. You cannot set the 'queueEvents' property on the endpoint, it can only be set at the connector level. i.e. <properties> <property name="queueEvents" value="true"/> <model name="TestModel"> <mule-descriptor name="TestComponent" implementation="org.mule.components.simple.PassThroughComponent"> <endpoint address="vm://test.queue" connector="vmQueue"/>
Notice that the endpoint explicitly tells Mule to use the vmQueue connector. Otherwise Mule will look for the first connector that matches the protocol for the endpoint.
Document generated by Confluence on Apr 24, 2008 08:11
Page 318
Using Persistent Queues VM queue can be made persistent so that its state can be maintained between server shutdowns. To make VM queues persistent you must set a persistence strategy in the Mule Xml configuration. This strategy is shared for all VM queues in Mule instance. <mule-environment-properties>
Note you must add a element for the VM queue configuration and you must also add a that tells mule how to persist the events. If a is not set, Mule will use the default in-memory persistence strategy. Users can write their own persistence strategies to write to a database or some other store if required. Persistence strategies must implement QueuePersistenceStrategy.
Using Transactions VM Queues support Transactions and can take part in distributed XA transactions. To make a VM queue endpoint transactional use the following configuration <endpoint address="vm://test.queue" connector="vmQueue">
You will also need to add a transaction manager to your configuration. For more information see Transaction Management.
Endpoints VM endpoints are 'resource' endpoints in that they just name a resource, there is not host or other configuration required. For example vm://myComponent
Points to an address called 'myComponent', anything listening on vm://myComponent will receive events dispatched on vm://myComponent. When using VM queues the notation is the same.
Transformers There are no specific transformers for the VM transport.
Document generated by Confluence on Apr 24, 2008 08:11
Page 319
WSDL Provider This page last changed on Jan 30, 2008 by ross.
The WSDL transport provider can be used to for invoking remote web services by obtaining the service WSDL. Mule will create a dynamic proxy for the service then invoke it. The javadoc for this provider can be found here.
WSDL Connector Properties The WSDL connector inherits all properties from its respective implementation connector superclass XFireConnector or AxisConnector.
WSDL Endpoints The WSDL endpoint works in much the same way as the other SOAP endpoints such as Axis, Glue or XFire. You must provide the full URL to the WSDL of the service to invoke and you must also supply a 'method' parameter which tells Mule which operation to invoke on the service wsdl:http://www.webservicex.net/stockquote.asmx?WSDL&method=GetQuote
The WSDL URL is pre-pended with wsdl:. Behand the scenes Mule will check you class path to see if there is a WSDL provider that it can use to create a client proxy from the WSDL. Mule supports the Axis and XFire methods. If you want to use a specific one you can specify which on the URL i.e. wsdl-xfire:http://www.webservicex.net/stockquote.asmx?WSDL&method=GetQuote or wsdl-axis:http://www.webservicex.net/stockquote.asmx?WSDL&method=GetQuote
The javadoc for the Xfire WSDL dispatcher can be found here. The javadoc for the AxisWSDL dispatcher can be found here. Issue with Axis Sometimes the Axis WSDL generation will not work (Incorrect namespaces are used) So you might want to experiment with each one. We have had no problems with the XFire WSDL generation so far
Transformers There are no specific transformers to set on WSDL endpoints.
Specifying an alternate WSDL location In the XFire transport, you have the option of specifying a location for the WSDL that is different than that specified with the ?WSDL parameter. This may be useful in cases where the WSDL isn't available the normal way, either because the SOAP engine doesn't provide it or the provider does not want to expose the WSDL publicly. In these cases, you can specify the "wsdlUrl" property of the XFire endpoint like this: <endpoint address="wsdl-xfire:http://localhost:8080/book/services/BookService?method=getBooks" connector="xfiretest"> <properties> <property name="wsdlUrl" value="file:///c:/BookService.xml"/>
In this case, the wsdl-xfire endpoint works as it normally does, except that it reads the WSDL from the local drive.
Document generated by Confluence on Apr 24, 2008 08:11
Page 320
Example of the XFire WSDL Endpoint For a simple example of the XFire WSDL Endpoint in action, you can do the following: 1. 2. 3. 4.
Download and unpack the latest XFire distribution (currently 1.2.5) Build the WAR for the book example, per the XFire User Guide Deploy the WAR into your favorite servlet container and start it Jar up the XFire demo classes from the WAR (under WEB-INF/classes) and put the new jar in your Mule classpath 5. Use the following Mule configuration file to access the service (change the URL as appropriate) <mule-configuration id="Sample" version="1.0"> <mule-environment-properties synchronous="true"/> <properties> <property name="clientTransport" value="org.codehaus.xfire.transport.http.SoapHttpTransport"/> <list name="clientOutHandlers"> <entry value="org.codehaus.xfire.demo.handlers.OutHeaderHandler"/> <model name="sample"> <mule-descriptor name="inputService" implementation="org.mule.components.simple.PassThroughComponent"> <endpoint address="stream://System.in?promptMessage=Enter something to invoke the service:"/> <endpoint address="wsdl-xfire:http://127.0.0.1:8080/xfiretest/services/BookService?method=getBooks" connector="xfiretest"/> <endpoint address="vm://process"/> <mule-descriptor name="outputService" implementation="org.mule.components.simple.PassThroughComponent"> <endpoint address="vm://process"/> <endpoint address="stream://System.out?transformers=DomDocumentToXml"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 321
Example of the XFire WSDL Endpoint with multiple arguments Sometimes, you have to pass multiple arguments to an external SOAP service. For example, the Currency Convertor on www.webservicex.net requires two arguments: the "from" currency code and the "to" currency code. When the XFire dispatcher prepares arguments for the invocation of the service, it expects to find a message payload of Object[] - that is, an Object array. In the case of the Currency Convertor, this should be an array of two Objects. There are several ways to do this, but the easiest is a new transformer - StringToObjectArrayTransformer - that translates a delimited String into an Object array. In the example below, all you have to do is type in a String in the format of ,. <mule-configuration id="Sample" version="1.0"> <mule-environment-properties synchronous="true"/> <properties> <property name="delimiter" value=","/> <model name="sample"> <mule-descriptor name="inputService" implementation="org.mule.components.simple.PassThroughComponent"> <endpoint address="stream://System.in?promptMessage=Enter from and to currency symbols, separated by a comma:" transformers="StringToObjectArray"/> <endpoint address="wsdl-xfire:http://www.webservicex.net/CurrencyConvertor.asmx? WSDL&method=ConversionRate"/> <endpoint address="stream://System.out"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 322
For example, type "EUR,USD" to get the conversion rate for Euros to US Dollars and you'll get something like this: Enter from and to currency symbols, separated by a comma: EUR,USD 1.3606
Document generated by Confluence on Apr 24, 2008 08:11
Page 323
Xmpp Provider This page last changed on Jan 30, 2008 by ross.
The Xmpp provider enables the Xmpp (jabber) instant messaging protocol using the Smack API. The javadoc for this transport provider can be found here and the Source Xref can be found here.
Endpoints An Xmpp endpoint specifies user credentials and a host to connect to. xmpp://username:[email protected]:5222/
It is important to ensure that there is a "/" at the end. To send and receive instant messages with a specific user, just put their username and hostname after the "/". For example: xmpp://muletest:[email protected]:5222/[email protected]
For sending messages, the recipient can also be specified at message level using the following notation: xmpp://muletest:[email protected]:5222/[email protected]
Note The latest version of MULE is required to successfully use this transport.
Filters TODO
Transformers There are two transformers provided with the Xmpp transport...
Transformer
Description
org.mule.providers.xmpp.transformers.XmppPacketToString Converts an Xmpp Packet to a String, returning a java.lang.String object. org.mule.providers.xmpp.transformers.ObjectToXmppPacket Accepts a String or an Xmpp Packet and returns an Xmpp Packet. This transformer doesn't accept all objects, only Strings and Xmpp Packets.
Document generated by Confluence on Apr 24, 2008 08:11
Page 324
Web Services This page last changed on Apr 18, 2008 by tcarlson.
Configuring Mule and Apache Axis. • Getting started - Introduction to exposing Mule services over Axis and invoking Soap services. • Axis Transport - Basic configuration of the Axis Connector. • Configuring Axis - Controlling WSDL generation, named parameters, Advanced Service configuration, etc. • Axis Soap Transports - Using Axis over Jms, Vm, Smtp and other Mule transports. • Axis SOAP Styles - Configuring services for Doc/Lit, Message or RPC style invocations. Glue Web Services - Configuring Mule and Webmethods Glue. XFire Web Services - Configuring Mule and XFire STaX-based Web services framework. Soap Transport Provider - A guide to Mule Soap configuration. Mule Client - The Universal Mule Client can be used as a soap client. Web Service Security - Support for WS-Security. Examples MULEINTRO:Echo Example - A simple example of exposing a Mule service as a web service using Axis. Spring Events - An example of how to Have you Spring Beans use Mule transports without configuring the Mule Server. The example demonstates using JMS, Axis web services and Email.
Document generated by Confluence on Apr 24, 2008 08:11
Page 325
Axis This page last changed on Jan 30, 2008 by ross.
Configuring Mule and Apache Axis. • Getting started - Introduction to exposing Mule services over Axis and invoking Soap services. • Axis Transport - Basic configuration of the Axis Connector. • Configuring Axis - Controlling WSDL generation, named parameters, Advanced Service configuration, etc. • Axis Soap Transports - Using Axis over Jms, Vm, Smtp and other Mule transports. • Axis SOAP Styles - Configuring services for Doc/Lit, Message or RPC style invocations.
Document generated by Confluence on Apr 24, 2008 08:11
Page 326
Axis SOAP Styles This page last changed on Jan 30, 2008 by ross.
By Default Mule Axis support uses RPC/Encoded for soap messages. However, due to compatibility issues on other platforms it has become increasingly popular to use Document/Literal/Wrapped style services. The following document descries how to use Doc/Lit, Doc/Lit/Wrapped and Message style services using Axis in Mule. For a really good overview of the pros and cons of each style/use combination have a look at - http://www-128.ibm.com/developerworks/webservices/library/ws-whichwsdl/. For each example we provide a client call and a server example. The Client example shows how to invoke an Axis web service hosted in Tomcat using the Mule client. The example behaves exactly the same way if the service is hosted in Mule unless explicitly noted otherwise. The Server example demonstrates how to expose a service in Mule with any additional steps that may be necessary. These tests were run against Tomcat 5.5.12 and Axis 1.3.1. Each test uses the Calculator service as used in the Axis User Guide.
Document Literal Wrapped This is the preferred approach to Document Literal style services. The 'Wrapped' bit just means that the parameters are wrapped in an element whose name is the name of the operation to invoke.
Client Example This example is very similar to the Doc/Lit example except that we set the message style to 'wrapped/ literal' and there is no need to add any server configuration as the method name is stored in the message. String URL = "axis:http://localhost:8080/axis/Calculator.jws?method=add"; MuleClient client = new MuleClient(); Map props = new HashMap(); props.put("style", "wrapped"); props.put("use", "literal"); UMOMessage 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 <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> 3 3
In the next example we can see how to change the namespace of the method as well as naming the parameters. This is obviously very useful when calling services from other platforms!
Doc/Lit/Wrapped with Named Parameters If you're invoking external services you will quickly find that the Axis generated names for parameters and namespaces will break things. However, it is trivial to change these in Mule. The following example demonstrates -
Client Example String URL = "axis:http://localhost:8080/axis/Calculator.jws"; MuleClient client = new MuleClient();
Document generated by Confluence on Apr 24, 2008 08:11
Page 327
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); UMOMessage result = client.send(URL, new Object[]{new Integer(3), new Integer(3)}, props); assertEquals(result.getPayload(), new Integer(6));
Note that we do not pass the method name in the query string of the URL, instead we create a SoapMethod object and add it to the parameters passed to the client call. The soap request now looks like <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> 3 3
Moving this information into configuration Sometimes you might not want to have Namespaces and parameter names hard-coded, but would prefer having this information in your Mule config file. Create an endpoint configuration in the MuleXml configuration and reference it from your Mule Client. the Config file will look like <mule-configuration id="axis_client_endpoint" version="1.0"> <endpoint name="calculatorAddEndpoint" address="axis:http://localhost:8080/axis/Calculator.jws? method=add"> <properties> <property name="style" value="wrapped"/> <property name="use" value="literal"/> <map name="soapMethods"> <list name="qname{add:http://muleumo.org/Calc}"> <entry value="Number1;int;in"/> <entry value="Number2;int;in"/> <entry value="return;int"/>
This endpoint configuration can be used by the MuleClient or on a component outbound router. The client code is now much more simple MuleClient client = new MuleClient("org/mule/test/integration/providers/soap/axis/soap-clientendpoint-config.xml"); UMOMessage result = client.send("calculatorAddEndpoint", new Object[]{new Integer(3), new Integer(3)}, null); assertEquals(result.getPayload(), new Integer(6));
Document generated by Confluence on Apr 24, 2008 08:11
Page 328
Notice the URL for the MuleClient call contains the name of the service endpoint not the physical location of the resource.
Document Literal Mule hosted Web services using Axis cannot be invoked using Doc/Lit, Doc/Lit/Wrapped should be used instead. Users can still invoke remote web services using Doc/Lit as shown in the example below.
Client Example For this example we must tell the Mule client to use 'document/literal' for the message style, and we pass this information into the call on the MuleClient. However, this will not work without some configuration on the Axis server. The biggest limitation of Doc/Lit is that operation/method name is not passed with the message 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"); UMOMessage 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 <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> 3 3
Using Doc/Lit with Axis sometimes may appear to work even when you don't add Operation info to the Axis Server configuration. This happens when there is a single parameter for the service and the parameter name (see Axis Operations) is the same as the operation/ method name you want to invoke.
RPC Encoded Client Example Because Axis uses RPC/Encoded by default there is no need to pass any additional config information. String URL = "axis:http://localhost:8080/axis/Calculator.jws?method=add"; MuleClient client = new MuleClient(); UMOMessage 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 <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>
Document generated by Confluence on Apr 24, 2008 08:11
Page 329
<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 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
Using the WSDL Url TODO
Client Example
Document generated by Confluence on Apr 24, 2008 08:11
Page 330
Axis Soap Transports This page last changed on Jan 30, 2008 by ross.
Quick Links • • • •
Soap over Jms Soap over Vm Binding to a Servlet container Using other Mule transports
Mule transports are used to deliver soap requests between Axis clients and Axis services hosted by Mule. This means you can easily use jms, vm, smtp even xmpp (jabber) to send soap requests. The following describes how to configure each one.
Soap over Jms First you'll need to add a Jms connector to your Mule Xml configuration <properties> <property name="connectionFactoryJndiName" value="ConnectionFactory"/> <property name="jndiInitialFactory" value="org.activemq.jndi.ActiveMQInitialContextFactory"/> <property name="specification" value="1.1"/> <map name="connectionFactoryProperties"> <property name="brokerURL" value="tcp://localhost:61616"/>
We will create a descriptor that listens to a queue called echoComponent. This will be the queue on which the soap request will be sent and the method is the operation to invoke. To expose a Mule service as a soap service over jms you add an inbound endpoint to the component <mule-descriptor name="echoComponent" implementation="org.mule.components.simple.EchoComponent"> <endpoint address="axis:jms://echoComponent"/>
Now all you need to do is configure the service endpoint. Here is an example of a client request endpoint over jms axis:jms://echoComponent?method=echo¶m=hello
When you need to dispatch on a queue having a different name than that of the serviceComponent then the service endpoint will have to be configured in a slightly different way in order to enable us to specify a SoapAction property for Axis to use since Axis will look for a service having the same name as that of our descriptor. For example, if we have the following descriptor configured: <mule-descriptor name="echoComponent" implementation="org.mule.components.simple.EchoComponent"> <endpoint address="axis:jms://soap.echo.queue"/>
Note that the queue name and the descriptor name are no longer the same. However, Axis will still register the service with the name echoComponent so using the following service endpoint will not work: axis:jms://soap.echo.queue?method=echo¶m=hello
Document generated by Confluence on Apr 24, 2008 08:11
Page 331
Instead we will have to add a Soap Action parameter to the endpoint to tell Axis to look for the echoComponent service. Using the MuleClient, this property would be configured in the following way: MuleClient client = new MuleClient(); UMOMessage request = new MuleMessage("hello"); request.setProperty("SOAPAction", "jms://soap.echo.queue/echoComponent"); UMOMessage result = client.send("axis:jms://soap.echo.queue?method=echo", request);
The above can also be achieved through configuration by setting the SOAPAction as a property on the dispatching endpoint. You can configure the Jms soap endping the same way you configure a normal Jms endpoint so that all QoS and transaction options are supported. See the Jms Provider documentation for a full description.
Soap over VM Soap over Mule's Vm transport is also supported. This can be usful for testing or prototyping. The endpoints are configured in the exact same way as Jms soap endpoints. For a client to invoke a service using VM axis:vm://echoComponent?method=echo¶m=hello
And to expose the service over the Vm transport <mule-descriptor name="echoComponent" implementation="org.mule.components.simple.EchoComponent"> <endpoint address="axis:vm://echoComponent"/>
Binding to a Servlet Container In you embed Mule in a webapp you might want to bind Axis services to the Servlet container port rather than open another port for Mule Soap services - you may not be able to do this due to firewall restrictions. In this scenario you can use the Mule Servlet Transport and Axis instead of http. To do this you need to add the MuleReceiverServlet to your web.xml <servlet> <servlet-name>muleServlet <servlet-class>org.mule.providers.http.servlet.MuleReceiverServlet <servlet-mapping> <servlet-name>muleServlet /mule/services/*
Next you need to add a servlet endpoint to your component <mule-descriptor name="TestService" implementation="org.mule.providers.soap.TestServiceComponent"> <endpoint address="axis:servlet://TestService"/>
Note that there is not host or port information on the endpoint, Just the component name. The host, port and path is dictated by the servlet container and the url-pattern of the MuleReceiverServlet. If The servlet container was listening on port 8080 the URL to invoke the service would be http://localhost:8080/mule/services/TestService
Document generated by Confluence on Apr 24, 2008 08:11
Page 332
Using other Mule transports There is no reason why other transports such as smtp or even xmpp couldn't be used to send and receive soap requests. The notation for configuring the endpoint to be used by Axis is to configure the endpoint according to the endpoint scheme and then prepend the axis: scheme. For client endpoints the method param must be set also. //Client axis:xmpp://mule1:[email protected]/axis?method=echo¶m=hello //Server axis:xmpp://mule1:[email protected]/axis
Document generated by Confluence on Apr 24, 2008 08:11
Page 333
Axis Transport This page last changed on Jan 30, 2008 by ross.
Axis Connector Allows Mule managed components to be published as Axis services and allows components to invoke web services using Axis client calls. The AxisConnector can be found at org.mule.providers.soap.axis.AxisConnector .
AxisConnector Properties
Property
Description
Default
Required
serverConfig
The wsdd config file used to configure the axis server for this connector. There is a default server configuration call muleserver-config.wsdd that ships with the provider. This is used if the property is not set.
./mule-serverconfig.wsdd
No
axisServer
The Axis server instance that the connector uses. This can be set as a bean property if using a DI container such as Spring or Pico
No
beanTypes
A list of class names that should be registered with the Axis Type Registry. Axis handles most serialisation for you such as primitives, Numbers, collections and arrays. The instance where you need to declare class names here is when you have a class, say com.foo.Person, that has an attribute of type com.foo.Address, you will need to add com.foo.Address to this list (Axis serialisation doesn't handle nested complex types automatically)
No
MuleDescriptor Properties There are a number of properties that can be set on a Mule compoent configuration that can be used to configure it as an Axis service.
Document generated by Confluence on Apr 24, 2008 08:11
Page 334
Property
Description
beanTypes
A list of class names that should be registered with the Axis Type Registry. Axis handles most serialisation for you such as primitives, Numbers, collections and arrays. The instance where you need to declare class names here is when you have a class, say com.foo.Person, that has an attribute of type com.foo.Address, you will need to add com.foo.Address to this list (Axis serialisation doesn't handle nested complex types automatically). If you have set this property on the connector, there is no need to set it on the component as well. Though the connector beanTypes list should contain a superset of all the types used by all components.
serviceInterfaces
A list of fully qualified interface names that the component implements that should be exposed as part of the Axis service descriptor.
axisOptions
A Map of configuration options that will be passed to the Axis configuration provider for this component. The common two options that can be set here are 1. allowedMethods A comma separated list of methods to expose. The default is '*' 2. scope - scope of the web service. Can be Request, Session or Application. The default is 'Request'.
No
documentation
A description of the web service that will be
No
Document generated by Confluence on Apr 24, 2008 08:11
Default
Required No
All interface methods are exposed
No
Page 335
displayed when a list of available services are requested.
Programmatic Configuration If you want to programmatically configure your Axis service you can implement the org.mule.providers.soap.axis.AxisInitialisable interface. This will pass the SOAPService object to your component where it can be manipulated.
Document generated by Confluence on Apr 24, 2008 08:11
Page 336
Axis Web Services and Mule This page last changed on Jan 30, 2008 by ross.
Axis integrates with Mule meaning you can expose Mule components as Axis services and invoke Axis Services from mule. To expose a Mule component as an Axis service all you have to do is set the components receive endpoint to An Axis URL. Please note that web services expect methods to be exposed through interfaces implemented by their respective components. Otherwise, you will receive configuration errors during Mule start-up. <mule-descriptor name="echoService" inboundEndpoint="axis:http://localhost:81/services" implementation="org.mule.components.simple.EchoComponent">
When Mule starts, the service will be available on http://localhost:81/services/echoService. The Echo component class implements the EchoService interface that has a single method called echo that accepts a single parameter string.
Invoking Web Services There are two ways of invoking webservices from Mule. 1. Programmatically using the Mule Client 2. As part of the event flow of a UMO Component Each method is described in detail in the following sections.
Invoking Services with the MuleClient To invoke Echo Service using the Mule Client, use the following TestEchoService.java public static void main(String[] args) { MuleClient client = new MuleClient(); UMOMessage 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 Component To invoke the Echo Service from a component you need to add an outbound endpoint to your component descriptor. The example shown below is a component that receives an event on vm://test.component, does some work on the event and then invokes or echo service. <mule-descriptor name="test" implementation="com.foo.TestComponent"> <endpoint address="vm://test.component" synchronous="true"/> <endpoint address=" axis:http://localhost:81/services/echoService?method=echo"/>
The org.foo.TestComponent looks like org.foo.TestComponent
Document generated by Confluence on Apr 24, 2008 08:11
Page 337
public class TestComponent implements Callable { public Object onCall(UMOEventContext 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, just return an array of parameters in your component. When an event is published vm://test.component the onCall method will be called with the current event. After the onCall method executes, Mule will invoke the outbound endpoint for TestComponent with what is returned from the onCall method call. Note that the vm://test.component endpoint has a parameter synchronous=true. This tells Mule to invoke requests from that endpoint in a single thread, making it a request/response style request. Thus the result of invoking the Echo Service (by invoking Test Component) will be returned to the callee who dispatched the event on vm://test.component. When the TestEchoService is run you will see the following output Message Echoed is: Hello!
Using Quick Configuration When testing it can be cumbersome to start a separate Mule server to test a service, so you can use the QuickConfigurationBuilder to start a server and register your service in your test code i.e. QuickConfigurationBuilder builder = new QuickConfigurationBuilder(); builder.createStartedManager(true, ""); UMOEndpoint soapEndpoint = new MuleEndpoint("axis:http://localhost:81/services"); builder.registerComponent(EchoComponent.class.getName(), "echoService", soapEndpoint);
See Configuring Mule Programmatically for more information. There are a couple of things to note about this demonstration 1. There is no need for a Servlet container as Mule is the container 2. You don't need to specify a deployment WSDD for your service. All you need to do is specify an endpoint for the service and the rest is done for you. 3. The MuleClient call will work just as well if the service you are invoking is hosted by an Axis instances running on Tomcat or any other Servlet Engine. You will need to have the Axis jar and associated jars on your classpath, these ship with the Mule distribution. Exposing Services All service operations are exposed through interfaces implemented by your component. This means your component must implement at least one service interface. This is generally good practice anyway.
Axis without a Servlet Container Using Axis with Mule means there is no need for a separate servlet container. When an axis endpoint such as 'axis:http://localhost:81/services' is declared, mule does a couple of things -
Document generated by Confluence on Apr 24, 2008 08:11
Page 338
• Creates an Axis Component in Mule. This is analogous to the AxisServlet, there is only one per Mule instance. • Creates a http connector for localhost:81 and registers it as a receiver for the Axis component. Cannot resolve external resource into attachment. Most web services are a lot more complex than the first example so the following sections will tell you how to configure the Axis instance and your services in more detail.
Configuring the Axis Server In the previous example, a default Axis connector is created when the axis endpoint is processed by Mule. The Axis connector uses a default server configuration file called mule-axis-server-config.wsdd. You can override this configuration by setting the serverConfig on the connector. This will allow you add additional Handlers, global configuration, etc. <properties> <property name="serverConfig" value="./axis/axis-server-config.wsdd"/>
If you use a custom server configuration remember to add the following handlers in the global configuration <requestFlow>
If you are configuring Mule from a container such as Spring, you can set the Axis server as a bean property (axisServer) on the connector and the serverConfig property is ignored. You can list the Axis services in the same way you list services when Axis is hosted in a servlet container. To list services simply point your browser at the host and port of the axis endpoint http://localhost:81/
To view Axis version information go to http://localhost:81/Version?method=getVersion
To view the WSDL for the service go tohttp://localhost:81/Version?wsdl
Note that the Axis JWS feature is not supported by Mule. Soap over Other Transports You can configure Axis to send/receive soap requests over other transports such as Jms and Smtp. For more information see Axis Soap Transports. For more information about customising Axis behaviour, Naming parameters, Message style options and more see Configuring Axis.
Document generated by Confluence on Apr 24, 2008 08:11
Page 339
Configuring Axis This page last changed on Mar 21, 2008 by yuenchi.lian.
Quick Links • • • • • • • • • •
Controlling Exposed Methods Document Styles Map as Parameters Service Properties Customising the Soap Action Named Parameters WSDL Generation Object Type Mappings Customising the Mule Axis Service Service Initialisation Callbacks
Configuring Mule Components As Axis Services Controlling exposed methods Often a service will not want to expose all it's methods to the outside world. One way to restrict the exposure is to set the serviceInterfaces property. This is a list of interface names that the service implements and that should be exposed. <mule-descriptor name="testService" implementation="org.mule.providers.soap.TestServiceComponent" inboundEndpoint="axis:http://localhost:38009/mule/services"> <properties> <list name="serviceInterfaces"> <entry value="org.mule.providers.soap.EchoService"/> <entry value="org.mule.providers.soap.DateService"/>
You can also specify one or more methods to expose in a comma separated list, using the axisOptions property (discussed in more detail later). <mule-descriptor name="testService" implementation="org.mule.providers.soap.TestServiceComponent" inboundEndpoint="axis:http://localhost:38009/mule/services"> <properties> <map name="axisOptions"> <property name="allowedMethods" value="echo,getDate"/>
Map as parameter The AxisConnector treats a Map as container for named parameters, which eventually will be unpacked... This will result into a problem if your exposed service needs to take a Map as a parameter, because the actual Map will never reach the service intact. There is one way though to configure the connector not to unpack Maps, so that these can be passed as parameters. The configuration of the connector looks as follows: <properties> <property name="treatMapAsNamedParams" value="false" />
Document generated by Confluence on Apr 24, 2008 08:11
Page 340
Setting SOAP Document Style The style and Uses properties can be set for a service by setting the properties on the mule-descriptor. For example to make your service Document/Literal/Wrapped <mule-descriptor name="testService" implementation="org.mule.providers.soap.TestServiceComponent" inboundEndpoint="axis:http://localhost:38009/mule/services"> <properties> <property name="style" value="Wrapped"/> <property name="use" value="Literal"/>
The style property can be on of: 'RPC' (default), 'Document', 'Message', or 'Wrapped'. And the use property can either be 'Encoded' (default) or 'Literal'. For more information about service styles and Mule see Axis SOAP Styles, also take a look at the Axis website.
Setting Service Properties Service properties are attributes that are set on the Axis service object itself. The two useful properties to set here are scope and allowedMethods, through there may be others depending on your Axis server configuration. <mule-descriptor name="testService" implementation="org.mule.providers.soap.TestServiceComponent" inboundEndpoint="axis:http://localhost:38009/mule/services"> <properties> <map name="axisOptions"> <property name="allowedMethods" value="*"/> <property name="scope" value="Application"/>
If these properties are not set the default Axis values are used.
Customising the soapAction format By default Mule uses the axis endpoint as the soapAction when make WS calls. This is fine for Axis clients but may not work with .Net clients. In fact the soapAction can be different across different soap implementations so developers need a way to customise how the soap Action is formatted. Mule users can set the soapAction on the outbound endpoint making the soap request i.e. <endpoint address="axis:http://localhost:38011/mule/echoService?method=echo" synchronous="true"> <properties> <property name="soapAction" value="http://localhost:38011/${method}"/>
The above example sets the soapAction on the request to _http://localhost:38011/echo_. If using the Mule Client you can set the soapAction as a property when making the call. The soap Action can be a static value or you can use template variables such as the method variable used above. The set of variables that can be used are listed below.
Document generated by Confluence on Apr 24, 2008 08:11
Page 341
Variable
Description
Example
method
The service method name being invoked
echo
methodNamespace
The service method name being invoked
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 soap endpoint
localhost
port
The port from the soap endpoint
38011
path
The path info from the soap endpoint
/mule/echoService
hostInfo
The scheme, host and port combined
http://localhost:38011
serviceName
The name of the service being invoked
echoService
other properties
Any other properties on the event or the endpoint can be refernced by name in the soapAction expression
Setting Named Parameters Some WebService clients require that all method parameters of a call should be named. You can do this in Mule in two ways. 1. In the Mule Xml the soap method parameters for a servie can be set on the endpoint using the soapMethods property map. <endpoint address="axis:http://localhost:38011/mule/echoService?method=echo" synchronous="true"> <properties> <map name="soapMethods"> <property name="echo" value="value;string;in,return;string"/>
Within the map element you can define 1 or more property elements where the name attribute is the method name and the value is a string representation of the named parameters of the method and the return type. The parameter string is in the format of [paramName1];[type];[mode],[paramName2];[type]; ...,[return;type]
The parameterName is the name of the parameter. The type is an XSD string such as int, long, map, etc. and the parameter mode can be in, out or inout. The return type is also an XSD type string. You can also set the returnClass instead of return and provider a fuly qualified classname instead of an XSD type. If you have a lot of named parameters you can pass in a list of parameters i.e. <endpoint address="axis:http://localhost:38011/mule/concatService?method=concat" synchronous="true">
Document generated by Confluence on Apr 24, 2008 08:11
Page 342
<properties> <map name="soapMethods"> <list name="concat"> <entry value="string1;string;in"/> <entry value="string2;string;in"/> <entry value="result;string;out"/>
Controlling Namespaces Namespaces for elements can be controled at the method and parameter level or declare a namespace on the method with a prefix of 'foo' with a uri of 'http://mycompany.com/foo' use the following <endpoint address="axis:http://localhost:38011/mule/echoService?method=echo" synchronous="true"> <properties> <map name="soapMethods"> <property name="qname{foo:echo:http://mycompany.com/foo}" value="value;string;in,result;string;out"/>
The syntax for the qname{} is qname{[prefix]:[localname]:[namespace]}
You can supply either just a localname, localname and namespace or a prefix, localname and namesspace. The namespace for the method will be applied to the parameters also, but you can set the namespace for each parameter explicitly also using an identical syntax i.e. <endpoint address="axis:http://localhost:38011/mule/echoService?method=echo" synchronous="true"> <properties> <map name="soapMethods"> <list name="qname{foo:echo:http://mycompany.com/foo}"> <entry value="qname{foo1:echo1:http://mycompany.com/foo1};string;in"/> <entry value="return;string"/>
To set method parameter name using the MuleClient you need to create a SoapMethod object and set it on the properties when making the call. The example below shows how to do this. MuleClient client = new MuleClient(); Map props = new HashMap(); //create the soap method passing in the method name and return type SoapMethod soapMethod = new SoapMethod("echo", NamedParameter.XSD_STRING); //add one or more parameters soapMethod.addNamedParameter("value", NamedParameter.XSD_STRING, ParameterMode.IN); //set the soap method as a property and pass the properties //when making the call props.put(MuleProperties.MULE_SOAP_METHOD, soapMethod); UMOMessage 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 MuleClient.
Document generated by Confluence on Apr 24, 2008 08:11
Page 343
Controlling WSDL Generation Most commonly, you will want to set the namespace for your service. this can be done by setting the 'serviceNamespace' property on your service i.e. <mule-descriptor name="testService" implementation="org.mule.providers.soap.TestServiceComponent"> <endpoint address="axis:[http://localhost:38009/mule/services]"/> <properties> <property name="serviceNamespace" value="http://foo.namespace"/>
You can also set the 'wsdlFile' property to the location of a wsdl document to use for this service if you do not want an autogenerated WSDL document. You can control the values used in Axis wsdl generation by setting wsdl specific Axis options. Not you do not need to changes these values, but if you want to you can. The options you can set are -
Option Name
Description
wsdlPortType
Sets the wsdl:portType name attribute. the Axis default is $Proxy0
wsdlServiceElement
Sets the wsdl:service name attribute. the Axis default is $Proxy0Service
wsdlTargetNamespace
Sets the wsdl:definitions targetNamespace attribute. The Axis default is http:// plus package name of the service class in reverse.
wsdlServicePort
Sets the wsdl:port name attribute of the wsdl:service element. The default is the name of the Mule component exposed by this service endpoint.
wsdlInputSchema wsdlSoapActionMode extraClasses To change the wsdlServiceElement name attribute to MyService in the generated Wsdl for a service use the following <mule-descriptor name="testService" implementation="org.mule.providers.soap.TestServiceComponent"> <endpoint address="axis:http://localhost:38009/mule/services"/> <properties> <map name="axisOptions"> <property name="wsdlServiceElement" value="MyService"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 344
Type mappings Note that as of Axis 1.2-RC3 it is no longer necessary to configure Type Mappings as bean serialisation is handled automatically by Axis. If you are using an older version of Axis Type Mappings may need to be configured. Mule enables default type mappings for object serialisation between soap calls. This means, for the most part serialisation/deserialisation of call parameters and return objects is handled automatically by Axis. This works for most java types including primitives, Numbers, Strings, Arrays and Collections, it also works for JavaBeans whose attributes comprise of these types. However, it does not work where you have a bean that has as another bean as an attribute; Axis will complain that it doesn't know how to handle the bean attribute. Mule handles this by allowing you to specify a list of beanTypes that Axis needs to understand in order to manage your service. For example, say you have a PersonService service that will get a Person object when passed the persons name. The Person object contains an Address object. The configuration will look like <mule-descriptor name="personService" implementation="org.foo.PersonServiceComponent" inboundEndpoint="axis:http://localhost:38009/mule/services"> <properties> <list name="beanTypes"> <entry value="org.foo.Address"/>
It is important to note that only custom types should be listed. If any standard types are present, like java.util.ArrayList, Axis may produce serialization errors.
For convenience, the BeanTypes property can be set on an Axis connector configuration so that all services that use the connector will have the types registered in the TypeRegistry for the service. <properties> <list name="beanTypes"> <entry value="org.foo.Address"/>
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.
Customising the Axis Service Component The Axis Service component is a Mule managed component that handles axis service requests. This component is equivilent to the Axis Servlet used when running Axis in a servlet container. Being a Mule managed component you can configure how threading, pooling and queuing behaves for the component. By default, when the Axis Service component is created it will be assigned the default threading, pooling and queuing as defined in the MuleConfiguration object. If your Mule instance is receiving a high number of requests you may want to increase the compoent pool size. To customise the Axis Service component you need to configure a mule-descriptor with a name of _axisServiceComponent and set the relevant properties on it. For example <mule-descriptor name="_axisServiceComponent" implementation="org.mule.providers.soap.axis.AxisServiceComponent"> <pooling-profile exhaustedAction="GROW" maxActive="20"
Document generated by Confluence on Apr 24, 2008 08:11
Page 345
maxIdle="20"/>
Service Initialisation Callback If you need further control over the Axis service created by Mule it is possible for your component to implement AxisInitialisable. AxisInitialisable.java public interface AxisInitialisable { public void initialise(SOAPService service) throws InitialisationException; }
This gets called when the service is initialised and allows you to customise the service configuration form your Mule component.
Document generated by Confluence on Apr 24, 2008 08:11
Page 346
Glue This page last changed on Jan 30, 2008 by ross.
WebMethods Glue integrates with Mule meaning you can expose Mule components as Glue Web Services and invoke Glue Web Services from Mule. This document provides a beginner overview of how to configureGlue endpoints in Mule. Also take a look at how to configure the Glue connector. To expose a Mule component as an Glue service all you have to do is set the components receive endpoint to An Glue URL, i.e. <mule-descriptor name="echoService" inboundEndpoint="glue:http://localhost:81/services" implementation="org.mule.components.simple.EchoComponent">
When Mule starts, the service will be available on http://localhost:81/services/echoService. The Echo component class has a single method called echo that accepts a single parameter string that it will echo back to the client. To invoke the service you can use the Mule Client i.e. TestEchoService.java public static void main(String[] args) { MuleClient client = new MuleClient(); UMOMessage result = client.send ("glue:http://localhost:81/services/echoService?method=echo", "Hello!", null); System.out.println("Message Echoed is: " + result.getPayload()); }
When the TestEchoService is run you will see the following output Message Echoed is: Hello!
Getting the WSDL To get the WSDL for a Glue service hosted by Mule you add ".wsdl" to the service URL. Using the example service above you would use http://localhost:81/services/echoService.wsdl
Downloading Glue Unfortunately due to Webmethods license restrictions, Mule cannot ship with Glue. Webmethods have either made it extremely difficult to locate Glue on their website or they have removed it. If you're using this connector it's assumed that you have the glue jar kicking around somewhere. You only need to include the glue.jar on the Mule classpath. Mule works with Glue Standard Edition and above.
Configuring Mule Components As Glue Services Service Initialiation Callback If you need control over the Glue service created by Mule it is possible for your component to implement org.mule.providers.soap.glue.GlueInitialisable. GlueInitialisable.java public interface GlueInitialisable { public void initialise(IService service, ServiceContext context) throws InitialisationException; }
Document generated by Confluence on Apr 24, 2008 08:11
Page 347
This gets called when the service is initialised and allows you to customise the service configuration form your Mule component. The service created is an instance of electric.service.virtual.VirtualService which is a proxy that invokes the underlying Mule component. Developers can use the the ServiceContext to add handlers and other configuration to the service before it is registered with the Glue server. Unlike the Axis Support the Glue provider uses Glue's internal Http server rather that the Mule Http Transport.
Document generated by Confluence on Apr 24, 2008 08:11
Page 348
Glue transport This page last changed on Jan 30, 2008 by ross.
Glue Connector Allows Mule managed components to be published as Glue services and allows components to invoke web services using Glue client calls. The GlueConnector can be found at org.mule.providers.soap.glue.GlueConnector .
GlueConnector Properties There are no specific properties that can be set on the Glue connector
MuleDescriptor Properties There are a couple of properties that can be set on a Mule component configuration that can be used to configure it as an Glue service.
Property
Description
Default
Required
serviceInterfaces
A list of fully qualified interface names that the component implements that should be exposed as part of the Axis service descriptor.
All interface methods are exposed
No
Programmatic Configuration If you want to programmatically configure your Glueservice you can implement the org.mule.providers.soap.glue.GlueInitialisable interface. This will pass the IService object and ServiceContext objects to your component where they can be manipulated.
Document generated by Confluence on Apr 24, 2008 08:11
Page 349
REST This page last changed on Apr 18, 2008 by tcarlson.
MULE:Servlet Binding - Configure Mule to Expose services using REST. REST Service Wrapper - Proxy REST service calls to invoke them as local components. MULEINTRO:Stock Quote Example - An Example of invoking a ASPX webservice using the REST service Wrapper.
Document generated by Confluence on Apr 24, 2008 08:11
Page 350
XFire This page last changed on Jan 30, 2008 by ross.
XFire is a next-generation Soap framework that makes service-oriented development approachable through its easy to use API and support for standards. It is also highly performant since it is built on a low memory StAX based model.
XFireConnector Properties Property
Description
Default
Required
clientInHandlers
A List of org.codehaus.xfire.handler.Handler objects for processing of incoming messages
No
clientOutHandlers
A List of org.codehaus.xfire.handler.Handler objects for processing of outgoing messages
No
clientTransport
Specifies the underlying transport for the client to use (http, jms, etc.)
No
clientServices
Specifies the underlying transport for the service to use (http, jms, etc.)
No
bindingProvider
The classname for the XFire binding provider
org.codehaus.xfire.aegis.AegisBindingProvider No
typeMappingRegistry
The classname for the XFire type mapping registry (AegisBindingProvider only)
org.codehaus.xfire.aegis.type.DefaultTypeMappingRegistry No
Exposing Mule services via XFire Mule services can be exposed using XFire making them Soap services that use streaming for better memory performance. Right now you can expose Xfire services over http and vm transports, but support for other Mule transports such as JMS, HTTPS, TCP, XMPP and SMTP will also be available soon. To expose a Mule component as an XFire service all you have to do is to set the component's receive endpoint to a XFire URL, i.e. <mule-descriptor name="echoService" implementation="org.mule.components.simple.EchoComponent"> <endpoint address="xfire:http://localhost:81/services"/>
When Mule starts, the service will be available on http://localhost:81/services/echoService. The Echo component class has a single method called echo that accepts a single parameter string that it will echo back to the client. To invoke the service you can use the Mule Client i.e. TestEchoService.java
Document generated by Confluence on Apr 24, 2008 08:11
Page 351
public static void main(String[] args) { MuleClient client = new MuleClient(); UMOMessage result = client.send("xfire:http://localhost:81/services/echoService?method=echo", "Hello!", null); System.out.println("Message Echoed is: " + result.getPayload()); }
When the TestEchoService is run you will see the following output Message Echoed is: Hello!
Getting the WSDL To get the WSDL for a XFire service hosted by Mule you add "?wsdl" to the service URL. Using the example service above you would use http://localhost:81/services/echoService?wsdl
Exposing methods using Interfaces/Abstract Classes... If you have a service and would like to expose just the methods overriden from a specific interface, then it is easy. The configuration is exactly the same as the way Axis is configured to use Interfaces to expose methods. <mule-descriptor name="HelloWorld" implementation="com.ricston.components.HelloWorld"> <endpoint address="xfire:http://localhost:82/services"/> <properties> <list name="serviceInterfaces"> <entry value="com.ricston.components.IHelloWorld"/>
Although the property serviceInterfaces is a list, which of course might contain more than one element, only the first interface will be considered. If you would like to expose methods from two or more interfaces, the work around is very simple. You need to create an abstract class which implements the interfaces you want to expose. In the serviceInterfaces list, then you just need to add this new abstract class.
Setting your custom Namespace You can choose to change the default Namespace that Mule uses to your own custom namespace. This can be done by setting the configuration property SOAP_NAMESPACE_PROPERTY on the component. The following is an example where the namespace is set to: http://mycustomnamespace.com <mule-descriptor name="echoService" implementation="org.mule.components.simple.EchoComponent"> <endpoint address="xfire:http://localhost:81/services"/> <properties> <property name="SOAP_NAMESPACE_PROPERTY" value="http://mycustomnamespace.com"/>
Messaging Styles The following describes how to configure diffent messaging styles for XFire services in Mule. To configure the style of service to use you set the style and use properties on the service object i.e.
Document generated by Confluence on Apr 24, 2008 08:11
Page 352
<mule-descriptor name="echoService" implementation="org.mule.components.simple.EchoComponent"> <endpoint address="xfire:http://localhost:81/services"/> <properties> <property name="style" value="document"/> <property name="use" value="literal"/>
Doc Lit TODO
RPC Wrapped TODO
Message TODO
RPC Encoded RPC encoded is not supported by XFire. For this request style you need to use either the Mule Axis or Glue transport.
Using Other Transports As well as Http, Mule allows you to expose SOAP services using other transports such as JMS, XMPP and SMTP. The following gives examples of each.
SOAP over VM Exposing your XFire service over the VM Transport is not very useful in production but is useful for development and testing. To expose the service using VM you specify the xfire and vm protocol and the component name, as shown below <mule-descriptor name="echoService" implementation="org.mule.components.simple.EchoComponent"> <endpoint address="xfire:vm://echoService"/>
SOAP over JMS TODO
SOAP over HTTPS TODO
SOAP over XMPP TODO
SOAP over SMTP TODO
Document generated by Confluence on Apr 24, 2008 08:11
Page 353
Sending Complex Types to a Web Service When it comes to sending Complex types with Xfire, both when using xfire and wsdl-xfire, a mapping needs to be created in order for the soap request to be built. The complex types need to be configured on the outbound endpoint as shown in the configuration below: <endpoint address="xfire:http://localhost:9999/services/PeopleServiceWS? method=addPersonWithConfirmation"> <properties> <map name="complexTypes"> <property name="org.mule.tck.testmodels.services.Person" value="Person:http://services.testmodels.tck.mule.org"/>
The map "complexTypes" is a map that can contain one or more complex types. The actual complex types are defined as properties of the complexTypes map. The above example shows how we can send the org.mule.tck.testmodels.services.Person bean over xfire. The class name is specified as the property's name, while the value should contain the complex type name as defined in the wsdl (in this case Person) and the namespace (which is also specified in the wsdl), separated by a ':'. The format should be as follows: complex type : namespace
Document generated by Confluence on Apr 24, 2008 08:11
Page 354
Writing Transports This page last changed on Apr 18, 2008 by tcarlson.
Transport providers are used to provide connectivity to an underlying data source or message source in a consistent way. Mule transport providers can be one of three types 1. inbound-only: Components can only subscribe to events, they cannot dispatch events. 2. outbound-only: Components can only dispatch events, but cannot subscribe to events. 3. inbound-outbound: Components can subscribe and dispatch events
In a Nutshell A transport provider consists of a set of interface implementations that expose the features for the underlying transport. Cannot resolve external resource into attachment. || Interface || Role ||
Connector
Used to manage Receivers and Dispatchers and used to store any configuration information
Message Receiver
Implements the 'server-part' of the transport. For example, a TcpMessageReceiver creates a server socket to receive incoming requests. A UMOMessageReceiver instance is created when components use this transport for inbound communication
Message Dispatcher
Implements the 'client-part' of the transport. For example, a TcpMessageDispatcher creates a socket to send requests. A UMOMessageDispatcher instance is created when components use this transport for outbound communication
Message Adapter
Is contained in the event and wraps the underlying message type used by this transport, To use TCP as an example, the Message adapter simply wraps a byte array. For JMS, the JMS message payload is exposed as the message payload and all Header and user properties are accessible using getProperty/setProperty on the message adapter
Transformers
Transformers are used to marshall data to and from the transport specific data format i.e. a Http Request or Jms Message.
Endpoints
Are the means of configuring communication channels to and from components. The endpoint defines which transport protocol to use, things like host name or queue name, plus other information such as a filter to use and transaction info. Defining an endpoint on a component will cause mule to create the necessary transport connector for the protocol being used.
Transport Provider Interfaces There are set of interfaces that need to be implemented when writing a transport provider for Mule. These interfaces define the contract between Mule and the underlying technology.
Document generated by Confluence on Apr 24, 2008 08:11
Page 355
org.mule.umo.provider.UMOConnector The connector is used by Mule to register listeners and create message dispatchers for the transport. Configuration parameters that should be shared by all Message Receivers and Dispatchers are stored on the connector. Usually, only one connector instance is needed for multiple inbound and outbound endpoints as multiple Message Receivers and Dispatchers can be associated with a connector. However, where the underlying transport API has the notion of a Connection such as the JMS or JDBC API there should be a one to one mapping between Mule Connector and the underlying connection.
org.mule.umo.provider.UMOMessageReceiver The JavaDoc for this interface can be found here The Message Receiver is used to receive incoming data from the underlying transport and package it up as an event. The Message Receiver is essentially the server implementation of the transport (where the Message Dispatcher is a client implementation). For example, the Http Message Receiver is a Http server implementation that accepts http requests. An implementation of this class is needed if the transport supports inbound communication.
org.mule.umo.provider.UMOMessageDispatcher The Message Dispatcher is used to send events, which is akin to making client calls with the underlying technology. For example the Axis Message Dispatcher will make a web service call. An implementation of this class is needed if the transport supports outbound communication.
org.mule.umo.provider.UMOMessageDispatcherFactory This is a factory class used to create UMOMessageDispatcher instances. An implementation of this class is needed if the transport supports outbound communication.
org.mule.umo.provider.UMOMessageAdapter The message adapter is used to provide a consistent way of reading messages in Mule. The massage adapter provides methods for reading the payload of the message and reading message properties. These properties may be message headers, custom properties or other meta information about the message.
Implementation Where do I start? With the maven Transport Archetype of course!
Abstract base classes to extend Mule provides abstract implementations for all of the above interfaces. These implementations handle all the Mule specifics leaving a few abstract methods where custom transport code should be implemented. So writing a custom transport provider is as easy as writing/embedding client and or server code specific to the underlying technology. The following sections describes the implementations available to you.
Connectors The org.mule.providers.AbstractConnector implements all the default functionality required for Mule connectors, such as threading configuration, and receiver/dispatcher management. Details about the standard connector properties can be found here. Further properties can be set on the connector depending on the implementation. Often a connector will have a set of properties that can be overridden on a per endpoint basis, meaning the properties set on the connector serve as defaults when an endpoint configuration doesn't provide overrides.
Document generated by Confluence on Apr 24, 2008 08:11
Page 356
Sometimes connector is responsible for managing a connection resource of the transport where the underlying technology has the notion of a Connection, such as in Jms or Jdbc. These types of connector will have a one to one mapping between a Mule connector and the underlying connection. So if you want to have two or more physical Jms connections in a single Mule instance a new connector should be created for each connection. For other transports there will be only connector of a particular protocol in a Mule Instance that manages all endpoint connections. One such example would be socket based transports such as Tcp where each receiver manages its own ServerSocket and the connector manages multiple receivers. Methods to Implement
Method Name
Description
Required
getProtocol()
This should return the protocol of the provider such as 'smtp' or 'jms'.
Yes
doInitialise()
Is called once all bean properties have been set on the connector and can be used to validate and initialise the connectors state.
No
doStart()
If there is a single server instance or connection associated with the connector i.e. AxisServer or a Jms Connection or Jdbc Connection, this method should put the resource in a started state.
No
doConnect()
Makes a connection to the underlying resource if this is not handled at the receiver/ dispatcher level.
No
doDisconnect()
Close any connection made in doConnect().
No
doStop()
Should put any associated resources into a stopped state. Mule will automatically call the stop() method
No
doDispose()
Should clean up any open resources associated with the connector.
No
Message Receivers Message Receivers will behave a bit differently for each transport, but Mule provides some standard implementations that can be used for polling resources and managing transactions for the resource. Usually there are 2 types of Message Receiver: Polling and Listener-based. 1. A Polling Receiver polls a resource such as the file system, database and streams. 2. The Listener-based type is a receiver that register itself as a listener to a transport. Examples would be JMS (javax.message.MessageListener); Pop3 (javax.mail.MessageCountListener). These base types may be transacted. The abstract implementations provided by Mule are described below.
Document generated by Confluence on Apr 24, 2008 08:11
Page 357
AbstractMessageReceiver The JavaDoc for this class can be found here The AbstractMessageReceiver provides methods for routing events. Developers extending this class should set up the necessary code to register the object as a listener to the transport. This will usually be a case of implementing a listener interface and registering itself . Methods to Implement
Method name
Description
Required
doConnect()
Should make a connection to the underlying transport i.e. connect to a socket or register a soap service. When there is no connection to be made this method should be used to check that resources are available. For example the FileMessageReceiver checks that the directories it will be using are available and readable. The MessageReceiver should remain in a 'stopped' state even after the doConnect() method is called. This means that a connection has been made but no events will be received until the start() method is called. Calling start() on the MessageReceiver will call doConnect() if the receiver hasn't connected.
Yes
doDisconnect()
Disconnects and tidies up any rources allocted using the doConnect() method. This method should return the MessageReceiver into a disconnected state so that it can be connected again using the doConnect() method.
Yes
doStart()
Should perform any actions necessary to enable the receiver to start receiving events. This is different to the doConnect() method which actually makes a connection to the transport, but leaves the MessageReceiver in a stopped state. For pollingbased MessageReceivers the start() method simply starts the polling thread, for the Axis Message receiver the start method on the SOAPService is called. What action is performed here depends on the transport being used. Most of the time a custom provider doesn't need to override this method.
No
Document generated by Confluence on Apr 24, 2008 08:11
Page 358
doStop()
Should perform any actions necessary to stop the receiver from receiving events.
No
doDispose()
Is called when the connector is being disposed and should clean up any resources. The doStop() and doDisconnect() methods will be called implicitly when this method is called.
No
PollingMessageReceiver The JavaDoc for this class can be found here Its quite common for some transport providers to poll a resource periodically waiting for new data to arrive. The PollingMessageRecievers implements the code necessary to setup and destroy a listening thread and provides single method poll() that is invoked repeatedly at a given frequency. Methods to Implement
Method name
Description
Required
poll()
Is executed repeatedly at a configured frequency. This method should execute the logic necessary to read the data and return it. The data returned will be the payload of the new event. Returning null will cause no event to be fired.
Yes
TransactedMessageReceiver The TransactedMessageReceiver can be used by transaction-enabled transports to manage transactions for incoming requests. This receiver uses a transaction template to execute requests in transactions and the transactions themselves are created according to the endpoint configuration for the receiver. Methods to Implement (in addition to those in the standard Message Receiver)
Method name
Description
Required
getMessages()
returns a list of objects that represents individual event payloads. The payload can be any type of object and will by sent to Mule Services wrapped in an MuleEvent object.
Yes
processMessage(Object)
is called for each object in the list returned from getMessages(). Each object processed is managed in its own transaction.
Yes
Connection Strategy Connection Strategy classes can be used to customise the way a connection is made to the transport when the connection fails or the Mule connector is started. Connection strategies are responsible for
Document generated by Confluence on Apr 24, 2008 08:11
Page 359
controlling how and when the doConnect() method is called on the UMOMessageReceiver and can provide fault tolerance when endpoints unexpectedly disconnect. For example a strategy may be to try and reconnect 4 times at 5 second intervals. Connection strategies can be configured on each connector independently or a global strategy can be set on the MuleConfiguration object (which is configured in XML using the <mule-environment-properties> element). Custom connection strategies must implement org.mule.providers.ConnectionStrategy. There is an AbstractConnectionStrategy that has support for executing the connection in a separate thread in case of a long-running strategy.
Thread Management It's common for receivers to spawn a thread per request. All receiver threads are allocated using the WorkManager on the receiver. The WorkManager is responsible for executing units of work in a thread. It has a thread pool that allows threads to be reused and ensures that only a prescribed number of threads will be spawned. The WorkManager is an implementation of UMOWorkManager which really just a wrapper of javax.resource.spi.work.WorkManager with some extra lifecycle methods. There is a getWorkManager() method on the AbstractMessageReceiver that can be used to get reference to the WorkMAnager for the receiver. Work items (i.e. the code to execute in a separate thread) must implement javax.resource.spi.work.Work. This extends java.lang.Runnable and thus has a run() method which will be invoked by the WorkManager. When scheduling work with the WorkManager it is recommended that Developers call scheduleWork(...) on the WorkManager rather than startWork(...).
Message Dispatchers Messages Receivers are equivalent to a server for the transport in that it will serve up client requests. Whereas, Message Dispatchers are the client implementation of the transport. They are responsible for making client requests over the transport, such as writing to a socket or invoking a web service. The AbstractMessageDispatcher provides a good base implementation leaving 3 methods for the custom MessageDispatcher to implement. Methods to Implement
Method name
Description
Required
doSend(UMOEvent)
Should send the event payload over the transport. If there is a response from the transport it should be returned from this method. The sendEvent method is called when the endpoint is running synchronously and any response returned will ultimately be passed back to the callee. This method is executed in the same thread as the request thread.
Yes
doDispatch(UMOEvent)
Is invoked when the endpoint is asynchronous and should invoke the transport but not return any result. If a result is returned it should be ignored and if they underlying transport does have a notion of asynchronous processing, that should be invoked. This method is executed in a different thread to the request thread.
Yes
Document generated by Confluence on Apr 24, 2008 08:11
Page 360
doReceive(long)
Can be used to make arbitrary requests to a transport resource. if the timeout is 0 the method should block until an event on the endpoint is received.
Yes
doConnect()
Should make a connection to the underlying transport i.e. connect to a socket or register a soap service. When there is no connection to be made this method should be used to check that resources are available. For example the FileMessageDispatcher checks that the directories it will be using are available and readable. The MessageDispatcher should remain in a 'stopped' state even after the doConnect() method is called.
Yes
doDisconnect()
Disconnects and tidies up any resources allocated using the doConnect() method. This method should return the MessageDispatcher into a disconnected state so that it can be connected again using the doConnect() method
Yes
doDispose()
Is called when the Dispatcher is being disposed and should clean up 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 the AbstractMessageDispatcher. When a request is made for a dispatcher, it is looked up from a dispatcher cache on the AbstractConnector. The cache is keyed by the endpoint being dispatched to. If a Dispatcher is not found one is created using the MessageDispatcherFactory and then stored in the cache for later. If developers want a new Dispatcher to be created for each request they can set the disposeDispatcherOnCompletion property on the AbstractConnector to true. This will essentially turn off dispatcher caching.
Message Adapters MessageAdapters are usually simple objects that provide a uniform way of accessing an event payload and associated metadata from a format used by the underlying transport. Almost all messaging protocols have the notion of message payload and header properties, which means that a MessageAdapter just needs to allow access to the header properties using standard Map notation i.e. //Jms message id String id = (String)message.getProperty("JMSMssageID"); or //Http content length int contentLength = message.getIntProperty("Content-Length");
Document generated by Confluence on Apr 24, 2008 08:11
Page 361
Note that the property names use the same name that is used by the underlying transport; 'ContentLength' is a standard Http header name and JMSMessageID is the equivalent bean property name on the javax.jms.Message interface. Message Adapter should extend the org.mule.provider.AbstractMessageAdapter as this abstract class implements much of the mundane methods needed by the org.mule.providers.UMOMessageAdapter . Methods to Implement
Method name
Description
Required
getPayload()
Returns the message payload 'as is'.
Yes
getPayloadAsString()
Returns a java.lang.String representation of the message payload.
Yes
getPayloadAsBytes()
Returns a byte[] representation of the message payload.
Yes
getUniqueId()
This ID is used by various routers when correlating messages. The superclass supplies a unique value by default, but this method can be overridden to provide an ID recognised by the underlying transport.
No
Service Descriptors A service descriptor is a file that contains a number of properties that describes how the internals of a transport provider is configured i.e. which Dispatcher factory to use or which endpoint builder to use. The service descriptor must be a file with the same name as the protocol of the transport stored in the META-INF directory, where protocol might be Jms, Http or File. META-INF/services/org/mule/providers/<protocol>.properties
The following describes each of the properties that can be set in a Transport service descriptor.
Property
Description
connector
The class name of the Connector Yes class to use. This must be an implementation of org.mule.umo.provider.UMOConnector.
connector.factory
The class name of the Connector No factory class to use when creating the connector instance. This can be used to gain greater control over the connector when it is created by Mule. This must be an implementation or org.mule.util.ObjectFactory and must return an implementation of org.mule.umo.provider.UMOConnector.
Document generated by Confluence on Apr 24, 2008 08:11
Required
Page 362
message.receiver
The class name of the Message No (if inbound only) Receiver class to use. This must be an implementation or org.mule.umo.provider.UMOMessageReceiver.
transacted.message.receiver
The class name of the No Transacted Message Receiver class to use. Some transports implement a transacted Message Receiver separately, in which case the MessageReceiver class can be specified here so Mule knows which receiver to use when creating endpoints that are transacted. This must be an implementation or org.mule.umo.provider.UMOMessageReceiver.
xa.transacted.message.receiver (Since Mule 1.4.2)
If the transport supports No XA transactions this is the class name of the XA Transacted Message Receiver implementation to use. Some transports implement a XA transacted Message Receiver separately, in which case the MessageReceiver class can be specified here so Mule knows which receiver to use when creating endpoints that are XA transacted. This must be an implementation of org.mule.umo.provider.UMOMessageReceiver.
dispatcher.factory
The class name of the No (if inbound only) Dispatcher factory class to use. This must be an implementation of org.mule.umo.provider.UMOMessageDispatcherFactory.
message.adapter
The Message adapter to use for No (if outbound only) this connector when receiving events. This is the class name of the Message Adapter to use which must implement org.mule.umo.providers.UMOMessageAdapter
stream.message.adapter
The Message adapter to use for No (if outbound only or if this connector when receiving streaming not supported) events that should be streamed. This is the class name of the Stream Message Adapter to use which must implement org.mule.umo.providers.UMOStreamMessageAdapter
inbound.transformer
The default transformer to use on inbound endpoints using this transport if no transform has been explicitly set on the endpoint. The property is the class name of a transformer that implements org.mule.umo.UMOTransformer.
Document generated by Confluence on Apr 24, 2008 08:11
No
Page 363
outbound.transformer
The default transformer to use on outbound endpoints using this transport if no transform has been explicitly set on the endpoint. The property is the class name of a transformer that implements org.mule.umo.UMOTransformer.
No
response.transformer
The default transformer to use on inbound endpoints using this transport if no transformer has been explicitly set for the response message flow in Request/Response style messaging. The property is the class name of a transformer that implements org.mule.umo.UMOTransformer.
No
endpoint.builder
The class name of the Yes endpoint builder used to build an UMOEndpointURI from an URI address. Mule provides a standard set of endpoint builders such as ResourceNameEndpointBuilder used by JMS and VM, SocketEndpointBuilder used by Tcp, http and Udp, UrlEndpointBuilder used by soap. Custom endpoint builders should extend org.mule.impl.endpoint.AbstractEndpointBuilder.
service.finder
Where a transport provider has more than one implementation (such as Soap which has Axis and Glue implementations), a service finder can be used to determine which implementation should be used when it hasn't been explicitly defined by the endpoint i.e. soap:http://... rather than axis:http://... Usually a service finder will check for a known class for each of the transport implementations and return the transport-specific name to use when creating the connector.
No
Coding Standards Package Structure All mule providers have a similar package structure. They follow the convention of org.mule.providers.<protocol>
Document generated by Confluence on Apr 24, 2008 08:11
Page 364
Where protocol is the protocol identifier of the transport such as 'tcp' or 'soap'. Any transformers and filters for the transport are stored either a 'transformers' or 'filters' package under the main package. Note that where a provider may have more than one implementation for a given protocol i.e. There are two Soap implementations in Mule, Axis and Glue, the package name to be used should be soap not axis or glue.
Internationalisation Any exceptions messages used in your transport provider implementation should be stored in a resource bundle so that they can be internationalised . The message bundle is a standard java properties file and must be located at META-INF/services/org/mule/i18n/<protocol>-messages.properties
Document generated by Confluence on Apr 24, 2008 08:11
Page 365
Transport Service Descriptors This page last changed on Jan 30, 2008 by ross.
A service descriptor is a file that contains a number of properties that describes how the internals of a transport provider is configured i.e. which Dispatcher factory to use or which endpoint builder to use. The service descriptor must be a file with the same name as the protocol of the transport stored in the META-INF directory, where protocol might be Jms, Http or File. META-INF/services/org/mule/providers/<protocol>.properties
The following describes each of the properties that can be set in a Transport service descriptor.
Property
Description
connector
The class name of the Connector Yes class to use. This must be an implementation of org.mule.umo.provider.UMOConnector.
connector.factory
The class name of the Connector No factory class to use when creating the connector instance. This can be used to gain greater control over the connector when it is created by Mule. This must be an implementation or org.mule.util.ObjectFactory and must return an implementation of org.mule.umo.provider.UMOConnector.
message.receiver
The class name of the Message No (if inbound only) Receiver class to use. This must be an implementation or org.mule.umo.provider.UMOMessageReceiver.
transacted.message.receiver
The class name of the No Transacted Message Receiver class to use. Some transports implement a transacted Message Receiver separately, in which case the MessageReceiver class can be specified here so Mule knows which receiver to use when creating endpoints that are transacted. This must be an implementation or org.mule.umo.provider.UMOMessageReceiver.
xa.transacted.message.receiver (Since Mule 1.4.2)
If the transport supports XA transactions this is the class name of the XA Transacted Message Receiver implementation to use. Some transports implement a XA transacted Message Receiver separately, in which case the MessageReceiver class can be specified here so Mule knows which receiver to use when creating endpoints that are XA transacted. This
Document generated by Confluence on Apr 24, 2008 08:11
Required
No
Page 366
must be an implementation of org.mule.umo.provider.UMOMessageReceiver. dispatcher.factory
The class name of the No (if inbound only) Dispatcher factory class to use. This must be an implementation of org.mule.umo.provider.UMOMessageDispatcherFactory.
message.adapter
The Message adapter to use for No (if outbound only) this connector when receiving events. This is the class name of the Message Adapter to use which must implement org.mule.umo.providers.UMOMessageAdapter
stream.message.adapter
The Message adapter to use for No (if outbound only or if this connector when receiving streaming not supported) events that should be streamed. This is the class name of the Stream Message Adapter to use which must implement org.mule.umo.providers.UMOStreamMessageAdapter
inbound.transformer
The default transformer to use on inbound endpoints using this transport if no transform has been explicitly set on the endpoint. The property is the class name of a transformer that implements org.mule.umo.UMOTransformer.
No
outbound.transformer
The default transformer to use on outbound endpoints using this transport if no transform has been explicitly set on the endpoint. The property is the class name of a transformer that implements org.mule.umo.UMOTransformer.
No
response.transformer
The default transformer to use on inbound endpoints using this transport if no transformer has been explicitly set for the response message flow in Request/Response style messaging. The property is the class name of a transformer that implements org.mule.umo.UMOTransformer.
No
endpoint.builder
The class name of the endpoint builder used to build an UMOEndpointURI from an URI address. Mule provides a standard set of endpoint builders such as ResourceNameEndpointBuilder used by JMS and VM, SocketEndpointBuilder used by Tcp, http and Udp, UrlEndpointBuilder used
Yes
Document generated by Confluence on Apr 24, 2008 08:11
Page 367
by soap. Custom endpoint builders should extend org.mule.impl.endpoint.AbstractEndpointBuilder. service.finder
Where a transport provider has more than one implementation (such as Soap which has Axis and Glue implementations), a service finder can be used to determine which implementation should be used when it hasn't been explicitly defined by the endpoint i.e. soap:http://... rather than axis:http://... Usually a service finder will check for a known class for each of the transport implementations and return the transport-specific name to use when creating the connector.
Document generated by Confluence on Apr 24, 2008 08:11
No
Page 368
XSLT Transformer This page last changed on Mar 07, 2008 by ross.
XSLT Transformer | Configuration | Configuration options | Example | Testing it
XSLT Transformer The XSLT Transformer gives users the ability to perform XSLT transformations on XML messages in Mule. This works in a very similar way to the XQuery Transformer on MuleForge.
Configuration To use the XSLT transformer you need to add it to your Mule XML configuration <properties> <map name="transformParameters"> <property name="title" value="#getProperty(message,'ListTitle')"/> <property name="rating" value="#getProperty(message,'ListRating')"/> <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 name="rating"> <xsl:value-of select="$rating"/> <xsl:apply-templates/> <xsl:template match="cd"> <xsl:element name="cd-title"> <xsl:value-of select = "title" /> ]]>
Here we are configuring a transformer using in-line XSLT expressions. We also define 2 transformParameters <map name="transformParameters"> <property name="title" value="#getProperty(message,'ListTitle')"/> <property name="rating" value="#getProperty(message,'ListRating')"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 369
These parameters are pulled from the current message and made available in the XSLT context so that they can be referenced in your XSLT statements. If a parameter is prefixed with '#' JXPath will be used to evaluate the expression, this also means you can execute XPath on Xml or Bean graph payloads.
Configuration options Name
Description
Required
xslt
The inline xslt script definition
No (if xsltFile is set)
xsltFile
A file that contains the XSLT script to execute with this transformer
No (if xslt is set)
transformParameters
A map of parameters to extract from the current message and make available in the XSLT context
No
xslTransformerFactory
The fully qualified class name of the javax.xml.TransformerFactory
Default JDK factory (TransformerFactory.newInstance())
uriResolver
The URI resolver to use when validating the XSL output (since 1.4.4-SNAPSHOT)
LocalUriResolver (reads from the classpath or file)
Example Now your configured XSLT transformer can be referenced by an endpoint. In the following example, you can drop and XML file into a directory on the local machine (see the inbound file endpoint) and the result will be written to System.out. The test data looks like Empire Burlesque <artist>Bob Dylan USA Columbia <price>10.90 1985 Hide your heart <artist>Bonnie Tyler UK CBS Records <price>9.90 1988
The result written to System.out will look like Empire Burlesque Hide your heart
The full configuration for this examples looks like -
Document generated by Confluence on Apr 24, 2008 08:11
Page 370
<mule-configuration id="xslt-test" version="1.0"> <properties> <map name="transformParameters"> <property name="title" value="#getProperty(message,'ListTitle')"/> <property name="rating" value="#getProperty(message,'ListRating')"/> <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 name="rating"> <xsl:value-of select="$rating"/> <xsl:apply-templates/> <xsl:template match="cd"> <xsl:element name="cd-title"> <xsl:value-of select = "title" /> ]]> <model name="main"> <mule-descriptor name="Echo" implementation="org.mule.components.simple.EchoComponent"> <endpoint address="vm://test.in" transformers="xslt" synchronous="true"/> <endpoint address="stream://System.out"/>
Testing it This can be tested using the following functional test public class XSLTFunctionalTestCase extends FunctionalTestCase { protected String getConfigResources()
Document generated by Confluence on Apr 24, 2008 08:11
Page 371
{ 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 UMOMessage message = client.send("vm://test.in", srcData, props); assertNotNull(message); assertNull(message.getExceptionPayload()); //Compare results assertTrue(XMLUnit.compareXML(message.getPayloadAsString(), resultData).similar()); } }
Document generated by Confluence on Apr 24, 2008 08:11
Page 372
Topologies This page last changed on Apr 19, 2008 by tcarlson.
Diagram below copied from http://www.getmule.com/mule_overview_flash1.php
Document generated by Confluence on Apr 24, 2008 08:11
Page 373
Profiling Mule with YourKit This page last changed on Apr 19, 2008 by tcarlson.
Mule Profiler Pack Starting with Mule 1.4.4 there's a dedicated Mule Profiler Pack featuring an easy-to-use integration with YourKit profiler. Until it's released, one can always grab it from the distribution area. Go to the downloads area and unfold that Other Links section. Just unpack it on top of the Mule installation and run Mule with -profile switch. Any extra YourKit startup optionscan be passed in as well, multiple parameters separated by commas, e.g. -profile onlylocal,onexit=memory. This integration pack will automatically take care of configuration differences for Java 1.4.x and 5.x/6.x.
Embedded Mule Nothing special about it, the configuration is completely delegated to the owning container. Launch YourKit Profiler, Tools -> Integrate with J2EE server... and follow simple instructions. Typically, a server's launch script is modified accordingly to support profiling and one has to use this modified start script instead of the original
Mule Standalone (all runtimes) Firsthand, any native YourKit libraries must be in your path. E.g. on Win32 that would be %YOURKIT_INSTALL_ROOT%\bin\win32 (replace the var with an actual value). Add the following line at the top of the mule launch script from $MULE_HOME/bin:
set PATH=c:\java\yourkit-6_0_15\bin\win32;%PATH% Next, follow the steps applicable to your Java runtime version below.
Mule Standalone (Java SE 1.4.x) Open the $MULE_HOME/conf/wrapper.conf file and locate a section with wrapper.java.additional.N values. Add YourKit's profiling agent (the actual value of N should be the next available in sequence):
wrapper.java.additional.4=-Xrunyjpagent:sessionname=Mule
Mule Standalone (Java SE 5.x and above) Java 5 and 6 introduced a new tool interface allowing much deeper insight into the running JVM. This provides for many profiling features not available before. Thus, a different agent is used with a slightly different syntax for specifying options.
wrapper.java.additional.4=-agentlib:yjpagent=sessionname=Mule
Document generated by Confluence on Apr 24, 2008 08:11
Page 374
Glossary This page last changed on Apr 19, 2008 by tcarlson.
This glossary tries to give a brief explanation of terms used within Mule. In addition to Mule specific terms the glossary also includes various descriptions revolving around integration and messaging concepts, e.g. SEDA or EIP. Please note that this glossary is constant work in progress and definitions may evolve over time. Whenever you feel there's a need for clarification of any Mule related term, feel free to add it to this list. ABCDEFGHIJKLMNOPQRSTUVWYXZ
Catch-All-Strategy A child element for the or elements. Allows Mule developer to configure a mechanism to "catch" any messages that are not handled by any of the configured routers. Typically required for situations where routers are selective routers, i.e., where they may not process a message that was consumed from the endpoint. More information can be found on the routers page.
Chaining Router An outbound router that is configured to send to two or more endpoints. It sends a synchronous message to the first endpoint and waits for a reply. This reply is routed to the second endpoint and its reply is routed to the next endpoint, etc. More information can be found on the routers page.
Channel ...
Communication Channel ...
Configuration Builder Class that knows how to parse a given configuration file - the default is the org.mule.config.MuleXmlConfigurationBuilder class that knows how to parse Mule's XML configuration. More information on the different types of configuration builders is available on the Configuration Overview page
Connector Connectors contain the logic of sending and receiving to an external system.
Connector Dispatcher ...
Correlation Event Resequencer ...
Document generated by Confluence on Apr 24, 2008 08:11
Page 375
Endpoint Endpoints are used to connect to components in the server and external systems or to each other locally or over the network. An Endpoint is a specific channel through which two parties can communicate. A provider can be used to send or receive events from disparate systems, for example, a purchasing component may receive an order request over Http. Once the order has been processed by the component a Jms message may be sent over a topic to notify an auditing system and response sent back over Http. For more detailed information see Endpoints.
EIP Common name referring to Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions, Gregor Hohpe & Bobby Woolf; Addison-Wesley 2003
Exception Based Router ...
Filter ...
Global Endpoint An Endpoint is considered to have Global scope when it is registered on the MuleManager instance or set in the Mule configuration as a .
Inbound Router ...
Interceptor Interceptors are used to intercept message flow into a service component. Mule interceptors are useful for attaching common behavior to multiple UMOs. Typical interceptors are loggers, profilers, or permissions checkers.
Local Endpoint These are endpoints that are configured or set on the objects that have Endpoints, but are not registered with the MuleManager.
Message Context ...
Message Filter ...
Message Payload The actual data of a message. See also Mule Message.
Message Router See Router
Document generated by Confluence on Apr 24, 2008 08:11
Page 376
Mule Mule is an ESB (Enterprise Service Bus) and integration platform. It can be thought of as a lightweight messaging framework and highly distributable object broker that can seamlessly handle interactions with other applications using disparate technologies such as JMS, Http, Email, and Xml-RPC. The Mule framework provides a highly scalable environment in which you can deploy your business components. Mule manages all the interactions between components transparently whether they exist in the same VM or over the Internet, and regardless of the underlying transport used. Mule was designed around the ESB (Enterprise Service Bus) enterprise integration pattern, which stipulates that different components or applications communicate through a common messaging bus, usually implemented using JMS or some other messaging server.
Mule Configuration ...
Mule Event An event message can be any kind of message in the messaging system. Event notification is used to coordinate actions among applications. A Mule Event actually references a Mule Message. The difference between a Mule Event and Mule Message (the payload really) is a matter of timing and content. An event's timing is very important whereas e.g. guaranteed delivery is important to content. ...
MuleForge ...
MuleHQ ...
Mule Instance ...
Mule Manager Service ...
Mule Message A message carrying a Message Payload and a set of properties that are associated with the processing of the message. The UMOMessage object represents a message in Mule. See also Mule Event.
Mule Model Container See Service Container
MuleSource ...
Document generated by Confluence on Apr 24, 2008 08:11
Page 377
Outbound Router ...
Placeholder ...
Property ...
Protocol ...
Provider See Transport Provider
Response Router ...
Router Routers are used to control how messages are sent and received by components in the system. Mule supports 3 classes of routers: • Inbound Routers that apply to messages as they are received. • Outbound Routers that are invoked when a message is being dispatched. • Response Routers that join forked tasks in a request response call. Routers can be nested and configured to filter messages. For details also see routers.
SEDA In SEDA, applications consist of a network of event-driven stages connected by explicit queues. This architecture allows services to be well-conditioned to load, preventing resources from being overcommitted when demand exceeds service capacity. SEDA is a design pattern for high throughput, massively scalable architectures. For more information see the SEDA homepage. Also, this article makes a good introduction.
Service Component A Service Component is a POJO running under Mule, which exposes the POJO to external entities as a service. It is also known as a Universal Message Object (UMO) within Mule.
Service Container Or Mule Model Container
Service Manager ...
Document generated by Confluence on Apr 24, 2008 08:11
Page 378
Transformer Transformers are used to transform message payloads to and from different types. Mule supports chaining of transformers. This allows to have reusable and fine-grained transformers that may be linked together to provide required functionality.
Transport ...
Transport Element See Transport Provider
Transport Provider Aka Provider or Transport Element. A Transport Provider is in fact a composite of a set of objects used to connect and communicate with the underlying system. The elements of a Transport Provider are • • • •
Connector, is responsible for connecting to the underlying system Message Receiver, is used to receive events from the system. Connector Dispatchers, are responsible for passing data to the system. Transformers are Transport specific transformers used to convert data received and data sent.
For more details see also Transport Elements
UMO See Service Component
Universal Message Object See Service Component
Wire Tap A router which forwards copies of messages to another endpoint. It can either forward a copy of all messages that it receives or it can be configured to use a filter and send a sub-set of these messages only. This router will not prevent messages from being delivered to service components. See also Interceptor.
Document generated by Confluence on Apr 24, 2008 08:11
Page 379
Tools This page last changed on Apr 18, 2008 by tcarlson.
These are the various tools that help develop, document or test Mule applications. Mule IDE - A set of Eclipse plugins for configuing and testing Mule applications MULEUSER:Benchmark - A simple command-line benchmarking tool for Mule Config Visualizer - A great little tool for generating a visual diagram of your Mule configuration Transport Archetype - A Maven archetype that creates a set of commented template classes for a new transport • Transport Archetype for Mule 2.0 - A more advanced Archetype for creating a template project for a Mule 2.0 transport. • Project Archetype - A Maven archetype for creating a Mule project. A project can be stand alone, and example project or module. • • • •
Document generated by Confluence on Apr 24, 2008 08:11
Page 380
Config Visualizer This page last changed on Apr 18, 2008 by tcarlson.
Note: the visualizer is bundled in Mule 1.4.2+, instructions below apply if building from the source. The Mule Configuration Visualizer is a great tool for generating Configuration graphs from Mule Xml. Take a look at some samples -
Mule Configuration Graphs (view as slideshow)
Loan Broker ESB Config
Loan Broker Sync Config
Voip Service Config
Hello Http Config
Error Handler Config
Echo Mule Config
Document generated by Confluence on Apr 24, 2008 08:11
Page 381
Running the tool Prerequisites You need Java 1.4 and Maven 2.0.6 to build the code and subversion (svn) to check out the source. Checkout the trunk using svn checkout https://svn.codehaus.org/mule/trunk trunk
Install Graphiz, a graph visualization software from http://www.graphviz.org. A binary is included for Windows. On Unix machines install Graphviz separately and add it to the standard PATH. It should then be used automatically. Alternatively, see "exec" option.
Building In the visualizer directory, build the project cd trunk/mule/tools/visualizer mvn compile
Running Running from Console The visualizer can be run as a command line application. Command line provide a few options that you can specify:
Option
Description
Default
Required
-files
A comma-separated list of Mule configuration files
-outputdir
The directory to write the generated graphs to.
Defaults to the current directory
No
-exec
The executable file used for Graph generation.
./win32/dot.exe
No
-caption
Default caption for the generated graphs.
Defaults to the 'id' attribute in the config file
No
-?
Displays usage help
Yes
No
Take note that, if you run the Mule visualizer command at any directory (instead of running it in $MULE_HOME/bin ) you need to specify the -exec option, e.g. set MULE_GRAPHVIZ=$MULE_HOME/lib/native/visualizer/dot.exe visualizer -files updater-config.xml -exec $MULE_GRAPHVIZ
Otherwise, please provide the full/relative path to the $MULE_HOME directory when you specify the configuration file location: $MULE_HOME/bin> visualizer -files C:/mule-config.xml
Please refer to README.txt in the distribution for more details.
Document generated by Confluence on Apr 24, 2008 08:11
Page 382
Options Options are specified inside the pom.
Option
Description
Default
Required
files
A list of Mule configuration files
exec
The executable file used for Graph generation
./win32/dot.exe for Windows, which dot for Unix
No
workingdir
The prefix path for output
target
No
outputdir
The directory to write the generated graphs to
outputfile
The name of the file to output
Input filename + '.gif'
No
caption
Default caption for the generated graphs
'id' attribute in the config file
No
mappings
The path to a mappings file (see below)
keepdotfiles
Keep temporary files
?
No
combinefiles
Whether to include all files in a single diagram
false
No
urls
?
?
No
config
?
?
No
templateprops
?
?
No
showall
Forces all other show parameters to true
false
No
showconnectors
Include connectors in the plot
true
No
showmodels
?
false
No
showconfig
?
false
No
showagents
?
false
No
showtransformers
?
false
No
Yes
No
No
Combining Files Combining files can be really useful for getting the 'big picture' of your Mule Application as you can combine Mule node configurations from many different machines.
Document generated by Confluence on Apr 24, 2008 08:11
Page 383
Mappings Mappings are used to make a logical connection between objects on the graph when there is no relationship configured in the Mule Xml. These logical Mappings are only required when the routing path between components is not explicitly defined i.e. dynamic routing. Mappings are defined as key/value pairs in a .properties file where the key 'maps' to the value in the diagram. These values use the object names as represented on the output graph so you can define relationships between component, endpoints, routers or any other object. An example mapping might be where a replyTo endpoint is set on a message and Mule handles the routing from the replyTo to the next component. Using the Loan Broker as an example, the replyTo endpoints for the Banks would be mapped as Bank1=LoanBrokerQuotes Bank2=LoanBrokerQuotes Bank3=LoanBrokerQuotes Bank4=LoanBrokerQuotes Bank5=LoanBrokerQuotes
When using dynamic routers such as the receipient List you may want to define the possible routes from the router to the endpoints i.e. LenderService.org.mule.routing.outbound.StaticRecipientList=Bank1,Bank2,Bank3,Bank4,Bank5
This says, from the StaticRecipientList router on the LenderService, map to each of the Bank endpoints.
Mapping Duplicate Endpoints Sometimes and inbound endpoint is not expressed in the same way as an outbound endpoint. This is the case for Soap endpoints where the outbound endpoint has a method param, but inbound endpoint Soap endpoint doesn't. You can logically map these two endpoints so that they appear as one on the graph, i.e. CreditAgencyReceiver.equals=CreditAgency
Note the 'equals' extension tells the Config Graph that the two objects are equivilent. Once you map the two endpoints you'll probably want to hide one of them...
Hiding Nodes To hide a node you add the following entry to the mapping file CreditAgencyReceiver.hide=true
Tips It's a good practice to use Endpoint Identifiers in your Mule Xml to map physical endpoints to logical names. This helps when configuring mappings for the Config Grapher and these logical names can be used in the mappings instead of the physical names.
Document generated by Confluence on Apr 24, 2008 08:11
Page 384
Mule IDE This page last changed on Apr 18, 2008 by tcarlson.
The Mule IDE is now hosted on MuleForge: http://www.muleforge.org/projects/IDE
Document generated by Confluence on Apr 24, 2008 08:11
Page 385
Mule Project Wizard This page last changed on Apr 18, 2008 by tcarlson.
The Mule project wizards are based on Maven Archetypes that are code templates that can get you up and running with a mule project complete with a set of implementation notes and 'todo' pointers. The Mule Project archetype enables users to generate a tailored boilerplate project in seconds. • Mule Project Archetype 2.x - Generate a Module, example or stand alone project for Mule.
Document generated by Confluence on Apr 24, 2008 08:11
Page 386
Project Archetype This page last changed on Apr 18, 2008 by tcarlson.
Following the instructions below will create template files, including all the necessary Java boilerplate and detailed implementation instructions in comments, for a new Mule project. The Mule project archetype is publicly available from the central maven repo.
Configuring Maven Edit the file settings.xml (usually in $HOME/.m2) so that Maven will allow you to execute Mule plugins. <settings> ... org.mule.tools ...
CodeHaus plug-in Repository You need to have the CodeHaus plug in repository accessible for Maven, to do this just add the following declarations to your settings file above. Later you can activate the codehaus profile using -Pcodehaus. Unfortunately, this approach does not work. See http://jira.codehaus.org/browse/MNG-3099 for a lengthy discussion on the progress <settings> ... <profiles> <profile> codehaus codehaus.org CodeHaus Snapshots http://snapshots.repository.codehaus.org <enabled>false <snapshots> <enabled>true codehaus.org CodeHaus Plugin Snapshots http://snapshots.repository.codehaus.org <enabled>false <snapshots> <enabled>true ...
Document generated by Confluence on Apr 24, 2008 08:11
Page 387
Move to wherever you want to place you code. > cd yourDir
Next you will execute archetype and generate the code. This will ask various questions and then generate the files. You need to pass in two system parameters -
artifactId
The short name for the project (i.e. 'myApp' or 'java6-extensions')
muleVersion
The version of the Mule project archetype you want to use. This will also be the default Mule version used for the generated artefact.
Note that this plug-in can be used without user prompts. For a full list of arguments that can be passed in. See MULE:Command Line Options. Note you also need to use the codehaus profile. The command looks like the following (all on one line) > mvn -Pcodehaus mule-project-archetype:create -DartifactId=xxx -DmuleVersion=2.0.0-RC1-SNAPSHOT
Next you'll be asked a number of questions about the Mule project you are creating. These may vary according to the options you select. An example of the output is shown below.
The Questions Explained • • • • • • •
MULE:Provide a description of what the project/module does MULE:Which version of Mule is this project/module targeted at? MULE:Will This project be hosted on MuleForge? MULE:Will This transport have a custom schema for configuring the project in Xml? MULE:What is the base Java package path for this module? (i.e. org/mule/modules) MULE:What type of project is this? MULE:Will This project need to make objects available in the Registry as soon as it's loaded?
Provide a description of what the transport does: You should provide an accurate description of the transport with any high level details of what you can or cannot do with it. This text will be used where a description of the project is required.
Which version of Mule is this transport targeted at? The version of Mule you want to use for your transport. By default this will default to the Archetype version passed in on the command line.
Will This project be hosted on MuleForge? If the transport is going to be hosted on MuleForge, then additional information will be added to your project for linking to its issue tracker, web site, build server and deployment information.
Will This transport have a custom schema for configuring the transport in Xml? It's recommended that all new transports targeted for Mule 2.0 should define an Xml schema that defines how the transport is configured. If you do not use this option, users will have to use generic configuration to use your transport.
Document generated by Confluence on Apr 24, 2008 08:11
Page 388
What is the base Java package path for this module? This should be a java package path for you project i.e. org/mule/modules/foo. Note that you must use slashes not dots.
What type of project is this? Specifies the type of project that will be created. Typically, the project structure will remain the same for each project type, but the POM configuration may change to inherit from a different parent POM.
Will This project need to make objects available in the Registry as soon as it's loaded? The registry bootstrap is a properties file that specifies class names of simple objects that can be made available in the Mule Registry as soon as the module is loaded. This is useful for registering custom transformers or property extractors. The custom option allows you to deviate from the existing endpoint styles and parse your own.
Example console output [INFO] description: ******************************************************************************** Provide a description of what the project does: [default:] ******************************************************************************** [INFO] muleVersion: ******************************************************************************** Which version of Mule is this module targeted at? [default: 2.0.0-RC1-SNAPSHOT] ******************************************************************************** [INFO] packagePath: ******************************************************************************** What is the base Java package path for this module? (i.e. org/mule/modules or org/mule/examples): [default: org/mule/applications] ******************************************************************************** [INFO] forgeProject: ******************************************************************************** Will This project be hosted on MuleForge? [y] or [n] [default: y] ******************************************************************************** [INFO] projectType: ******************************************************************************** What type of project is this? - [s]tand alone project - [e]xample project that may be hosted on the MuleForge or in the Mule distribution - [m]ule module to be hosted on the MuleForge on in the Mule distribution
Document generated by Confluence on Apr 24, 2008 08:11
Page 389
[default: s] ******************************************************************************** [INFO] hasCustomSchema: ******************************************************************************** Will This project have a custom schema for configuring the module in Xml? [default: n] ******************************************************************************** [INFO] hasBootstrap: ******************************************************************************** Will This project need to make objects available in the Registry as soon as it's loaded? [default: n] ********************************************************************************
Command Line Options By default this plug in runs in interactive mode, but it's possible to run it in 'silent' mode by using
-Dinteractive=false The following options can be passed in -
Name
Example
Default Value
artifactId
-DartifactId=mule-module-xxx
mule-application-<artifactId>
description
-Ddescription="some text"
none
muleVersion
-DmuleVersion2.0.0-RC1SNAPSHOT
none
hasCustomSchema
-DhasCustomSchema=true
true
hasBootstrap
-DhasBootstrap=true
false
projectType
-DprojectType=e
s (stand alone)
packagePath
-DpackagePath=org/mule/ modules/xxx
org/mule/application/ <artifactId>
forgeProject
-DforgeProject=true
true
version
-Dversion=1.0-SNAPSHOT
<muleVersion>
groupId
org.mule.application.<artifactId> DgroupId=org.mule.applicationxxx
basedir
-Dbasedir=/projects/mule/tools
Document generated by Confluence on Apr 24, 2008 08:11
<current dir>
Page 390
Transport Archetype This page last changed on Apr 18, 2008 by tcarlson.
The Mule code wizards are based on Maven Archetypes that are code templates that can get you up and running with a mule project complete with a set of implementation notes and todo pointers. The Mule transport archetype enables users to generate a tailored boilerplate transport project in seconds. Following the instructions below will create template files, including all the necessary Java boilerplate and detailed implementation instructions in comments, for a new transport. The transport archetype is publicly available from the central maven repo.
Adding BobberPlus to Maven Edit the file settings.xml (usually in $HOME/.m2) so that Maven will find the BobberPlus plugin. <settings> ... org.mule.tools ...
Generating the Template Move to wherever you want to place you code (if you want to integrate with an existing maven project - the standard Mule transport directory can also be downloaded with svn - then you need to modify the pom to have an appropriate "parent", and add the module to the parent's pom). > cd yourDir
Create the archetype. This will ask various questions and then generate the files (the "\" in the command below indicate that it is all on one line) > mvn bobberplus:create -DarchetypeGroupId=org.mule.tools \ -DarchetypeArtifactId=mule-transport-archetype -DarchetypeVersion=1.4.1-SNAPSHOT \ -DgroupId=yourGroupId -DartifactId=yourArtifactId -Dversion=yourVersion [INFO] Scanning for projects... [...lots of output snipped...] [INFO] Please enter the values for the following archetype variables: [INFO] MuleVersion: ******************************************************************************** Which version of Mule are you working with? [default: 1.4] ******************************************************************************** 1.4.1-SNAPSHOT [INFO] TransportName: ******************************************************************************** The protocol name to use for the transport (lower case) i.e. jms or http [default: myTransport] ******************************************************************************** foo [INFO] TransportDescription: ******************************************************************************** Provide a description of what the transport does: [default: ] ******************************************************************************** Stuff. Lots of stuff.
Document generated by Confluence on Apr 24, 2008 08:11
Page 391
[INFO] Receiver: ******************************************************************************** Can the transport receive inbound requests? [y] or [n] [default: y] ******************************************************************************** y [INFO] PollingMessageReceiver: ******************************************************************************** Does the Message Receiver need to poll the underlying resource? [y] or [n] [default: n] ******************************************************************************** y [INFO] Streaming: ******************************************************************************** Does this transport support Streaming? [y] or [n] [default: n] ******************************************************************************** y [INFO] InboundTransformer: ******************************************************************************** If this transport will have a default inbound transformer, enter the name of the transformer? (i.e. JmsMessageToObject) [default: n] ******************************************************************************** FooMessageToObject [INFO] Dispatcher: ******************************************************************************** Can the transport dispatch outbound requests? [default: y] ******************************************************************************** y [INFO] OutboundTransformer: ******************************************************************************** If this transport will have a default outbound transformer, enter the name of the transformer? (i.e. ObjectToJmsMessage) [default: n] ******************************************************************************** ObjectToFooMessage [INFO] Transactions: ******************************************************************************** Does this transport support transactions? [y] or [n] [default: n] ******************************************************************************** y [INFO] CustomTransactions: ******************************************************************************** Does this transport use a non-JTA Transaction manager? [y] or [n] (i.e. needs to wrap proprietary transaction management) [default: n] ******************************************************************************** y [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)
Document generated by Confluence on Apr 24, 2008 08:11
Page 392
- [c]ustom - parse your own [default: r] ******************************************************************************** c [INFO] ---------------------------------------------------------------------------[INFO] Using following parameters for creating Archetype: mule-transport-archetype:1.0-SNAPSHOT [INFO] ---------------------------------------------------------------------------[INFO] Parameter: packagePath = yourGroupId [INFO] Parameter: Receiver = y [INFO] Parameter: Dispatcher = y [INFO] Parameter: InboundTransformer = FooMessageToObject [INFO] Parameter: MuleVersion = 1.4.1-SNAPSHOT [INFO] Parameter: TransportName = foo [INFO] Parameter: CustomTransactions = y [INFO] Parameter: version = yourVersion [INFO] Parameter: Transactions = y [INFO] Parameter: groupId = yourGroupId [INFO] Parameter: PollingMessageReceiver = y [INFO] Parameter: EndpointBuilder = c [INFO] Parameter: packageName = yourGroupId [INFO] Parameter: Streaming = y [INFO] Parameter: OutboundTransformer = ObjectToFooMessage [INFO] Parameter: basedir = /home/andrew/projects/mule/trunk/mule-sandbox/transports [INFO] Parameter: package = yourGroupId [INFO] Parameter: TransportDescription = Stuff. Lots of stuff. [INFO] Parameter: artifactId = yourArtifactId [...lots of output snipped...]
Document generated by Confluence on Apr 24, 2008 08:11
Page 393
Implementation Guide This page last changed on Apr 18, 2008 by tcarlson.
User Guide 1. Using Mule • Mule Distributions • MULEINTRO:Embedding Mule in a Java Application • MULEINTRO:Embedding Mule in a Webapp
2. Making Mule Production-Ready 3. Mule Security 4. Mule Client 5. Mule Agent 6. Administration Tools • Mule IDE • Benchmark • Config Visualizer
7. Mule Best Practices 8. MULECB:Home
Document generated by Confluence on Apr 24, 2008 08:11
Page 394
Configure Maven Plugins This page last changed on Apr 18, 2008 by tcarlson.
Configuring Maven Edit the file settings.xml (usually in $HOME/.m2) so that Maven will allow you to execute Mule plugins. <settings> ... org.mule.tools ...
CodeHaus plug-in Repository You need to have the CodeHaus plug in repository accessible for Maven, to do this just add the following declarations to your settings file above. Later you can activate the codehaus profile using -Pcodehaus. Unfortunately, this approach does not work. See http://jira.codehaus.org/browse/MNG-3099 for a lengthy discussion on the progress <settings> ... <profiles> <profile> codehaus codehaus.org CodeHaus Snapshots http://snapshots.repository.codehaus.org <enabled>false <snapshots> <enabled>true codehaus.org CodeHaus Plugin Snapshots http://snapshots.repository.codehaus.org <enabled>false <snapshots> <enabled>true ...
Document generated by Confluence on Apr 24, 2008 08:11
Page 395
Programmers Guide This page last changed on Apr 18, 2008 by tcarlson.
Mule Programmers Guide This page is currently under construction and is incomplete and some of the links do not work yet.
Introduction The aim of this guide is to provide a practical approach for developing with Mule. It will describe the steps involved in setting up Mule application and best practices.
Prerequisites This guide assumes you have an understanding of the core concepts of Mule, ESBs, and J2EE. If you are not yet familiar with Mule see the Getting Started Guide.
The Programming Model To best understand the programming model and which bits you need write it helps to understand the different elements involved when processing messages and which of them you can control. Cannot resolve external resource into attachment.
Inbound Message Flow Stage Inbound message flow is triggered by data being received by a transport (such as a record being written to a DB or data written to a socket). The Mule transport provider is responsible for receiving this data and wrapping into a Mule Message. The Inbound router is responsible for applying routing logic to the inbound Message, such as Idem potency, re-sequencing, batching, etc. MuleMessage Construction The MuleMessage is constructed by taking the body of the received data as the payload and any message headers and meta information (such as Filename in the File Transport). For example the Content-Type of a Http request can be read using – MuleMessage.getStringProperty("Content-Type", null) or a JMS header such as JMSPriority can be read using - MuleMessage.getIntProperty("JMSPriority") If the underlying transport supports attachments (such as SOAP and Mail) these will be added to the MuleMessage attachments.
Endpoint The Endpoint is used to receive messages from a transport. An endpoint is a configuration object that defines how data will be received and transformed by Mule. On the Endpoint you can configure the endpoint address, transport-specific configuration information, transactions and filters. For more information see Mule Endpoints.
Inbound Router Inbound Routers control the inbound flow of events to a component and can re-sequence, aggregate or filter incoming messages. For example the IdempotentReceiver will reject any inbound messages that
Document generated by Confluence on Apr 24, 2008 08:11
Page 396
have already been received. The CorrelationResequencer will 'hold' a number of correlated events and hand them to the component in the correct order (based on the order they were dispatched).
Element
Customisation
Coding Required
Endpoint (Inbound)
An endpoint is a configuration of a Mule transport. To introduce a new endpoint means to introduce a new transport. There is a guide to writing mule transports here. You can also customise the behaviour of an existing transport to change the way messages are received or dispatched. For more information about doing this see General Transport Configuration.
Writing your own transports is the most labour-intensive customisation in Mule. However, Most of the work is done for you with Abstract classes leaving template methods where the transport-specific code should be written.
Inbound Router
Mule provides a number of standard Inbound Routers that can be used without any customisation. The only reason customisation is necessary is when custom logic is required to do things like aggregate a set of events.
Only the routers such as the CorrelationAggregator need customisation in order to plug in logic to aggregate many events into one event.
Component Flow Stage Component flow starts when the MuleMessage is passed to the Model (Service container). Here the message will be passed to your Service object, but before that Interceptors and transformers can be invoked as part the inbound Message flow.
Interceptor (pre) Interceptors are used to intercept message flow into your service component. They can be used trigger monitor/events or interrupt the flow of the message i.e. an authorisation interceptor could ensure that the current request has the correct credentials to invoke the service.
Inbound Transformer Inbound transformers are used to transform the inbound message from the underlying transport format to something that the Service Component needs. Transformers can be chained together and should be used for data-level transforms i.e. from one data-type/format to another. Complex Transformations Advanced transformations where access to external data sources is required such as enrichment or lookup data it is recommended that a Service Component is introduced to perform this task rather than using a Transformer object is used for simpler data marshaling.
Service Invocation The service is the business logic. It can be a POJO, EJB, Remote Object or any other type of object. The Service component can be instantiated by the mule Model or it can be created by or stored in another container such as Spring, Hivemind, JNDI, Pico or Plexus.
Document generated by Confluence on Apr 24, 2008 08:11
Page 397
Invoking the Service Todo Implementing the Callable interface For more information see the Writing Components chapter.
Interceptor (post) If an interceptor configured on the Service is an Envelope Interceptor (it extends [org.mule.interceptors.EnvelopeInterceptor]) The after() method will be called allowing developers to hook in behaviour once the component has finished processing.
Element
Customisation
Coding Required
Interceptor (pre)
Can be used to introduce cross-cutting behaviour for components such as authorisation.
A single method interface to implement [org.mule.umo.UMOInterceptor].
Inbound Transformer
Transformers are used to transform the message payload from one data format to another. Transformers can be chained together so that fine-grained transformers can be reused. Mule provides a number of transformers for XML and XSLT as well as transformers for standard java types . Transports are required to provide transformers for converting to and from underlying data formats.
There is an [AbstractTransformer] that all transformers should extend. This provides a single abstract method doTransform(...) that must be implemented. There is also an [AbstractEventAwareTransformer] that will also get passed the current UMOEventContext for the message flow.
Service Invocation
This is where the service object actually gets invoked. It can be a POJO, EJB, Remote object or objects instantiated by a container such as Spring or Hivemind.
This object has to be written by the developer and can be as simple or complex as the service requires. The service object itself need not have any reliance or knowledge about mule. Service Components should be stateless or manage any state in a shared data repository, unless the component is not running [concurrently].
Interceptor (post)
Used to introduce any crosscutting behaviour after the service component has executed.
Developers need to extend the [EnvelopeInterceptor] and implement any logic in the after() method.
Outbound Flow Stage The Outbound message flow starts one the result message (output from a Service Invocation) is passed on from the Service. If there is no result message or no Outbound Router configured this stage is skipped.
Document generated by Confluence on Apr 24, 2008 08:11
Page 398
Outbound Router The Outbound Router is responsible for controlling how and where the message goes next. Mule defines a number of standard Outbound Routers including all those listed in the excellent Enterprise Integration Pattern Book plus some other routing patterns that we have seen. Outbound Routers allow for Contentbased, Itinerary (routing slip), Dynamic and Header-based routing or a combination of these. Mule has standard routers for MessageSplitting, Multicasting and content-based routers.
Outbound Transformer TODO Endpoint (outbound) Note that there can be zero or more endpoints that the event gets dispatched on depending on the Outbound Router logic. TODO
Element
Customisation
Coding Required
Outbound Router Outbound Transformer Endpoint (Outbound)
Messages and Events TODO
The UMOEventContext TODO
Document generated by Confluence on Apr 24, 2008 08:11
Page 399
Transformations and Mule Best Practices This page last changed on Apr 15, 2008 by tcarlson.
Mule Best Practices for Transformations * Note: this is the start of a discussion between support and our customers around the area of Best Practices - work in progress. If you feel differently about this, please contribute your ideas and suggestions. Inevitably, Mule users and customers ask us - "How should I handle a given transformation?" or "Where should I do this transformation in my ESB event flow?". With Mule's flexibility, you may be wondering what the "recommended" way to handle a given problem. Mule has a rather efficient transformation mechanism. Transformers are applied on to inbound or outbound endpoints and the data is transformed before it gets to the component (or before it gets sent). Transformers can be easily concatenated so it is simple to perform multiple transformations on in-flight data. More information is available here: Transformers If you research ESB concepts on the web, there is no general consensus as to how/where transformations should occur in an ESB. Some maintain that since transformations are not business decisions (that is to say, since a transformation should always be applied on inbound/outbound data), then the transformation should be available as part of the ESB [MULE:1]. This matches the concepts of Aspect Oriented Programming (AOP). Others conclude that it is far more efficient to encode the transformation logic into the business components themselves. [MULE:2] In the second case however, there is no distinction between code that is related to a business process and code that is generic enough to be reused which goes against the philosophy of an ESB. While there is no industry best practise, we recommend that developers examine their transformation logic to see if it will always be used (AOP) or if it is specific to a business process. If the former, then this is a transformation. If the latter, then this should be part of the service component. References: [MULE:1] - http://msdn2.microsoft.com/en-us/library/aa480061.aspx [MULE:2] - http://blogs.ittoolbox.com/eai/applications/archives/transformation-in-a-soa-12186
Document generated by Confluence on Apr 24, 2008 08:11
Page 400
Architecture Guide This page last changed on Apr 15, 2008 by tcarlson.
Many of Mule's features are documented here using the same terms as the popular Enterprise Integration Patterns book. The book describes the problems Mule aims to solve and documents many of the patterns used in the Mule framework. EIP documentation in this guide and other Mule guides will be in the form of -
EIP - (pattern name) (book pattern no.) (the pattern url on the EIP site) (pattern image) (short description) "Quote from the website/book"
Introduction This document aims to give an insight to the architecture of Mule. Mule's ultimate goal is to provide a unified method of interacting with data from disparate sources without encumbering the developer with the details about how the data is sent or received or the protocols involved. The result is an ESB (Enterprise Service Bus) server that is highly-scalable, light-weight, fast and simple to pick up and start using. Mule was architected with the ESB model in mind and its primary focus is to simply and speed up the process of developing distributed service networks. However, as the name suggests, the ESB model is usually associated with large integration projects where there are an array of disparate enterprise applications. Mule makes Enterprise level service architectures possible for smaller projects where resources, development cost and TTM need to be kept to a minimum.
Architecture Overview The primary goal is to enable integration between applications using standards, open protocols and welldefined patterns. To achieve this goal, Mule defines a set of components that can be used to perform most of the hard work necessary to get disparate applications and services talking together. Cannot resolve external resource into attachment. This diagram shows a simple end-to-end topology of how Mule components fit together.
Application The Application can be of any type, such as a web application, back office system, application server or another Mule instance.
Channel Can be any method of communicating data between two points. Channels are used in Mule to wire UMO components together as well as to wire different Mule nodes together across a local network or the internet.
EIP - Message Channel (60) http://www.eaipatterns.com/MessageChannel.html Cannot resolve external resource into attachment. Mule doesn't implement or mandate any particular channels though Mule does provide many channel options known as Transport providers. "When an application has information to communicate, it doesn't just fling the information into the messaging system, it adds the information to a particular Message Channel. An application receiving information doesn't just pick it up at random from the messaging system; it retrieves the information from a particular Message Channel."
Document generated by Confluence on Apr 24, 2008 08:11
Page 401
Message Receiver A Message Receiver is used to read or receive data from the Application. In Mule a Receiver is just one element of a Transport provider and Mule provides many transports such as JMS, SOAP, HTTP, TCP, XMPP, SMTP, file, etc. Much of the 'magic' in Mule is it's ability to communicate to disparate systems without your business logic (UMO components) ever needing to know about system location, format of the data, the delivery mechanism or protocols involved. Likewise when the UMO component has done its work, it need not worry about where the data is going next or in what format the data is expected.
EIP - Message Endpoint (95) http://www.eaipatterns.com/TransactionalClient.html Cannot resolve external resource into attachment. Mule manages all delivery of data to and from endpoints transparently. "Message Endpoint code is custom to both the application and the messaging system's client API. The rest of the application knows little about message formats, messaging channels, or any of the other details of communicating with other applications via messaging. It just knows that it has a request or piece of data to send to another application, or is expecting those from another application. It is the messaging endpoint code that takes that command or data, makes it into a message, and sends it on a particular messaging channel. It is the endpoint that receives a message, extracts the contents, and gives them to the application in a meaningful way."
Inbound Router Inbound routers are used to control how and which events are received by a component subscribing on a channel. Inbound routers can be used to filter, split aggregate and re-sequence events before they are received by the UMO component. There is more information on Message Routers further on in this guide.
Connector The connector understands how to send and receive data over a particular channel. A Message receiver is coupled with a connector to register interest in data coming from a source understood by the connector. There is more information on connectors further on in this guide.
Transformers Transformers are used to transform message or event payloads to and from different types. Mule does not define a standard message format (though Mule may support standard business process definition message types in future) Transformation provided out of the box is Type transformation, such as JMS Message to Object and standard XML transformers. Data transformation is very subjective to the application and Mule provides a simple yet powerful transformation framework. There is more information on transformers further on in this guide.
Endpoint An endpoint is really a configuration wrapper that binds a connector, endpoint URI, transformers, filters and transactional information to provide a Channel Adapter. The provider also stores transactional information for the provider instance. See the Mule Endpointschapter that goes into more detail about endpoints.
EIP - Channel Adapter (127) http://www.eaipatterns.com/ChannelAdapter.html Cannot resolve external resource into attachment. A provider is equivalent to a Channel Adapter.
Document generated by Confluence on Apr 24, 2008 08:11
Page 402
"The adapter acts as a messaging client to the messaging system and invokes application functions via an application-supplied interface. Likewise, the Channel Adapter can listen to Application-internal events and invoke the messaging system in response to these events."
Outbound Router Outbound routers are used to publish messages/events to different providers depending on different aspects of events or other rules defined in configuration. There is more information on MEssage Routers further on in this guide.
Mule Manager Core to Mule is the MuleManager. It manages the configuration of all core services for the Model and the components it manages. Below is an overview of the core components that comprise a Mule manager. Cannot resolve external resource into attachment. The following sections go in to more detail for each of these elements in Mule.
The Model The model encapsulates and manages the runtime behavior of a Mule Server instance. It is responsible for maintaining the UMO's instances and their configuration. The Model has 3 control mechanisms to determine how Mule interacts with it's UMO components -
Entry Point Resolver Defined by the org.mule.umo.model.UMOEntryPointResolver interface, an entry point resolver is used to determine what method to invoke on an UMO component when an event is received for its consumption. There is a DynamicEntryPointResolver that is used if no other is configured on the model (see the Configuration Guide for more information). The DynamicEntryPointResolver provides entry point resolution for common usage, the steps it takes are 1. Checks to see if the component implements the Callable life cycle interface, in which case, the onCall(UMOEventContext) method will be used to receive the event. 2. If the component has a transformer configured for it, the return type for the transformer will be matched against methods on the component to see if there is a method that accepts the transformer return type. If so this event will be used. Note if there is more than one match, an exception will be thrown. 3. If there is a method on the component that accepts an org.mule.umo.UMOEventContext . If so this event will be used. Note if there is more than one match, an exception will be thrown. 4. The last check determines if there are any methods on the component that accept a java.util.Event . If so this event will be used. Note if there is more than one match, an exception will be thrown. 5. If none of the above find a match an exception will be thrown and the component registration will fail. Of course there are many scenarios where the DynamicEntryPointResolver is suitable. For example, if you are migrating from another framework you may want to restrict (such as org.mule.model.CallableEntryPointResolver that only accepts components that extend org.mule.umo.lifecycle.Callable ) or change the way the entry point is resolved. To implement a custom Entry Point Resolver the org.mule.model.EntryPointResolver must be implemented.
Lifecycle Adapter Defined by the org.mule.umo.lifecycle.UMOLifecycleAdapter interface, the lifecycle adapter is responsible for mapping the mule component lifecycle to the underlying component. The DefaultLifecycleAdapter simply delegates life cycle events to the component where the component implements zero or more UMO lifecycle interfaces.
Document generated by Confluence on Apr 24, 2008 08:11
Page 403
Clearly this isn't suitable for existing components that you want to be managed by Mule, as they will most likely have their own lifecycle methods that will still need to be invoked in the Mule framework. Luckily, the org.mule.umo.lifecycle.LifecycleAdapter is very simple to implement. Lifecycle adapters are configured using an implementation of org.mule.umo.lifecycle.UMOLifecycleAdapterFactory. The factory is declared in the configuration of the model. A default is provided DefaultLifecycleAdapterFactory.
Component Pool Factory The Component Pool factory property of the model defines the factory to use when creating a component pool for a given UMO Component. The pool is used to pool UMOComponents and this extension point allows developers to use their own pooling mechanism if needed. Mule ships with two Pooling implementations • commons-pool - this uses Jakarta commons-pool to manage the pooling of UMOComponents. • pico-pool - this is a Pico extras component that manages object pooling using picoContainer. Developers wishing to roll their own pooling implementation need to implement org.mule.umo.model.UMOPoolFactory, org.mule.until.ObjectPool and org.mule.util.ObjectFactory.
Transport Providers A transport provider is a Mule plug-in that enables Mule components to send and receive information over a particular protocol, repository messaging or other technology. The following describes the architecture of a transport provider. Cannot resolve external resource into attachment.
Connectors The connector provides the implementation for connecting to the external system. The connector is responsible for sending data to the external receiver and managing the listener on the connector to receive data from the external system. For example, the Http connector creates a Http Connection and sends the payload over the connection and will return a UMOEvent with the return status (if running synchronously). Receivers for the Http connector are simply objects that get notified when something is received on the Http server port. A connector has two objects responsible sending and receiving events • MessageReceiver - Used to listen on an endpoint to the underlying technology. The receiver is usually quite dumb with all configuration performed in the connector and the receiver is just a listening thread. • MessageDispatcher - Is used to dispatch events to the underlying technology. Message Dispatchers are poolable threads that can be used to dispatch events or perform a 'receive' on the underlying technology to retrieve an available event if there is one. The UMOMessageDespatcher interface defines 3 important methods ° dispatch() - sends data to the external system asynchronously. ° send() - sends data to the external system synchronously and returns any response from the external system as a UMOEvent. ° recieve() - will request an event from the underlying technology and returns the result. This method has a timeout parameter. Connectors are responsible for managing sessions for the underlying technology, i.e. the JmsConnector provides a JMS Session for the Connectors' Message Receiver and one also for the Message Dispatcher to publish or send events over Jms.
Endpoints Address An endpoint address defines any form of destination or source of data and is always expressed as URI. Examples of endpoints could be -
Document generated by Confluence on Apr 24, 2008 08:11
Page 404
transport
Description
Example
POP3/SMTP
usually username password and a hostname
pop3:// user:[email protected]
JMS
A name of a topic or queue
jms://topic:myTopic
HTTP
A host and possibly a port, path and query string
http://mycompany.com/mule
File
The path of a directory or file
file:///tmp/data/in
VM
The name of another UMO component runnig in the same VM
vm://MyUMO
SOAP
The location of UMO component exposed as a service or a service location to invoke
axis:http://mycompany.com/ mule/services/MyUMO
Endpoint addresses are always expressed as valid URIs with the protocol of the connector then resource specific information. Mule Transport providers have pluggable endpoint builders that allow developers to customize the way an endpoint is read by Mule.
Endpoint Resolution This section describes the process Mule uses to resolve an endpointUri. For this example we will use the following URI 'jms://topic:myTopic?durable=true'. This a JMS URI to a durable topic. 1. 2. 3. 4.
The ConnectorFactory is invoked with the URI. It will look in META-INF/services/org/mule/providers for a service descriptor that matches 'jms'. From this a ConnectorServiceDescriptor object is created. You can specify on the Endpoint URI whether to create a new Connector for the URI or use an existing connection. When there is no instruction an existing connection will be looked up based on protocol. 5. The ConnectorServiceDescriptor contains the Endpoint builder to use and the Endpoint is passed into the endpoint builder. 6. It is then up to the endpoint builder to decompose the URI into its component parts according to the URI specification.
Message Receivers Message receivers or message listeners are responsible for receiving data from the external system. It is the responsibility of the connector to manage the registering and unregistering of receivers. The complexity of the message receiver will vary depending on the external system being used. For example, the message receiver for the JMS provider simply implements the javax.jms.MessageListener and the JMS connector registers the listener with its JMS connection. However, the Http message receiver implements an Http server that listens on a specified port for incoming requests.
Message Adapters Message adapters are required to read disparate data objects in the format they are received from the external application in a common way. The UMOMessageAdapter interface specifies a small set of methods needed to read the payload and properties of any Java object. Message Adapters are specific to a connector; when a connector is written a Message Adapter is also needed to read or translate data from a particular data type used by the connector into either a byte array or string.
Document generated by Confluence on Apr 24, 2008 08:11
Page 405
Transactions Transactions are managed at the Provider; Transactions are begun or committed when a Message Receiver receives a message or a Message Dispatcher sends the message. Central to Mule's transaction Management is the TransactionCoordinator, which is responsible maintaining transaction state. For more information about transactions in Mule see the Transaction Management chapter of the User Guide. In order for Mule to treat all transactions the same way there is a small API that transacted enabled providers must define • org.mule.umo.UMOTransaction - A wrapper around the underlying transaction. Some systems do not explicitly define a transaction object, instead, transaction demarcation may be achieved by calling methods on a connection or session. The UMOTransaction API defines a set of methods that can be used to interrogate any transactional resource. • org.mule.umo.UMOTransactionFactory - A factory used to create an implementation of UMOTransaction.
Container Contexts The component resolver is the gateway to using an external container framework to manage the instantiation and configuration of UMO components or their dependent objects. Mule doesn't provide it's own component container as there is a wealth of very good IoC containers that are tried and tested. Instead Mule provides some default Component Resolvers for popular containers • Spring Component Resolver - see the Spring Framework. For more information about Mule / Spring integration see the Spring chapter of the user guide. • Pico Component Resolver - see the PicoContainer. To use a component from an external container as your UMO component simply configure the desired ComponentResolver on the model and when defining the mule-descriptor in the configuration file , set the implementation attribute to the component key (or class in the case of picocontainer) in the container. If the configuration does not specify a Component Resolver the MuleComponentResolver is used. This implementation expects a class name to instantiate instead of a component key to resolve the component with. It behaves in the same way as real implementations except it does not support looking up components from a container. To implement a custom ComponentResolver two interfaces need to be implemented • org.mule.umo.model.UMOComponentResolver - This does the actual resolving of components from the container. • org.mule.umo.model.UMOContainerContext - This is responsible for creating and initializing the container. The Component Resolver will query the external framework through this context.
UMO Components Central to the architecture of Mule are single autonomous components that can interact without being bounded by the source, transport or delivery of data. These components are called UMO Components and can be arranged to work with one another in various ways. These components can be configured to accept data a number of different sources and can send data back to these sources. Cannot resolve external resource into attachment. The 'UMO Impl' specified above actually refers to an Object. This object can be anything, a JavaBean or component from another framework. This is your client code that actually does something with the events received. Mule does not place any restrictions on your object except that if configured by the Mule directly, it must have a default constructor (if configured via Spring or Pico, Mule imposes no conventions on the objects it manages). Obviously, with this sort of flexibility, Mule needs to know a bit more about your object. It is the job of the outer two layers shown to control how events are utilized by your Object.
Document generated by Confluence on Apr 24, 2008 08:11
Page 406
Component Lifecycle The lifecycle adapter is used by the Model to fire lifecycle methods on your object (if any). Custom lifecycles can be introduced on a per-model basis allowing different models to management the lifecycle of their components in different ways. Mule defines a default lifecycle for the components it manages. The components can participate in none, any or all of these lifecycle events by implementing the required lifecycle interfaces. The lifecycle is as follows - Cannot resolve external resource into attachment. Components managed by Mule do not need to follow the Mule defined lifecycle. Using the DefaultLifecycleAdapter a component can implement any of the lifecycle interfaces • org.mule.umo.lifecycle.Initialisable - Will add an initialise() method to the component. • org.mule.umo.lifecycle.Startable - Will add a start() method to the component where your component can execute any code to put itself in a state ready to receive events. • org.mule.umo.lifecycle.Callable - Will add an onCall(UMOEventContext eventContext) method to the component. This method will be called when an event is received for the component. • org.mule.umo.lifecycle.Stoppable - Will add stop() method to the component where your component can put itself in a stoped state. Note that the component should be in such a state that it can be started again. • org.mule.umo.lifecycle.Disposable - Will add a dispose() method to the component where it can do any final tidying up before it is disposed. These lifecycle interfaces also apply to Connectors, Agenets and Interceptors. For example the LifecycleInterceptor implements the Startable, Stoppable and Disposable interfaces to manage it's lifecycle.
Transformers Transformers are used to convert source data to an object type required by the UMO Component. Transformers can be configured on Endpoints that receive data to ensure that the expected object type is always received by an UMO Component. Transformers configured on an Outbound endpoint ensure that the endpoint receives the the correct object type before dispatching the event. Multiple transformers can be chained together to allow for finer grained transformer implementations that are easier to reuse. To configure an Endpoint to use more than one transformer, just specify a space separated list of transformers in the config file or programmatically chain the transformers together using the setTransformer() method on the transformer. For example an inbound transformer may look like Cannot resolve external resource into attachment. And an outbound transformer might look like Cannot resolve external resource into attachment. All Mule transformers must implement org.mule.transformer.UMOTransformer. There is an abstract transformer implementation that defines methods for controlling the object types this transformer supports and validates the expected return type, leaving the developer to implement a single doTransform() method.
Entrypoint Resolvers Also (not shown on this digram) is the EntryPointResolver. This is used by the Model when the UMOComponent is registered to find the method to call on your object when an event is received for it. If a method is not found an exception will be thrown. The details of the EntryPoint resolver can be seen here.
Events Mule is an event-based architecture, that is, actions within a Mule network are triggered by either events occurring in Mule or in external systems. Events always contain some sort of data, the payload, which will be used and/or manipulated by one or more components and a set of properties that are associated to the processing of the event. These properties are arbitrary and can be set at any time from when the
Document generated by Confluence on Apr 24, 2008 08:11
Page 407
event is created. The data in the event can be accessed in its original state or in its transformed state. The event will use the transformer associated with the Endpoint that received the event to transform its payload into a format that the receiving component understands. For more information about the event lifecycle see the Message Flow section below.
Event Processing Mule can send and receive events using 3 processing models 1. Asynchronously - Many events can be processed by the same component at a time in different threads. When the Mule server is running asynchronously instances of a component run in different threads all accepting incoming events, though the event will only be processed by one instance of the component. 2. Synchronously - When a UMO Component receives an event in this mode the the whole request is executed in a single thread 3. Request-Response - This allows for a UMO Component to make a specific request for an event and wait for a specified time to get a response back. You can control the synchronicity of event processing by setting the synchronous property on the endpoint (or programmatically on the event). Synchronicity of the call can be propagated across the network where the transports being used support a reply channel. For example, a synchronous JMS request will establish a temporary reply queue when a request is made and will wait for a response on that queue. The same applies to socket based transports. The actual event flow is governed by the synchronous property, whether the endpoint is inbound or outbound and if there is a transaction in progress. The following rules apply.
Asynchronous Event Processing Asynchronous event processing occurs when the inbound endpoint synchronous flag is set to false. Asynchronous inbound and outbound Cannot resolve external resource into attachment. In this scenario the message is dispatched to a queue and is consumed by a worker thread in a pool that actually does the execution work of your UMOComponent. The outbound endpoint is also asynchronous the resulting message will be dispatched by a dispatcher thread. Asynchronous inbound, synchronous outbound Cannot resolve external resource into attachment. In this scenario the message is dispatched to a queue and is consumed by a worker thread in a pool that actually does the execution work of you UMOComponent. The outbound endpoint is synchronous so the dispatch happens in the same thread as component execution. This scenario is used by outbound transactions so that all dispatches from the component occur in the same thread. This behavior is handled automatically by Mule.
Synchronous Processing Synchronous inbound only Cannot resolve external resource into attachment. An event is received and processed by your UMOComponent in the same thread and any result is returned from your UMO component will be passed back to the receiver where if there is a response channel, i.e Socket outputstream a result will be sent. Synchronous inbound and outbound Cannot resolve external resource into attachment.
Document generated by Confluence on Apr 24, 2008 08:11
Page 408
An event is received and processed in the same thread. The outbound dispatch also happens in the receiver thread. Here if the outbound endpoint transport being used supports a reply channel such as sockets or JMS a response from the dispatch will be intercepted (or the wait will timeout) and that response is passed back to the receiver where if there is a response channel, i.e Socket outputstream a result will be sent. Synchronous inbound and outbound with transaction Cannot resolve external resource into attachment. Transactions can only (currently) be managed over synchronous endpoints. Thus if an endpoint has been configured for transactions it will automatically be synchronous. When dispatching and a transaction is in progress the dispatch will also happen in the current thread.
Message Routers Message routers are used to control how events are sent and received by components in the system. Mule defines Inbound routers that apply to events as they are received and outbound routers that are invoked when an event is being dispatched.
EIP - Message Router (78) http://www.eaipatterns.com/MessageAdapter.html Cannot resolve external resource into attachment. Mule provides extensible routers to control how messages are dispatched. "a Message Router ... consumes a Message from one Message Channel and republishes it to a different Message Channel channel depending on a set of conditions."
Inbound Routers Inbound routers can be used to control and manipulate events received by a component. Typically, an inbound router can be used to filter incoming event, aggregate a set of incoming events or re-sequence events when they are received. You can chain inbound routers together, in this scenario each router is matched before the event is dispatched to a Mule component. Inbound routers are different to outbound routers in that the provider is already known so the purpose of the router is to control how messages are sent via the provider. You can specify a catch-all strategy which will be invoked if any of the routers do not accept the current event. An Inbound Router can be configured on a mule-descriptor element in the mule-config.xml
If there are no special processing requirements for messages received by a component there is no need to configure an inbound router.
Outbound Routers Outbound routers are used to control which providers are used to send events once an UMO component has finished processing. Message Routers are configured on UMOCompnent and allow the developer to define multiple routing constraints for any given Event. You can specify a catch-all strategy which will be
Document generated by Confluence on Apr 24, 2008 08:11
Page 409
invoked if none of the routes accept the current event. An example of an Outbound Message Router is given below
Catch All Strategy The catch all strategy receives the event if none of the router accept the event. Custom strategies must implement org.mule.umo.routing.UMORoutingCatchAllStrategy which defines a method public void catchMessage(UMOMessage message, UMOSession session, boolean synchronous) throws RoutingException;
Note that this a void method, so that no return event can be passed back to the calling code. This is important when running synchronously as the synchronous chain of events is broken. It is considered an error condition when a catch-all strategy is invoked.
Routers In the example, there are 2 routers defined, with the outbound-router element as the parent. This means that each router will be checked in order to see if the current event can be routed. It is not recommended to use transacted providers in router configurations. As routing of the event is determined at run-time, there are situations where an event within a transaction is routed to a nontransacted provider, thus orphaning the current transaction causing 'surprise' transaction timeouts. For transacted providers it is recommended that you configure one inbound and one outbound transacted provider for the event path. In situations where only one outbound provider is configured for an UMO component it is not necessary to define a Message router. For more information about using the routers that ship with Mule, see the Message Routers chapter of the Home.
Interceptors Mule interceptors are useful for attaching common behavior to multiple UMOs. The Interceptor or Command pattern is often referred to as practical AOP (Aspect Oriented Programming) as it allows the developer to intercept processing on an object and potentially alter the processing and outcome. Interceptors a very useful for attaching profiling, permission and security checks, etc, to a component in Mule. Mule has two types of interceptors 1. org.mule.interceptors.EnvelopeInterceptor - Envelope filter that will execute before and after the event is processed. Good for Logging and profiling.
Document generated by Confluence on Apr 24, 2008 08:11
Page 410
2. org.mule.umo.UMOInterceptor - Simply gets invoked then forwards processing to the next element. An interceptor can stop further processing by not forwarding control to the next interceptor, for example as permissions checker interceptor. The following shows a typical interceptor stack and the event flow. Cannot resolve external resource into attachment.
Exception Management Exception strategies can be defined on UMOComponents, but sometimes it's sufficient to have all components managed by the the model tp use the same exception strategy. By defining the exception strategy on the model, it is not necessary to define individual exception strategies (by default if no exception strategy is defined on a UMO Component the org.mule.impl.DefaultExceptionStrategy will be used). It is common to define your own exception strategy, to do so you must implement org.mule.umo.UMOExceptionStrategy.
Document generated by Confluence on Apr 24, 2008 08:11
Page 411
MULE_SERVICE_METHOD This page last changed on Apr 15, 2008 by tcarlson.
MULE_SERVICE_METHOD Mule's entry point resolver class (based upon org.mule.umo.model.UMOEntryPointResolver) works its way through its priority scheme to be able to figure out what entry point to use. This allows Mule to dynamically use a different entry point depending on the payload of the inbound message. Other entry point resolver classes can also be used if the DynamicEntryPointResolver is not sufficient for your needs. The only drawback to the default mechanism is the fact that if two methods have the same type of parameters, Mule obviously cannot decide which of the methods to use and raises a TooManySatisfiableMethods exception. In such cases, you can easily implement the Callable interface in your component and direct the message to the correct method. However, this is not always a feasible solution; perhaps you do not have access to the source code of your service component or perhaps you do not want to make your component "Mule-aware". The work around to this would be to have a wrapper component that can direct the message for you but this just adds another level of abstraction that you may not want either. Besides, this is all routing logic so why should we put this into a service component? Let us illustrate this with a simple example - If we have two components called "A" and "B" that communicate synchronously using the VM channel called "vm://Communication". Let us assume that "A" is the producer of string messages and "B" consumes these messages. However, "B" has more than one method that accepts strings.
What we need is a routing mechanism that allows us to select which method to use. We need to be able to specify a number of methods within our configuration that can be used directly and therefore bypass the entry point resolver logic. What we really need is the ability to specify a different endpoint for each of the methods; i.e, to be able to route along a particular channel but control which part of the consumer will actually be invoked. Mule has such a property for the endpoints - the MULE_SERVICE_METHOD property that needs to be configured on both the inbound and outbound endpoints. Component "A" would have the following outbound router configured: <endpoint address="vm://Communication?method=Method1"/>
Here, the endpoint is defined as it usually is but has a "method" property which we have set to "Method1". We therefore want the result of this service component to be sent along the VM channel called "Communication" and passed along to the method called "Method1" Component "B" would have the following inbound router configured:
Document generated by Confluence on Apr 24, 2008 08:11
Page 412
<mule-descriptor name="ComponentB" implementation="org.foo.ComponentB"> <endpoint address="vm://Communication"/> <properties> <property name="MULE_SERVICE_METHOD" value="Method1"/> <property name="MULE_SERVICE_METHOD" value="Method2"/> <property name="MULE_SERVICE_METHOD" value="Method3"/> <property name="MULE_SERVICE_METHOD" value="Method4"/>
Note that the configuration of the inbound router and the inbound endpoint is the same as it usually is. The difference is the addition of the properties on the Mule descriptor. We can therefore route a message along a channel for a specific method as long as the methods are defined as properties on the mule-descriptor. This allows us to bypass the entry point resolver logic and control which method to invoke in case of multiple methods having the same parameters.
Pitfalls Here, the Mule configuration is tightly coupled with the implementation of your component. If the component changes and the methods are renamed, you will need to adjust your configuration accordingly.
Restrictions This will only work on synchronous paradigms. This will currently not work if your processing is asynchronous due to an issue with threading.
Filtering Of course, we still need to figure out what criteria to look out for before routing using this mechanism. If "B" has any number of methods, we still need to figure out which method is the correct one for each message. If we take a simple content based example, the criteria would be contained within the payload itself. In such a situation, the Mule configuration would look like this: <mule-descriptor name="CompA" implementation="org.foo.ComponentA"> <endpoint address="vm://inFromSource"/> <endpoint address="vm://Communication?method=Method1"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 413
<endpoint address="vm://Communication?method=Method2"/> <endpoint address="vm://Communication?method=Method3"/> <endpoint address="vm://Communication?method=Method4"/> <mule-descriptor name="ComponentB" implementation="org.foo.ComponentB"> <endpoint address="vm://Communication"/> <properties> <property name="MULE_SERVICE_METHOD" value="Method1"/> <property name="MULE_SERVICE_METHOD" value="Method2"/> <property name="MULE_SERVICE_METHOD" value="Method3"/> <property name="MULE_SERVICE_METHOD" value="Method4"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 414
MULE and Oracle SOA BPEL Integration This page last changed on Jan 30, 2008 by ross.
This cookbook contains various examples on how to invoke Oracle SOA BPEL engine from Mule and how to invoke services hosted on Mule from BPEL engine. Although these examples are based on the Oracle BPEL Engine, they demonstrate how Mule can be integrated with any BPEL engine via standard SOAP endpoints (web services) and JMS. • How to invoke Oracle SOA BPEL engine from Mule using Web Services — A Mule configuration that demonstrates how to invoke Oracle SOA BPEL engine using Web Services • How to invoke Oracle SOA BPEL from Mule Using JMS connector — A Mule configuration file that demonstrates how to invoke an Oracle BPEL process using Jms connector • How to invoke services hosted on Mule from SOA BPEL process — Demonstrates how to invoke services hosted on Mule from SOA BPEL engine
Document generated by Confluence on Apr 24, 2008 08:11
Page 415
How to invoke Oracle SOA BPEL engine from Mule using Web Services This page last changed on Jan 30, 2008 by ross.
A Mule configuration that demonstrates how to invoke Oracle SOA BPEL engine using Web Services Following example is tested against Oracle SOA Suite 10g Release 3 (10.1.3.1.0). Oracle SOA comes with several sample processes. CreditRatingService a bpel process that receives a social security number and returns credit rating. Following is the picture of the process.
CreditRatingService bpel is located under \bpel\samples\utils\CreditRatingService.This process needs to be deployed either using admin console or simply typing "ant" in the process directory. Following is a Mule configuration file to invoke this process using xfire endpoint. Notice that the input, social security number, is given from commandline. The result of process invocation, credit score, is converted to xml string and displayed on the console. <mule-configuration id="WS.MuleToOracleSOA" version="1.0"> <model name="mule2orabpel"> <mule-descriptor name="MuleToOracleSOABridge" implementation="org.mule.components.simple.BridgeComponent"> <endpoint address="stream://System.in?promptMessage=SSN:" />
Document generated by Confluence on Apr 24, 2008 08:11
Page 416
<endpoint address='wsdl-xfire:http://192.168.0.3:8888/orabpel/default/CreditRatingService/1.0? WSDL&method=process'/> <endpoint address="stream://System.out" transformers="DocToXml"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 417
How to invoke Oracle SOA BPEL from Mule Using JMS connector This page last changed on Jan 30, 2008 by ross.
A Mule configuration file that demonstrates how to invoke an Oracle BPEL process using Jms connector Following example is tested usingOracle SOA Suite 10g Release 3 (10.1.3.1.0). Oracle SOA comes with several sample processes. Queue2Topic a bpel process that receives an xml instance of expense record on a queue and publishes it to a topic. Following is the snapshot of the process:
Queue2Topic bpel is located under \bpel\samples\tutorials\123.JmsAdapter \Queue2Topic. This process needs to be deployed either using admin console or simply typing "ant" in the process directory. Following is a Mule configuration file to invoke this process using Jms connnector. Notice thatjms/ demoQueue is Jndi name of the receiving queue. jms/QueueConnectionFactory is the jndi name of theQueueConnectionFactory. The input, expense record, is given from commandline as xml string. sample input: Expense Record: <ExpenseRecord xmlns="http://xmlns.oracle.com/pcbpel/samples/expense"> <EmpId>111 - PC
1 1149.99 <mule-configuration id="JMS.MuleToOracleSOA" version="1.0">
Document generated by Confluence on Apr 24, 2008 08:11
Page 418
<properties> <property name="specification" value="1.0.2b" /> <property name="jndiDestinations" value="true" /> <property name="forceJndiDestinations" value="true" /> <property name="connectionFactoryJndiName" value="jms/QueueConnectionFactory" /> <property name="jndiInitialFactory" value="com.evermind.server.rmi.RMIInitialContextFactory" /> <property name="jndiProviderUrl" value="opmn:ormi://127.0.0.1:6003:home/orabpel" /> <map name="jndiProviderProperties"> <property name="java.naming.security.principal" value="oc4jadmin"/> <property name="java.naming.security.credentials" value="welcome1"/> <property name="username" value="oc4jadmin"/> <property name="password" value="welcome1"/> <model name="mule2orabpel"> <mule-descriptor name="MuleToOracleSOA" implementation="org.mule.components.simple.BridgeComponent"> <endpoint address="stream://System.in?promptMessage=Expense Record:" /> <endpoint address="jms://jms/demoQueue" /> <endpoint address="stream://System.out" transformers="DocToXml"/>
Document generated by Confluence on Apr 24, 2008 08:11
Page 419
How to invoke services hosted on Mule from SOA BPEL process This page last changed on Jan 30, 2008 by ross.
Demonstrates how to invoke services hosted on Mule from SOA BPEL engine Following example is tested against Oracle SOA Suite 10g Release 3 (10.1.3.1.0). In order to invoke a web service on Mule, the WSDL file for the service needs to copied to a local directory. For example, the configuration file for a HelloWorld service deployed on mule is given below. <mule-configuration id="MuleHelloWorldService" version="1.0"> <model name="oraclews"> <mule-descriptor name="helloWorld" implementation="org.mule.samples.hello.HelloWorld"> <endpoint address="axis:http://localhost:81/services" />
The Java code that that implements the logic of this web service is given below: package org.mule.samples.hello; //interface: Defined in IHelloWorld.java public interface IHelloWorld { public String sayHello(String src); } //implementation: Defined in HelloWorld.java public class HelloWorld implements IHelloWorld{ public String sayHello(String src){ return "Hello " + src; } }
In order to get WSDL file for this service, open a browser and enter url "http://:81/ services/helloWorld?WSDL". Save this file to a local directory where Oracle SOA is installed. Following is a simple Oracle process that receives a string as input. Using the input string, it invokes the Mule service using web service call.
Document generated by Confluence on Apr 24, 2008 08:11
Page 420
Using JDeveloper add a partner link by pointing to the WSDL file. Oracle automatically creates partner roles as seen in following picture.
Document generated by Confluence on Apr 24, 2008 08:11
Page 421
Create a link to partner using appropriate message and method call as seen in the following picture.
In order to invoke the process, go to BPEL console using a browser and invoke the process.
Document generated by Confluence on Apr 24, 2008 08:11
Page 422
JavaSpaces This page last changed on Feb 19, 2008 by ross.
The JavaSpaces module for Mule is now hosted at MuleForge. You can go directly to the project here.
Document generated by Confluence on Apr 24, 2008 08:11
Page 423