Beruflich Dokumente
Kultur Dokumente
#140
Get More Refcardz! Visit refcardz.com
Mule 3:
CONTENTS INCLUDE:
n
About Mule
n
Mule XML
n
Messages
Simplifying SOA
n
Connectivity
n
Modules
n
Hot Tips and more...
By John D’Emic
• Connector definitions.
ABOUT MULE
• Global configuration elements like endpoints,
transformers and notification listeners.
Mule is the world’s most widely used open-source integration
platform and Enterprise Services Bus (ESB). Mule is designed to • Flows, patterns and services.
support high-performance, multi-protocol transactions between Flows
heterogeneous systems and services. It provides the basis Flows, new to Mule 3, provide a free-form method of
for service-oriented architecture. It is lightweight and can run orchestrating message processing in Mule. A flow consists of a
standalone or embedded directly in your application. message source, typically an inbound-endpoint, followed by a
sequence of message processors.
This Refcard covers the use of Mule 3. If you are a new user, it will
serve as a handy reference when building your integration flows
in Mule. If you are an existing user, especially of Mule 2, it will
help ease your transition into using Mule 3.
MULE XML
<jms:connector name=”jmsConnector”
connectionFactory-ref=”connectionFactory”
username=”guest”
password=”guest”/>
<simple-service name=”random-number-service”
address=”http://localhost:8080/rest”
component-class=”com.mulesoft.refcard.
RandomNumberResource”
type=”jax-rs”/>
</mule>
Sending a JMS Message with a Flow MULE_CORRELATION_ The order of a correlation group.
SEQUENCE
Sending a JMS message is easy with a flow. Here’s how you can
use a flow to read files from a directory and send their payload to MULE_SESSION A property that holds encoded session data.
a JMS queue. Scopes
<flow name=”File to JMS Message”>
Properties are scoped differently depending on when they’re
<file:inbound-endpoint path=”data/files”> set or accessed during message processing. The following table
<byte-array-to-string-transformer/>
</file:inbound-endpoint> contains the available scopes.
<jms:outbound-endpoint queue=”output”/>
</flow>
Scope Description
The file:inbound-endpoint will read files from the given path, inbound Set by message sources, typically an inbound-endpoint.
transforming their contents into Strings. The content is then outbound Any properties in this scope will get attached to an outbound
passed as JMS TextMessages to the “output” queue. or response message. Properties set by the message-
properties-transformer default to the outbound scope.
Using Patterns session Properties in the session scope are available between flows and
Mule Configuration Patterns, extending the Enterprise services without explicit propagation.
Integration Patterns, encapsulate common integration paradigms invocation Used internally by Mule and lasts only for an invocation of a
in a compact configuration format. flow or service.
<simple-service name=”random-number-service” Mule connects to over 100 applications, protocols and APIs. Mule
address=”http://localhost:8080/rest”
componentclass=”org.refcard.RandomNumberResource”
endpoints enable connectivity to protocols such as JMS, HTTP
type=”jax-rs”/> and JDBC. Cloud Connectors enable connectivity to applications
and social media like SalesForce and Twitter.
In this case, we are using the simple-service pattern to expose
a JAX-RS resource that returns a random number from an HTTP Endpoints
GET request. Messages can be received with an inbound endpoint and sent
with an outbound endpoint. Inbound and outbound endpoints
Flows and patterns now supersede services, are configured using the XML namespace prefix of the transport.
which were the predominant integration paradigm Connectors
Hot in Mule 2. While services will always be supported,
Tip you should favor flows and patterns for new
A connector is used to configure connection properties for an
endpoint. Most endpoints don’t require a connector. However,
applications. some (like JDBC or JMS) do require connector configuration, as
we’ll see below.
MESSAGES Configuring an SMTP connector
The following example illustrates how an SMTP connector is
Messages encapsulate data entering and leaving Mule. The configured.
content of a message is called its payload. The payload is
<smtp:connector name=”smtpConnector”
typically a Serializable Java class, an InputStream or an array fromAddress=”user@foo.com”
of bytes. bccAddresses=”admins@foo.com”
subject=”A Message from Mule” />
Attachments
A message can have zero or more mime attachments in addition
to the payload. These can be used to associate files, documents
and images with the message.
The following table describes some common endpoints supplied JSON JSON support, including marshalling, transformation and
filtering.
by Mule.
CXF SOAP support via Apache CXF.
Endpoint Description Jersey JAX-RS support for publishing RESTful services.
http://[host]:[port]:[path]?[query] Send and receive data over HTTP. Scripting Support for JSR-223 compliant scripting language, like Groovy
ajax://[channel] Pub / Sub to browser apps using or Rhino.
CometD. XML XML support, including XML marshalling, XPath and XSLT support.
file://[path] Read and write files.
The full list of available modules is available in the official Mule
ftp://[user]@[host]:[port]/[path] Read and write files over FTP or SFTP.
documentation. Additional modules are available on MuleForge.
jms://[type]:[destination]?[options] Full support for JMS topics and queues.
smtp://[user]@[host]:[port] Send email over SMTP.
Hot Use MuleForge.org to locate community-written
imap://[user]@[host]:[port]/[folder] Receive email via IMAP. Tip extensions.
jdbc://[sql query] Send and receive data from a SQL
database.
vm://[path] Uses memory-based queues to send
Bridging REST to SOAP
between services and flows. The following demonstrates how the CXF module can be used to
bridge a RESTful service to a SOAP service.
The full list of transports is available in the Mule documentation.
<flow name=”HTTP to SOAP Bridge”>
Use exchange patterns to define how a message is <http:inbound-endpoint host=”localhost” port=”8080”
path=”service”/>
recieved by an endpoint. For endpoints that generate <cxf:jaxws-client
Hot a response(synchronous) use the request-response, clientClass=”com.mulesoft.refcard.FooService”
Tip for asynchronous endpoints use the one-way
wsdlLocation=”classpath:/wsdl/hello_world.wsdl”
operation=”greetMe”/>
</flow>
exchange pattern.
The inbound-endpoint accepts HTTP POST requests to
Cloud Connectors http://localhost:8080/service. The POST data is then sent to the
Cloud connectors enable easy access to SaaS, social media and SOAP service defined by the CXF jaxws-client.
infrastructure services such as Amazon WS and Facebook. Routers
These connectors can be used anywhere in a flow to invoke a Routers implement the Enterprise Integration patterns (EIP) and
remote service. A cloud connector usually has a ‘config’ element determine how messages are directed in a flow.
where service credentials are set and then one or more elements The following table contains commonly used routers.
that invoke service methods. The following demonstrates how the
Twitter cloud connector can be used to post a tweet: Router Description
all Sends the message to each endpoint.
curl –-data “status=go mule!” http://localhost
<twitter:config name=”twitter” format=”JSON” choice Sends the message to the first endpoint that matches.
consumerKey=”${twitter.consumer.key}”
consumerSecret=”${twitter.consumer.secret}” recipient-list Sends the message to all endpoints in the expression
oauthToken=”${twitter.access.token}” evaluated with the given evaluator.
oauthTokenSecret=”${twitter.access.secret}” />
round-robin Each message received by the router is sent to alternating
<flow name=”updateStatusFlow”>
endpoints.
<http:inbound-endpoint host=”localhost” port=”80”/>
<twitter:update-status wire-tap Sends a copy of the message to the supplied endpoint
status=”#[header:INBOUND:status]”/>
</flow>
then passes the original message to the next processor in
the chain.
We can now post a tweet to the inbound-endpoint with curl: first-successful Sends the message to the first endpoint that doesn’t throw
an exception or evaluates the failureExpression to true.
curl –-data “status=go mule!” http://localhost
splitter Will split the current message into parts using an
Polling expression or just split elements of a List.
Mule has a poll tag that allows data from a remote service to be aggregator Will collect related messages and create a message
collection.
received periodically. To get updates from a Twitter timeline:
<flow name=”getStatusFlow”>
Transformers
<poll> Transformers modify the message and pass it to the next
<twitter:public-timeline />
</poll> message in the chain.
</flow>
The following table contains commonly used transformers. In addition to custom components, Mule provides the following
utility components.
Name Description
message-properties- Adds and removes properties from a message, Component Description
transformer optionally specifying their scope. <log-component> Logs messages.
byte-array-to-string- Many basic type transformers are included. <echo-component> Returns and passes along.
transformer
<test:component> Helps test message flows (in the test namespace).
xml:jaxb-xml-to-object- Transforms JAXB objects explicitly.
transformer
auto-transformer Will automatically find the best transformer for a Hot Try to avoid implementing Callable to keep your
specified type. Tip component code decoupled from Mule’s API.
xml:xslt_transformer Transforms a message using the given stylesheet.
json:object-to-json- Transforms message payloads to and from JSON.
transformer Filters
gzip-compress- Compresses and uncompress message payloads
Filters selectively pass messages to the next processor in
transformer using gzip. the chain.
encrypt-transformer Encrypts and decrypts message payloads. The following table contains commonly used filters.
Name Description
Endpoints often include their own transformers. expression-filter Passes messages using any of the expressions
Hot JMS for instance, allows transformers to convert languages supported by Mule.
Tip message payloads to and from JMS messages regex-filter Decides what messages to pass by applying the
autormatically. supplied regular expression to the message payload.
payload-type-filter Passes messages only of the given type.
Components custom-filter Specifies the class of a custom filter that implements
Components allow business logic to be executed in a flow. Any the org.mule.api.routing.filter.Filter interface.
Java object or script can be used as a component. Components and-filter, or-filter, Logic filters that work with other filters.
are configured by either identifying the class or providing a not-filter
reference to a Spring bean for dependency injection. Using Filters with XPath
The following snippet shows how a class called MyService can be The following example demonstrates how the xpath-filter can
configured as a component using a class and via dependency- be used to only pass certain XML documents. In this case, only
injection via Spring. order XML documents containing a certain ZIP code are allowed
to pass.
<bean class=”com.acmesoft.service.MyService”/>
<flow name=”Filter messages using the XPath filter”>
<flow name=”test”> <vm:inbound-endpoint path=”input”/>
<http:inbound-endpoint host=”foo.com”> <mulexml:xpath-filter pattern=”/order/zipCode”
<component> expectedValue=”11209”/>
<spring-object bean=”myService”/> <vm:outbound-endpoint path=”output”/>
</component> </flow>
</flow>
Mule will use the type of the payload of the message being EXPRESSIONS
processed to determine what method to invoke. It’s often
necessary, however, to explicitly specify the method to invoke. Mule provides a rich expression language to evaluate data at
Entry point resolvers are used for this purpose. The following runtime using the message currently being processed.
table contains a list of available resolvers.
Evaluators
Resolver Description The following are commonly used expression evaluators.
method-entry-point-resolver Resolves the method using the specified
name. Name Description
property-entry-point-resolver Resolves the method using the specified xpath Query the message payload using XPath
message property.
payload Use the message’s payload for evaluation.
custom-entry-point-resolver A Java class that implements
map-payload A Java class that implements org.mule.api.model.
org.mule.api.model.EntryPointResolver
EntryPointResolver or extends org.mule.model.resolvers.
or extends org.mule.model.resolvers.
AbstractEntryPointResolver.
AbstractEntryPointResolver.
regex Perform a regular expression evaluation against a message
The use of entry point resolvers allows you to use POJO’s as payload.
components, decoupling your code from Mule. Sometimes, bean Evaluates the message payload as a JavaBean.
you will want access to the MuleMessage or MuleContext when groovy Use Groovy to evaluate an expression. Mule provides
processing a message. In cases like this, you can implement certain variables, like payload, properties and
the org.mule.api.lifecycle.Callable interface. Callable includes a muleContext, to the script context to aid in evaluation.
single method, onCall, to implement that provides direct access header:[scope] Return the given header for a specific scope, as
to the MuleMessage when the method is invoked. demonstrated below.
You can use the Mule 3 annotation support to quickly implement Functional testing is an important part of testing Mule
transformers and components. applications. Mule provides a helper class, org.mule.tck.
FunctionalTestCase, which you can extend to simplify setting up
Implementing a Transformer with Annotations
a TestCase.
Here’s an example of a transformer that lowercases a message’s
payload.
assertNull(client.request(“vm://output”, 5000));
}
}
#82
CONTENTS INCLUDE:
■
■
About Cloud Computing
Usage Scenarios Getting Started with
Aldon Cloud#64Computing
■
Underlying Concepts
Cost
by...
■
Upcoming Refcardz
youTechnologies ®
■
Data
t toTier
brough Comply.
Platform Management and more... borate.
■
Chan
ge. Colla By Daniel Rubio
on:
dz. com
grati s
also minimizes the need to make design changes to support
CON
ABOUT CLOUD COMPUTING one time events. TEN TS
INC
s Inte -Patternvall
■
HTML LUD E:
Basics
Automated growthHTM
ref car
Continuous Delivery
Usef
ContiPatterns an
■
However, the demands and technology used on such servers faced by web applications.Structure Tools
Core
Key ■
Structur Elem
E: has changed substantially in recent years, especially with al Elem ents
INC LUD gration the entrance of service providers like Amazon, Google and Large scale growth scenarios involvingents
specialized
NTS and mor equipment
rdz !
HTML
CO NTE Microsoft. es e... away by
(e.g. load balancers and clusters) are all but abstracted
Continu at Every e chang
About ns to isolat
relying on a cloud computing platform’s technology.
Software i-patter
space
CSS3
■
n
fca
e Work
Build
riptio
and Ant
Desc
These companies have a Privat
are in long deployed
trol repos
itory
webmana applications
ge HTM
L BAS
■
■
that adapt and scale
Deve
les toto large user
a versio bases, In addition, several cloud computing
ment ize merg
rn
Version e... Patte it all fi minim le HTM
r
Repo
This Refcard active
will introduce are withinto you to cloud riente computing, with an
d units
RATION etc. Some platforms ram support large grapRDBMS deployments.
■
The src
dy Ha
softw
e ine loping and Java s written in hical on of
INTEG attribute
task-o it all
softwar emphasis onDeve es by
Mainl these
ines providers, so youComm can better understand
also rece JavaScri user interfac web develop and the rris
Vis it
OUS
NoSQL
codel chang desc
ding e code Task Level as the
ww w.dzone.com
its
tern. term
Privat
(starting from zero) by Perfo all majorated cloud
feedb computing platforms. on As a user of Amazon’s
n. HTM EC2 essecloud shares platform, you are
ntiallycomputing result ed man ed layout
than
anybody
the pat gration of the e, this as autom as they
occur based proc certain is came supp
” cycl such Build Send builds
assigned esso
an operating L system
files shouin theplai
same elem
way as on allents
hosting The late a lack of stan up with clev y competi
ous Inte tional use and test concepts
soon n text ort.
ration ors as ion with r
Integ entat
ld not in st web dar er wor ng stan
Continu conven “build include oper
docum
be cr standar kar dar
While
the to the to rate devel
efers ion of CI Gene
Cloud Computing
the not
s on
expand
DZone, Inc.
140 Preston Executive Dr.
Suite 100
Cary, NC 27513
DZone communities deliver over 6 million pages each month to 888.678.0399
more than 3.3 million software developers, architects and decision 919.678.0300
makers. DZone offers something for everyone, including news,
Refcardz Feedback Welcome
$7.95
tutorials, cheat sheets, blogs, feature articles, source code and more.
refcardz@dzone.com
“DZone is a developer’s dream,” says PC Magazine.
Sponsorship Opportunities
Copyright © 2011 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a
retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, sales@dzone.com Version 1.0
without prior written permission of the publisher.