mule fundamentals

52

Upload: surendra

Post on 21-Nov-2015

77 views

Category:

Documents


0 download

DESCRIPTION

Mule Fundamentals user guide.

TRANSCRIPT

  • 1. Mule Fundamentals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.1 Meet Mule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

    1.1.1 About SOA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111.1.2 How Mule Differs from a Web Application Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

    1.2 Mule Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141.2.1 Mule Application Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191.2.2 Understanding the Mule Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

    1.2.2.1 Mediation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331.2.2.2 Orchestration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351.2.2.3 Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361.2.2.4 Endpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371.2.2.5 Understanding the Logical Data Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391.2.2.6 Policy Enforcement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

    1.3 Examples and Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441.4 Get Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

  • 3Mule Fundamentals

    Mule is a that enables you to connect anything, anywhere. Rather thanlightweight integration platformcreating multiple point-to-point integrations between systems, services, APIs, and devices, you can use Muleto intelligently manage message routing, data mapping, orchestration, reliability, security, and scalabilitybetween nodes. Plug other systems and applications into Mule and let it handle all the communicationbetween systems, enabling you to track and monitor everything that happens.

    Mule is so named because it carries the heavy development load of connecting systems.

    With Mule, you can:

    integrate applications or systems on premise or in the clouduse out-of-the-box connectors to integrate software-as-a-service (SaaS) applicationsbuild and expose APIsconsume APIscreate Web services which orchestrate calls to other servicescreate interfaces to expose applications for mobile consumptionintegrate B2B with solutions that are secure, efficient, and quick to build and deployshift applications onto the cloudconnect B2B e-commerce activities

    See what Mule is all about in this introductory video:

  • 41. 2. 3. 4.

    Learn the EssentialsThe following Mule Fundamentals chapters are organized into a learning syllabus. Read through them tofamiliarize yourself with Mule functionality and tools.

    Meet Mule A quick introduction to the Mule platform and its supporting tools.Mule Concepts Get familiar with Mule's event-driven architecture.Examples and Use Cases Browse detailed examples and use cases.Get Started Download Mule and try it out.

    Optionally, take the to learn the basic Mule concepts and work through a simple integrationfree online trainingapplication using Mule Studio.

    Step 1: Meet Mule >>

  • 5Meet Mule

    Meet Mule Mule is a Java-based enterprise service bus (ESB) and integration platform that allowsdevelopers to connect applications to exchange data. Mule enables easyquickly and easily integration of existing systems, regardless of the different technologies that the applicationsuse, including JMS, Web Services, JDBC, HTTP, and more.

    Mule is available in two runtime versions: Community and Enterprise. Mule Community is alightweight tool that includes the basic functionality you need to facilitate systems integration.

    Mule Enterprise includes additional features and capabilities that are ideal for production deployments of Mulethat have requirements for performance, scalability, HA, resiliency, or technical support. Both runtimes are builton a common codebase, so it is easy to upgrade from Mule Community to Mule Enterprise. Read more aboutthe differences between .Mule ESB Community vs Mule ESB Enterprise

    ContentsMule: The Big PictureWhat is Mule, Exactly?

    Design and DevelopDeployManage

    ExampleGo FurtherNext: Learn the basic Mule concepts >>

    Mule: The Big PictureMule was developed to take the donkey-work out of integration. If your application integration architecturelooks like this....

    ... Mule can help stop this point-to-point madness. Implementing an like Mule ESBEnterprise Service Bustakes the pain out of connecting all the applications you use in your business, whether they are on-premise orin the cloud.

  • 6Still not sure if you need an ESB? Read more about the "To ESB or not to ESB" question in this series of blog.posts

    What is Mule, Exactly?Mule ESB is a lightweight, open-source middleware that provides comprehensive applicationintegration. The Enterprise Service Bus (ESB) at Mules core facilitates intranet connectionswithin an organization as well as secure external connections to Web-based APIs and othercloud resources. All Mule applications and their cloud-based cousins known as iApps are easy to build, because they leverage pre-packaged building blocks designed to plug into the standardized interface provided by the Mule service bus.

    Let's take a quick tour of Mule and its related components, breaking things down into three basic stages ofapplication development and operations:

    design and develop deploy

    manage

    Design and Develop

  • 7Mule Studio is Mule's Eclipse-based graphical userinterface (GUI). Studio provides a powerful dragand drop design canvas and application builder,and includes a companion XML editing environmentfor developers who prefer to edit code directly. MuleStudio is also .available as an Eclipse plug-in

    Mule Studio contains the following features:

    The powerful feature builtDataMapperinto Mule Studio not only translates

    payloads from one data format to another; itcan map input to output data fields as well asfilter, enrich, and route message payloads.

    is a suite ofMule Enterprise Securitysecurity features that enforce secureaccess to information in Mule

    applications.

    A large and ever-expandingassortment of bundled and premium A

    facilitates quick, nypoint Connectorseasy cloud integration for the Mule applicationsyou create.

    Mule DataSense uses messagemetadata to proactively acquireinformation such as data type and

    structure in order to prescribe how to accurately mapor use data in your application.

    APIkit, released as a Beta product, isan open-source, declarative model speciallydesigned to facilitate REST API design anddevelopment.

    The Mule Healthcare Toolkit is a collection offeatures that facilitates integration with healthcaresystems by providing the tools needed to easilycreate, read and transform HL7 version v2.xmessages within Mule.

    Deploy

    Deploy to the embedded server bundled with MuleStudio for testing and debugging.

  • 8Deploy to the ESB Standalone server, available asan Enterprise or Community product.

    Deploy to the Mule Application Repository, whichyou administer through the Mule ManagementConsole. Use this option to deploy a Muleapplication to a .clustered Mule topology

    Deploy to CloudHub, the world's first integrationPlatform as a Service (iPaaS). Built on top of Mule,CloudHub allows you to integrate and orchestrateapplications, data sources, and services acrosson-premise systems and the cloud.

    Deploy your service definitions to the cloud-basedservice repository in toAnypoint Service Registryenable effective governance and support servicereuse within your organization.

    Manage

    The facilitatesMule Management Consoledeployment to the Mule Repository and subsequentdeployment to Mule clusters. It provides robustruntime management capabilities for on-premisedeployments.

    CloudHub Insight tracks everything your data doesin an application deployed to CloudHub. Insightmakes information searchable and helps you findand recover from any errors that occurred duringmessage processing.

    Anypoint Service Registry is an SOA governanceplatform that is built to be tightly integrated with MuleESB and CloudHub. Built from the ground up tosupport hybrid use cases, Anypoint Service Registrygoverns all of your service and API assets, whethertheyre internal or external, behind the firewall or onthe cloud, on a single platform.

    Anypoint API Manager (currently in private Beta) isa cloud-based API management service that allowsenterprises to connect with business partners andcreate new revenue channels through a secure andscalable API strategy.

    APIhub allows developers and enterprises todiscover and use over 13,000 APIs, and enablesAPI providers to publish and document APIs,engaging the developer community on an open,collaborative platform.

  • 9ExampleLet's say you work at a company that uses an online Customer Relationship Manager (CRM) and an in-houseaccounting system to manage all your customer accounts. Long ago, someone in the company wired thosetwo things together the CRM to the accounting system so that a customer's account details automaticallymove back and forth between the systems. This set-up has been working well for years with a littlemaintenance from a few IT administrators.

    Then, you merge with another company and are faced with the problem of getting the systems andapplications to communicate with each other. You could hire, or out-source, a team of developers to hard-codepoint-to-point connections between each...

    ... but this exercise is labor intensive to set-up, and very maintenance-heavy over the long term. If one systemupgrades to a new version, or if a system needs to be replaced, or if a new system is introduced into thenetwork, the point-to-point connections have the potential to multiply exponentially and become unwieldy and expensive to maintain.

    Alternatively, you could use , a light-weight integration platform that acts as an intelligent,Mulemessage-routing hub between nodes. Plug other systems and applications into Mule and let it handle the

  • 10

    routing logic to facilitate communication between systems.

    Go FurtherFind out .how Mule differs from a web application serverGet a deeper understanding of .Service-Oriented ArchitectureWatch a of Mule ESB.video overview

    Next: Learn the basic Mule concepts >>

  • 11

    Download whitepaper

    About SOA

    About SOAMule ESB is based on the concept of a . The SOA approach toservice-oriented architecture (SOA)development allows IT organizations to compose applications by building service interfaces aroundcomponents of applications and exposing those to service consumers. are discrete sets ofServicesfunctionality that are completely separate from each other but can work together on a canonical set of objects.For example, if you need to process customer invoices, you might have one service that merges customerdata from a database into the invoice and another service that checks the inventory database to see if theitems on the invoice are in stock and a third service that fulfills the order.

    Because each service stands alone, services can be used as building blocks for multiple processes and do nothave to be recreated for each type of process or message. For example, the service that merges customerdata onto the invoice could also be used to merge customer data onto statements, letters, or other documents.The logic that determines how the invoice data and customer data are merged is decoupled from the logic thatlooks up and retrieves the necessary customer data. This modular approach allows you to create functionalityonce and re-use it as many times as needed, streamlining development.

    This decoupling is a key element of . Mediation is a well-known pattern for promoting looseservice mediationcoupling. In SOA, service mediation also describes the capabilities of the ESB to convert between transportprotocols (including the ability to bridge between synchronous and asynchronous protocols), changing therepresentation of messages by transforming data, and enforcing compliance with policies by taking thenecessary steps such as auditing, logging, security monitoring, etc.

    Constructing the building blocks into a logical process is called . Service orchestration using anorchestrationESB allows for automation of common backend processes at the application service layer. These processescan be scheduled or exposed as services that are triggered by external events. Service orchestration differsfrom business process orchestration which may include longer running stateful business processes, complexhuman interactions and approvals, or parallel execution of those types of processes at the business servicelayer.

    Using SOA, businesses can realize dramatic savings on development costs and can rapidly adapt to changingbusiness conditions by reusing and reconfiguring existing services in developing new applications. SOA alsoenables better integration of enterprise IT resources, including previously isolated application silos and legacysystems. Mule fully supports the SOA approach and orchestrates communication among the services, allowingyou to easily tie all these applications together.

    Learn more about the top challenges for SOA firmsand best practices on how to address them.

    Go FurtherReturn to .Meet MuleFind out how Mule differs from a web application server.

    Next: Learn the basic Mule Concepts >>

  • 12

    How Mule Differs from a Web Application Server

    How Mule Differs from a Web Application ServerA common question that arises about Mule is "How does Mule compare to JBoss, Tomcat, or other webapplication servers?" While they share some important similarities, the differences come down to what you aretrying to achieve. Certain kinds of applications are easier to write, deploy, and manage in Mule, and otherkinds of applications would be easier to write, deploy, and manage using a web application server.

    SimilaritiesFirst, let's take a look at the similarities between Mule and a web application server:

    They both allow you to run simultaneously.multiple applicationsThey both provide an application container. In other words, they both provide an environment inwhich an application can run, acting as an intermediary between application code and the operatingsystem, and providing database access, easier communication over the network, memorymanagement, lifecycle management, and other services.They both allow you to your applications at runtime.manage

    DifferencesHowever, Mule works differently from a web application server because of its core activity as an integrationplatform. Mule specializes in three things:

    acting as a platform for applications that move data from one place to another often transformingthat data along the way so that it is readable at the other endexporting services to other applicationsorchestrating services

    In short, Mule was built to make interactions easier. Web application servers, on the othersoftware-to-softwarehand, are designed to make interactions easier. If you need to implement a usersoftware-to-end-userinterface, a web application server is generally a better bet. This doesn't mean that it wouldn't be possible tobuild in Mule, but doing so might be time-consuming and complex.

    Mule Web Application Servers

    Mule specializes in integration betweendifferent applications, databases, and cloud

    services.

    Web applications specialize in interaction withend users

    Mule applications are stateless andevent-driven

    Web applications are stateful

    Mule supports service-oriented architecture Web applications support multitier architecture

    Mule applications are built as a series of lightweight, stateless components in an event-driven processingchain called a flow. (For more about flows, check out .) Data travels in, through, and out of aMule ConceptsMule application, connecting other applications, databases, enterprise systems, or cloud services to oneanother. By keeping individual services at either end of the flow discrete, Mule supports service-oriented

    .architecture

    Web application servers, in contrast, support a , which allocates presentation, processing,multitier architecture

  • 13

    and data management into logically separate layers. Using a web application server makes it easy to deliver agraphical user interface on the presentation layer, but it doesn't include the integration capabilities of Mule thatwould allow it to connect seamlessly to databases or other services. For that, you'd have to write customcode.

    You can successfully like Tomcat or JBoss, or you could embedembed Mule within a web application serverany other kind of web container inside a Mule flow. Leveraging Mule for the integration and serviceorchestration tasks that it was designed for and using an application server to handle the end-user interactionscan provide a full spectrum of functionality.

    Go FurtherInvestigate different .Deployment ScenariosRefer to the detailed .Apache Tomcat resource center

    Next: Learn the basic Mule Concepts >>

  • 14

    Mule Concepts

    Mule ConceptsAt the simplest level, Mule applications accept and process through several Lego-block-likemessagesmessage processors plugged together in what we call a . Understanding the basic message structure andflowflow architecture is key to understanding Mule. Essentially every Mule flow contains a series of building blocksthat accept, then transform and process messages.

    In this introduction to Mule concepts, we'll examine the concept of the Mule flow first, then break down thecomponents of the Mule message that passes through that flow.

    ContentsThe Mule Flow

    Developing with FlowsThe Anatomy of a Flow

    The Mule MessageThe Message HeaderThe Message Payload

    Go FurtherNext: Explore some examples and use cases >>

    The Mule FlowA flow is the construct within which you link together several individual components (i.e. building blocks) tohandle the receipt, processing, and eventual routing of a message. Flows support synchronous andasynchronous child flows, one-way and request-response exchange-patterns, and other architecturaloptions. You can connect many flows together to build a complete application which you can then deploy onpremise, on Mule or another application server, or in the cloud.

    Developing with FlowsYou can build a Mule flow in two ways:

    typing lines of code into an XML-based application configuration fileusing Mules Studio graphical interface to arrange building block icons into visual sequences

    Subsequently, you configure these sequenced building blocks using additional Studio graphical tools, or byediting XML code in the configuration file, or a combination of the two.

    The Anatomy of a FlowAt the simplest level, flows are sequences of message-processing events. A message that enters a flow maypass through a wide variety of processors. In the example diagram below below, Mule receives the messagethrough a request-response inbound endpoint, transforms the content into a new format, and processes thebusiness logic before returning a response via the message source.

  • 15

    The units from which flows are constructed are known generically as (in Mule Studio) orbuilding blocks elem(in Standalone or Studio XML configuration). In general, a corresponds to an icon in theents building block

    Mule Studio GUI which in turn represents a message source, processor, or component. A building block is avisual representation of an XML element within the Mule application configuration file.

    Click the tabs below to view a simple flow in the Mule Studio visual editor and in XML.

    Studio Visual Editor

    Studio or Standalone XML

  • 16

    View namespace

    ...

    Mule processes messages initiated by external resources (i.e. events). For example, a message can beinitiated by an event such as a consumer request from a mobile device, or a change to data in a database, orthe creation of a new customer ID in a SaaS application.

    The first building block of most flows is a receiver which receives new messages and places them in the queuefor processing. Mule uses a element in the example above, an inbound HTTP endpoint message source to receive messages from one or more external sources, thus triggering the execution of a flow. A ctransportarries the message along as it passes through the integration and application levels for processing.

    Mule are the key to exchanging data between nodes, as they allow Mule to convert messagetransformerspayload data to a format that another application can understand. Mule also enables content enrichment ofmessages which allows you to retrieve additional data during processing and attach it to the message.

    Mule uses to conduct backend processes for specific business logic (like checking the customercomponentsand inventory databases). Then, the components route messages to the correct application (such as an orderfulfillment system). Mule uses what is called for core asynchronousStaged Event-Driven Architecture (SEDA)message processing in flows. Importantly, components don't have to have any Mule-specific code; they can

  • 17

    simply be POJOs, Spring beans, Java beans, Groovy scripts, or web services containing the business logic forprocessing data. Components can even be developed in other languages such as Python, JavaScript, Ruby,and PHP. Mules catalog of building blocks includes the most commonly used Enterprise Integration Patterns.

    Flows can also include filters, scopes, flow controls, error handling strategies, and a wide variety of cloudconnectors. For more details about the many types of flow building blocks and how they can be combined toprovide the exact functionality you need for your application, see . Mule Application Architecture

    For a more detailed walkthrough of how messages pass through flows, see Understanding the Mule.Architecture

    The Mule Message

    The is the data that passes through your application via one or more flows. It has twoMule messageimportant parts:

    the message , which contains metadata about the message headerthe message , which consists of your business-specific data. payload

    Some Mule messages may also have a third component: an attachment. However, as attachments are notfrequently used, we will not focus on them here.

    The Message HeaderThe Mule message header contains metadata about the message. This metadata consists of and properties v

    which provide useful information about the message that help it to get where it's going. Propertiesariables and variables share a common format: each individual property or variable has a and a . Thename valuename is how you refer to the property or variable in Mule, and the value is the information stored within it.Thus, the name is like a key to a door and the value is whatever is behind the door.

    A message's properties and variables contained in the header have specific that define and organizescopeshow they apply across that message's lifecycle.

    Properties have two main scopes: inbound and outbound.

    Inbound properties are automatically generated by the message source and cannot be set ormanipulated by the user.Outbound properties can be configured by the user. Outbound properties can become inboundproperties when the message passes from the outbound endpoint of one flow to the inboundendpoint of a different flow.

    Variables are user-defined metadata about a message. Variables have two scopes:

    Flow variables exist only for that flow. Session variables apply across all flows within the same session lifecycle.

    You can set, invoke, and manipulate outbound properties, flow variables, and session variables using Mule (MEL). We use the terms and because of , butExpression Language flow variable session variable MEL syntax

    these variables could be considered another flavor of properties. Flow variables could also be called invocationproperties, session variables could also be called session properties. For another explanation of Mulemessage properties and variables, with downloadable examples, check out .this blog post

    The Message PayloadThe message payload is the most important part of the Mule message because it is the data content that youare sending through your Mule application. You may apply metadata in the message header to communicateinformation about your message or secure it from being tampered with, but the core of the message the datayou are transporting is the reason the message exists in the first place.

    The payload doesn't necessarily stay the same, however, as it travels through a flow. Various message

  • 18

    processors in a Mule flow can affect the payload along the way by setting it, enriching, or transforming it into anew format. You can also extract information from a payload within a flow using MEL.

    Go FurtherRead more about flows, flow building blocks, and more complex examples of flow architecture in Mul

    .e Application ArchitectureFor a more detailed conceptual walkthrough of how messages pass through flows, see Understandi

    .ng the Mule ArchitectureRead about how to use (MEL) to access and manipulate information inMule Expression Languagethe message header and payload within the course of a Mule flow.Take the free online training to learn the basic Mule concepts and work through a simple integrationapplication using Mule Studio. Module 2 of this training describes the components of the Mulemessage and describes how to work with it using MEL.

    Next: Explore some examples and use cases >>

  • 19

    Mule Application Architecture

    Mule Application ArchitectureThis page covers the structural features you can build into Mule applications.

    ContentsAbout Mule ApplicationsFlow Building Blocks

    Message Source Message ProcessorsMessage Processing BlocksEndpointsProcessing StrategiesException Strategies

    Flow ArchitectureChild Flows

    SynchronousAsynchronousCalling Child Flows

    Flow ConfigurationAdvanced Use Case

    How It Works

    About Mule ApplicationsAt the simplest level, Mule applications accept one message at a time, processing received messages in theorder they are received. Such processing can lead to a variety of results. Sometimes, the Mule applicationreturns an altered or replacement message to the source of the original message. Additionally or instead, theapplication can send the message in its original or altered form to one or more third parties. In still other cases,Mule can decline to process the message if it has not met specific criteria.

    Sophisticated Mule applications go far beyond this sort of linear message processing. Advanced mechanismscan process different messages in very different ways. Furthermore, you can construct applications that utilize:

    various queue-and-thread arrangements to maximize throughputtransactionality or clustered nodes to maximize reliabilityobject stores to ensure data persistence

    These represent only a fraction of the features you can implement through Mule applications.

    In the following sections, we'll discuss flow architecture using the concept of building blocks within MuleStudio. Building blocks correspond to XML elements in the XML configuration file, but for the purposes ofmodeling flows and explaining concepts, we'll use building blocks and Studio graphical representations here.

    Flow Building BlocksStudio building blocks fall into several functional categories, some of which are processing blocks thatcomprise several building blocks themselves.

    Not all building blocks can occupy all positions within a flow. Often, the position of a building block in relation tothe rest of the flow (or in relation to the building blocks in its immediate vicinity) greatly influences the behaviorof the building block and how it must be configured.

    The following sub-sections detail the various types of building blocks (and processing blocks) that canpopulate a Mule Flow.

  • 20

    Message Source The first building block in most flows is a , which receives messages from one or moremessage sourceexternal sources, thus triggering a . Each time it receives another message, the messageflow instancesource triggers another flow instance.

    Typically an serves as a message source, although an can performInbound Endpoint Anypoint Connectorthis role as well.

    Sometimes the message source immediately places the incoming message into a queue. This allows themessage source to close the receiver thread it used to accept the message, and immediately open anotherthread to accept another incoming message. The message just placed into the queue waits until it reaches thehead of the queue and can be processed through the rest of the flow. Since the message is processedsequentially by two distinct threads (with an intervening wait inside the queue), start-to-finish transactionprocessing is not possible.

    Sometimes, a message source can accept incoming messages from multiple transport channels. For instance,you can embed an HTTP endpoint and a Servlet endpoint into the same message source. Or you can create amessage source to receive both IMAP and POP3 mail. Either embedded endpoint (i.e., transport channel) cantrigger a flow instance as soon as it receives an incoming message.

    Under certain conditions, flows do not need to be triggered by message sources. For instance, a Flow can trigger a private, child flow. Similarly, the can trigger a child flow thatReference Component Async Scope

    executes asynchronously, (i.e., in parallel with the parent flow).

    Message ProcessorsTypically, are pre-packaged units of functionality that process messages in variousmessage processorsways. Except for message sources, all the building blocks in a flow qualify as message processors. Messageprocessors offer the following advantages:

    generally, they dont have to be custom-codedmultiple message processors can be combined into various structures that provide the exactfunctionality you need for your application

    You can assemble message processors into application (i.e., flow) sequences in two distinct ways:by arranging icons on the Studio canvasby inserting XML code into the application configuration file

    Message processors fall into a number of convenient categories, as the following table indicates:

    Category Brief Description

    Endpoints They fall into two sub-categories (Inbound andOutbound), and provide a means for Muleapplications to communicate with the outside world.

  • 21

    Scopes They enhance, in a wide variety of ways, thefunctionality of other message processors orfunctional groups of message processors known as

    .Processing Blocks

    Components They allow you to enhance a flow by attachingfunctionality such as logging, display output, andeven child flows. Alternatively, they facilitateSoftware as a Service (SaaS) integration byproviding language-specific "shells" that makecustom-coded business logic available to a Muleapplication.

    Transformers They prepare a message to be processed through aMule flow by enhancing or altering the messageheader or message payload.

    Filters Singly and in combination, they determine whether amessage can proceed through an application flow.

    Flow Controls They specify how messages get routed among thevarious Message Processors within a flow. They canalso process messages (i.e., aggregate, split, orresequence) before routing them to other messageprocessors.

    Error Handlers They specify various procedures for handlingexceptions under various circumstances.

    Anypoint Connectors They facilitate integration of Mule applications withWeb-based, 3rd-party APIs, such as Salesforce andMongo DB.

    Miscellaneous This special category currently contains just onemember: the buildingCustom Business Eventblock, which you place between other buildingblocks to record (KPI)Key Performance Indicatorinformation, which you monitor through the MuleConsole.

    After you have arranged the various building blocks in your flow into proper sequence, you may need toconfigure these message processors using one or both of the available options:

    selecting from drop-down lists of available options or completing text fields in the Studio graphicalinterfaceentering attribute values within the XML configuration code. (A nifty, predictive auto-completefeature eases this task greatly).

    Message Processing BlocksMule provides several ways to combine multiple message processors into functional processing blocks.

    For instance, the scope allows you to embed into a single message source two or morecomposite sourceinbound endpoints, each one listening to a different transport channel. Whenever one of these listenersreceives an incoming message, it triggers a flow instance and starts the message through the message

  • 22

    processing sequence.

    Other building blocks known as provide multiple ways to combine message processors intoscopesconvenient functional groups that can:

    make your XML code much easier to readimplement parallel processingcreate reusable sequences of building blocks

    EndpointsAs previously mentioned, implement transport channels that facilitate the insertion or extraction ofendpointsdata from flows. Endpoints serve a diverse variety of roles, depending on how they are configured. Forexample, they can, as previously mentioned, serve as or conduits. They can implementinbound outboundone-way or request-response exchange patterns. And, in certain situations, you can embed other types ofmessage processors, such as transformers or filters, into endpoints.

    Inbound Endpoints

    When placed at the start of a flow, either alone, or embedded with other endpoints in a cocomposite sourcemponent, an endpoint is always referred to as an , because it accepts messages frominbound endpointexternal sources and passes them to the rest of the flow, thereby triggering a new flow instance.

    Not all flows require an inbound endpoint. For instance, a child flow can be triggered by a flow reference whichsends data to the child flow without using an inbound endpoint.

    Not all endpoints can serve as inbound endpoints. For instance, the SMTP endpoint and the Anypoint ServiceRegistry endpoint can both serve only as an outbound endpoint.

    Outbound Endpoints

    At the most basic level, pass data out of a flow. Often they occupy the final messageoutbound endpointsprocessor position in a flow, so when they pass data out of the flow, the flow instance is considered complete.

    However, an outbound endpoint can also appear in the middle of a flow, passing data to a database as therest of the flow continues, for instance.

    Not all endpoints can serve as outbound endpoints. For instance the POP3 and IMAP can only serve asinbound endpoints.

    Outbound endpoints can also be configured for a request-response exchange pattern, as detailed in thefollowing section.

    Request-Response Endpoints

    When inbound endpoints such as HTTP or VM are configured for a request-response pattern, they effectivelybecome hybrid inbound-outbound endpoints. Even if other outbound endpoints exist to conduct data out of theflow, the inbound endpoint configured for a request-response exchange pattern also conducts data out of theflow by returning a response to the original sender of the message.

    When outbound endpoints are configured for request-response exchange patterns, they can exchange datawith resources outside the flow or with a string of message processors entirely within the same Muleapplication, as depicted by the following schematic:

  • 23

    Not all endpoints can be configured for the request-response exchange pattern, and of those that can,request-response is the default exchange pattern for only some of them. To complicate matters further, certaincases exist (such as the JDBC Endpoint) where request-response is available, but only when the endpoint isconfigured as an outbound endpoint.

    When none of the endpoints in a main flow is configured to the request-response exchange pattern, the flowfollows a in which it receives incoming messages, but is not expected to provideone-way exchange patternany response to the original sender. However, the flow may send data to other parties such as a log file, adatabase, an email server, or a Web-based API.

    Processing StrategiesA processing strategy determines how Mule executes the sequence of message processors in yourapplication. For example, when the message source is configured for the request-response exchange pattern,Mule sets the processing strategy to which means that the entire flow gets executed on asynchronous,single processing thread, thus ensuring that the entire sequence of message processors executes, and theclient receives a response, as expected.

    By contrast, when the flow is configured for a one-way, non-transactional exchange pattern (i.e., no responseto the original message sender is required, and it isnt necessary to verify that all steps in the flow have beencompleted), Mule sets the processing strategy to which has the potential to raise flowqueued asynchronous,throughput. Under this processing strategy, the inbound endpoint places the incoming message into the queueas soon as it is received, then closes the receiver thread. When the message reaches the top of the queue, itresumes processing, but this time on a different thread. By implication, this sort of processing does not qualifyas transactional end-to-end, because the transfer from one thread to the next means that the processing cannot be rolled back if an exception is thrown.

    For further details, see .Flow Processing Strategies

    Exception StrategiesAn determines how Mule responds if and when an error occurs during the course ofexception strategymessage processing. In the simplest case, the error is simply logged to a file.

    You can configure a custom exception strategy to respond in a variety of ways to a variety of conditions. Forexample, if an exception is thrown after a message has been transformed, you can set Mule to commit the

  • 24

    message as it existed after being transformed, but immediately before the error occurred, so that the messagecannot inadvertently be processed twice.

    Studio provides four pre-packaged error handling strategies to handle exceptions thrown at various pointsduring the message processing sequence. For details, see .Error Handling

    Flow ArchitectureMule flows are extremely flexible, so you can combine building blocks in many ways, often to achieve thesame result. For many use cases, however, certain message processors tend to fall into loosely orderedpatterns. For example, suppose you wanted to create an application that receives product catalog requestsfrom a Web page then sends a PDF of the catalog back to the client who submitted the request. In addition,you want this flow to record the clients customer information to a database and log the transaction so that youcan keep track of how many of each kind of catalog have been sent. Your flow might look something like this:

    Note that you could embed the filter and the transformers inside the Inbound Endpoint, but placing them in themain Flow sequence makes the sequence of events easier to read on the Studio Message Flow canvas andin the XML-based application configuration file.

  • 25

    Child FlowsBefore we discuss the different kinds of child flows, let's clarify some of the conventions we use in theschematic diagrams on this page.

    A solid line (below) indicates processing along a single thread, which is ideally suited to synchronous transac. Execution of the parent flow halts while the child flow executes and does not resume untiltional processing

    the child flow has completed its processing and returned control to the parent flow.

    A dashed line (below) indicates simultaneous, parallel, asynchronous processing along multiple threads. Theparent flow triggers the asynchronous child flow while simultaneously passing a copy of the message

  • 26

    processed by the second building block to the third building block; the flows execute simultaneously andindependently until each finishes on its own.

    Every flow-based Mule application is built around a main flow. Typically, processing for each message beginswhen the message source receives a message and concludes when the last message processor in the mainflow completes its task. However, the main flow can also spawn various types of branch (i.e., child) flows thatrun synchronously or asynchronously, and can potentially provide the following advantages:

    an branch flow (which isnt required to return data to the main flow) can performasynchronouspotentially time-consuming tasks, such as writing data to an external database or emailing amessage.a child flow that handles operations considered much more (or much less) important than the tasksperformed by the main flow can respond to errors differently from the main flow.a child flow can make a complex application easier to read, either as an arrangement of icons onthe Message Flow canvas or as code within the XML editor.some child flows only need to be created once then can be multiple times throughout anreusedapplication.under certain circumstances, multiple child flows can promote by ensuring thathigh reliabilitycrucial sequences of events get completed.multiple child flows can be configured to execute on the next available node in a Mule cluster, thuspromoting and .high availability high throughput

    As the following sub-sections detail, child flows fall into two main categories: Synchronous and Asynchronous.

    SynchronousWhen a main flow triggers a synchronous child flow, it passes programmatic control to that child flow andsuspends its own message processing activity until the child flow completes its sequence of messageprocessing events and returns programmatic control to the main flow.

    Since the main flow and the child flow hand off programmatic control to each other, and by implication, allprocessing occurs on the same thread, each event in the message processing sequence can be tracked, and t

    can be ensured.ransactional processing

  • 27

    To learn more about transactional processing, clickhere.

    Transactional processing handles a complex event (such as the processing of anindividual message by a Mule application) as event that either distinct, individual succee

    or , and never returns an intermediate or indeterminate outcome.ds entirely fails entirelyEven if only one of the many message processing events in a Mule application flowfails, the whole flow is considered to fail.

    The application can then roll back (i.e., undo) all the successully completed messageprocessing steps so that, for instance, a customer invoice issued early in the flow isrescinded whenever one of the final steps in the flow, such as the physical mailing ofthe merchandise, fails to take place.

    Sometimes, in addition to rolling back all the steps in the original, failed processinginstance, the application can recover the original message and reprocess it from thebeginning. Since all traces of the previous, failed attempt have been erased, a singlemessage ultimately produces a only single set of results.

    Typically, transactionality is difficult to implement for Mule flows that transfer processingcontrol across threads, which occurs for most types of branch processing. However,certain measures (such as the use of VM endpoints at the beginning and end of eachchild flow that does not run on the main flows thread) can ensure that each of thesechild flows executes successfully , although this architecture does not ensureas a unitthat each message processor within one of these child flows completes its tasksucessfully. For details see .Two Queue Example

    SubflowsSubflows, which always run synchronously, inherit both the processing strategy and exception strategy of theparent flow. This type of child flow, which is referenced through the Subflow component in the Studio palette,provides a number of potential advantages. First, a subflow can isolate logical processing blocks, making theunderlying XML code much easier to read.

    Subflows are ideally suited for code reuse, so a developer can write a particular block of code just once, thenreference the same subflow repeatedly from within the same application. Here is a schematic example of asubflow that is called twice by different subflow component instances in the same parent flow.

    Although a subflow operates synchronously, it can spawn an asynchronous child flow of its own, whichexecutes in parallel, while the parent subflow and then the main flow continue to run.

    Synchronous Child Flows that are not SubflowsA special type of child flow operates synchronously, as a subflow does, but unlike a subflow, this type ofsynchronous child flow uses its own (rather than the parent flows) exception strategy. This can be useful whenthe message processing events inside the child flow are either much more or much less crucial than the rest of

  • 28

    the events in the main flow. In either case, you can set the exception strategy used by the synchronous childflow to perform very differently from the exception strategy you configured for the main flow.

    AsynchronousAsynchronous flows begin processing when triggered by the main flow (or a child flow that becomes itsparent). Since this type of child flow does not need to return data to the parent flow, it can executesimultaneously with the main flow. In other words, when the main flow triggers the asynchronous flow, itneither passes programmatic control to the asynchronous flow, nor does it pause its own message processinguntil the asynchronous flow completes execution. In other words, the parent flow retains programmatic controlthroughout, without regard to the state of the asynchronous thread.

    Calling Child FlowsThe flow reference component can call three distinct types of child flows.

    The first type, known as a , is synchronous and always inherits both the processing strategy andsubflowexception strategy employed by the parent flow. While a Subflow is running, processing on the parent flowpauses, and it resumes only after the Subflow completes and hands control back to the parent flow. Also,because a subflow must be named, it can be referenced multiple times by Flow Reference Componentsscattered about the main flow.

    The second type of child flow is called a , which is named, and therefore can besynchronous child flowreused just like a Subflow. Also just like a Subflow, a Synchronous Child Flow causes the parent flow to pauseuntil it completes execution. , unlike a Subflow, a Synchronous Child Flow does inherit theHowever notexception strategy used by the parent flow. This allows special error handling measures to be applied to justthe message processing events within the Synchronous Child Flow.

    The third type of child flow you can call through the Component is called an flow reference asynchronus. Note that an asynchronous flow called in this manner must be named, and because it existschild flow

    outside the parent flow, it can be called (i.e., reused) multiple times.

    An called by the scope, rather than the flow reference component, exists asynchronous child flow async in-li (i.e., within the parent flow), and runs asynchronously on a separate thread while the main thread continuesne

    to run without pause.

  • 29

    1.

    2.

    3.

    4.

    5.

    6.

    The following table details the component to use for calling the various types of child flows:

    Type of ChildFlow

    CallingComponent

    In-line ? (i.e. not named and non-reusable)

    Execution ExceptionStrategy

    Subflow Flow Reference No Synchronous Inherited

    Synchronous ChildFlow

    Flow Reference No Synchronous Not Inherited

    AsynchronousChild Flow

    Flow Reference No Asynchronous Not Inherited

    AsynchronousChild Flow

    Async Yes Asynchronous Inherited

    Flow ConfigurationBecause flows consist of sequences of Studio building blocks, you cannot place any building block in anyposition within a flow. Additionally, the proximity or absence of certain building blocks within a sequence candetermine whether a given building block can be placed at a certain point within a flow. Finally, dependingwhere it resides in a flow, a given building block, especially an endpoint, can expose an significantly differentset of attributes for configuration.

    Fortunately, the graphical canvas in Mule Studio keeps track of all these contingencies, and it will not let youplace a building block icon where it is not allowed.

    Although it is impossible to cover all the possible sequences of building blocks that can produce workableflows, a typical flow might utilize the following sequence:

    A consisting of one or more inbound endpoints triggers the flow each time it receivesmessage sourcea message.A , which may be embedded in the message source or follow it in the main flow, may identifyfilterinvalid messages and decline to pass them to the rest of the flow for processing.A can convert the incoming message into a data format consumable by the other messagetransformerprocessors in the flow. Like a filter, a transformer can be embedded within the message source orreside within the main flow.A can add certain vital information to a message. For instance, if a message arrivesmessage enricherwith an address attached, the message enricher might use the postal code to look up the associatedtelephone area code, then append this information to the message header for marketing purposes.After the message has been prepared for processing, it is generally sent to some pre-packed orcustom business logic (usually called a ) so that it can be processed in a mannercomponentappropriate for its particular content. Sometimes, external databases or APIs such as Salesforce areleveraged through building blocks known as .anypoint connectorsThe final stages of a flow can vary considerably; some or all of the following can occur:

    A response is returned to the original sender of the message.The results of the business processing are logged to a database or sent to some other third

  • 30

    6.

    party.

    Throughout the flow, you can do the following:

    send messages to queues (even more than one type on the same flow)specify threading modelscall child flows of various types

    Advanced Use CaseBy judiciously combining the architectural options and product features available in Mule ESB, you can, with aminimum of development effort, design and create powerful, robust applications that fit your needs exactly.

    The application pictured below leverages child flows, two types of queues, clustering, and load balancing tocreate a Mule application that facilitates all of the following:

    high throughputhigh availabilityhigh reliability (transactionality)

    How It WorksOur application builds upon a request-response exchange pattern, in which Web clients submit messages(requests), then wait for responses from the application.In this particular topology, A Java Message Server (JMS) sits between the clients and our application,receiving messages as they are submitted and managing them through Active MQ, a messaging queue thatperforms the following:

    keeps track of every submissionforwards messages to the application in the order they were submittedmakes sure that our application provides a response to every message within a specified timeoutperiodforwards each response the the appropriate sender

    Since the JMS sits outside the application, it is relatively slow compared to the rest of our application, which

  • 31

    runs on multiple threads within our cluster of Mule nodes. Also, it does not have direct visibility into thesuccess or failure of the individual message processing events within our application. Nevertheless, the JMSprovides a form of high-level transactionality by ensuring that a response is received for each message.

    Within our application, an HTTP endpoint set to the request-response exchange pattern serves as both theapplications message source (i.e., inbound endpoint) and its outbound endpoint, dispatching a response toeach sender by way of the JMS.

    The message processors within the main flow are segregated into three child flows, each of which begins andends with a VM endpoint and also runs on a separate thread. These VM endpoints share memory through aVM queue. If any of the asynchronous child flows fails to execute successfully, the VM queue reports this, thusensuring a type of flow-level transactionality known as .high reliability

    Our application has been configured through the Mule Management Console to run on a four-node cluster. Ifany of the nodes go down, one of the others picks up the processing load, thus ensuring high availability.

    As the following diagram illustrates, even if none of the nodes goes down, the child flow steps can beprocessed on the next available node. This type of automatic promotes .load balancing high throughput

    The above application stands as just one example of the many ways in which you can leverage Muletechnology to speedily create and deploy powerful, custom-tailored Mule applications.

  • 32

    Understanding the Mule Architecture

    Understanding the Mule ArchitectureThis section describes the different parts of the Mule architecture and how they handle messages and theirdata. For the sake of illustration, it uses the example of a company that needs to generate invoices forcustomer orders, perform some processing on those invoices, and then send them to the shipping departmentfor order fulfillment.

    This section includes the following topics:

    MediationOrchestrationComponentsEndpointsUnderstanding the Logical Data FlowPolicy Enforcement

  • 33

    Mediation

    Mediation - Separating Business Logic from MessagingOne of the many advantages of Mule ESB is that it can handle messages that are sent via a variety ofprotocols. For example, an invoice might always be in XML format, but it might arrive over HTTP in onesituation and as a JMS message in another depending on which application created the invoice. If acomponent handles only business logic and works with the data, not the message itself, how does it know howto read the various formats in which the message might arrive?

    The answer is that components don't know how to read the messages, because by default, components are. Instead, a carries the message along, and completely shielded from the message format transport transform

    change the message's payload (such as the invoice) as needed to a format the component can readersbefore the flow passes the message to the component. For example, if an XML invoice is sent over HTTP, theHTTP transport turns it into a Mule message, transformers change it along the way (such as from XML to aJava object) as required, and the flow directs the message to each component that needs to process it. All thetransporting, transforming, and routing of the message are completely transparent to the component. Thisdecoupling is .service mediation

    Transformers are the key to exchanging data, as they allow Mule to convert the data to a format that anothercomponent or application can understand. Most importantly, . Instead ofdata is transformed only as neededmandating the conversion of every message to a single common data protocol (like XML) and specificmessage format, messages and their data are transformed only as needed for the target component orapplication where the message is being sent. Mule also enables content enrichment of messages throughintegration patterns that allow you to retrieve additional data during processing and attach it to the message.

    Multiple types of transports can be enabled to handle different channels, such as sending the message over asynchronous HTTP endpoint and then forwarding it as an asynchronous JMS message after it has beenprocessed by the Customer Data component. This decoupling of the transport layer allow services to bereused across the enterprise regardless of the legacy technology decisions that were made and enabledifferent choices in protocols to be made based on service level agreements or concerns around reliability orperformance.

    Mediation also means that policy compliance can be layered into the architecture outside of the services.Logging, auditing, and security monitoring can all be performed without any modification of the existing code.Policy enforcement can even be applied based on who is calling the service or what routing has occurred.

    The separation of the business logic from the sending and transformation of messages allows for greatflexibility in how you set up your architecture and makes it much simpler to customize the business logic

  • 34

    without having to worry about the various formats in which a message might arrive. Your component can workwith the raw data of the message if desired, but it is not required.

  • 35

    Orchestration

    Orchestration - Routing Messages Between ComponentsA Mule component contains business logic for processing the data in the message. It does not contain anyinformation about how to receive or send messages themselves. To ensure that the component receives theright messages and routes them properly after processing, an flow wraps the component (ororchestrationcomponents) with additional message processors that filter, transform, enhance or route the message to theappropriate component or endpoint. This allows the invocation sequence to be dynamically varied based onthe context of the message or the current load or availability of the system.

    When business process orchestration is required, Mule provides a for enabling different BPMBPM moduleengines within Mule. Business process orchestration should be used for longer running stateful businessprocesses, complex human interactions and approvals, or parallel execution of those types of processes at thebusiness service layer rather than the application layer.

  • 36

    Components

    Components - Processing the DataWhen a message is sent from an application (such as the invoice from an order entry system), Mule picks upthe message, sends it to a flow that processes it using some specific business logic (such as checking thecustomer and inventory databases), and then routes it to the correct application (such as the order fulfillmentsystem). Mule contains many individual parts that handle the processing and routing of the message. One keypart is a . Components execute business logic on messages, such as reading the invoice object,componentadding information to it from the customer database, and then forwarding it to the order fulfillment application.

    An important feature of components is that they don't have to have any Mule-specific code; they can simply bePOJOs, Spring beans, Java beans, Groovy scripts, or web services containing the business logic forprocessing data in a specific way.

    Mule manages components for you, bundles them with configuration settings, exposes them as messageprocessors, and ensures that the right information is passed to and from them based on the settings youspecified for their flows in the Mule configuration file.

    Mule supports chaining multiple processing steps together through an orchestration mechanism called a flow.Flows allow any number of components to be chained together along with other forms of message processing.Flows allow Mule to orchestrate how and when a message is routed to a component.

    You can have many different components that perform different business logic, such as one that verifieswhether the items on the invoice are in stock and one that updates a separate customer database with theorder history. The invoice, which is encapsulated in a message, can flow from one component to the next untilall the required processing is complete.

  • 37

    Endpoints

    Endpoints - Wiring Everything TogetherEndpoints are configuration elements that are the key to wiring together all your services. You specifyendpoints in your flows to tell Mule ESB which transport to use, where to send messages, and whichmessages a component should receive. The primary part of an endpoint is the address which indicates thetransport to use, the location (a transport-specific resource), and any additional parameters.

    Addresses may be expressed as a Uniform Resource Identifier ( ) or as schema-specificURIXML configuration

    For example, if a flow's inbound endpoint's address is , the HTTP transport takes anyhttp://myfirm.com/mulemessages that have been sent to that URL and dispatches them to the flow. If the inbound endpoint specifiesfile://myserver/files/, the File transport, which is watching that directory, dispatches any new files created inthat directory to the flow.

    Depending on the messaging style you specify, Mule may or may not generate a response to send backthrough the inbound endpoint to the sender. Mule supports several Message Exchange Patterns and eachtransport has a default pattern it will follow unless you specify otherwise. Mule will typically return the finalresult of the message processing back as the result; however response processing can also be specified tocontrol what is returned.

    An outbound endpoint can also be specified to indicate where the message will go next. For example, afterprocessing an HTTP request, you may want to place the result on a JMS queue as shown in the followingillustration.

    A flow can receive messages using many different transports. For each type of transport that a flow uses, youspecify one or more separate endpoints. For example, if you want one of your flows to handle messagescoming in on both the HTTP and JMS channels, you would specify at least one inbound HTTP endpoint and atleast one inbound JMS endpoint. Mule registers these endpoints with the flow, and the transport uses thisinformation at runtime to configure itself and determine where to send and receive messages.

    Mule also supports dynamic endpoints, allowing the destination to be constructed from the content of themessage. This allows routing-slip patterns where the message instructs Mule where to route it.

    The flow can also include filters that further specify which messages to send or receive. For example, you canspecify that the component only receives RSS messages by a specific author. Specifying filters, routers, and

  • 38

    endpoints for your services simply requires editing an XML configuration. You do not have to write any Javacode. Some routers are also dynamic and can change behavior based on the content of the message or anexternal data source such as a file or database. As stated previously, your components code remainscompletely separate from messaging and routing, which you handle through Mule configuration.

    In summary, Mule provides a simple and lightweight way to write components that do something to datawithout needing to worry about the sender or recipient of the data, the format of the data, or the technologybeing used to send/receive the data. Although many brokering and integration technologies offer the ability toconnect to disparate data sources, they often require extra coding to get messages to behave the way youwant and to deliver the data where you want it to go. Mule allows you to quickly develop components and thenchange the way they behave through simple XML configuration instead of writing Java code.

  • 39

    1.

    2.

    3. 4. 5.

    6.

    7.

    8.

    9.

    Understanding the Logical Data Flow

    Understanding the Logical Data FlowThe previous sections introduced each of the parts of the Mule instance from a conceptual view point. Now,using the invoice example again, let's take a look at how data flows logically through each part of a Muleinstance. Throughout the process, Mule uses the Mule configuration file to determine which components,routers, transports, and transformers to use along the way. The diagram that follows illustrates these steps.

    The customer places an order on the company web site, and an invoice is created as an XML form andsubmitted to .http://myfirm.com/ordersThe HTTP transport receives the XML invoice and wraps it in a Mule message. The Customer Dataflow's inbound endpoint is set to , so the HTTP transport dispatches thehttp://myfirm.com/ordersmessage to the flow.The XML to Object transformer converts the XML invoice into a Java object.The flow passes the message with its transformed payload to the Customer Data component.The Customer Data component queries the master customer database to pull additional data about thecustomer and updates the invoice with the data.What follows in the flow is an HTTP outbound endpoint, so the HTTP transport determines that it mustnow dispatch the message to its address, .http://myfirm.com/verifyThe HTTP transport uses the configuration of the Inventory Verification flow to receive the message andpass it to the Inventory Verification component.This component updates the invoice with an ID code of the warehouse that has all the items on theinvoice in stock.The outbound endpoint specifies a JMS address, so the JMS transport dispatches the message to theorder fulfillment application, which picks up orders on that address.

  • 40

  • 41

    Policy Enforcement

    Policy EnforcementMule provides capabilities to add audit, logging, and security enforcement at the ESB layer.

    ExamplesThe following are examples of how to set and enforce policy in a Mule application.

    Event TrackingYou can inspect all messages using a Wire Tap pattern. To inspect messages that travel on a point-to-pointchannel, insert a Recipient List into the channel that publishes each incoming message to the main channeland a secondary channel.

    The Wire Tap is a fixed Recipient List with two output channels. It consumes messages off the input channeland publishes the unmodified message to both output channels. To insert the Wire Tap into a channel, createan additional channel and change the destination receiver to consume from the second channel. Because theanalysis logic is located inside a second component, a generic Wire Tap can fit into any channel without anydanger of modifying the primary channel behavior. This improves reuse and reduces the risk of instrumentingan existing solution.

    The Notifications API

    Mule's API includes the concept of notifications. ServerNotification is an event triggered by somethinghappening in the server itself such as the server starting or a flow being registered. It is the parent of a host ofconcrete notifications you can use in your Mule-aware Java applications:

    ServerNotificationComponentMessageNotificationConnectionNotificationCustomNotificationEndpointMessageNotificationExceptionNotificationFlowConstructNotificationManagementNotificationMessageProcessorNotificationModelNotificationMuleContextNotificationRegistryNotificationRemoteDispatcherNotificationRoutingNotificationSecurityNotificationServiceNotificationTransactionNotification

    LoggingExamining the Mule log is a way to understand what is happening as messages move through a Muleapplication. Mule's logging configuration is stored in ./conf/log4j.properties. Edit this file to change the verbosityof the log output.

    The following code demonstrates how to log messages:

  • 42

    For more details, use a scripted logging component like the following:

    log.info(message); log.info(payload);message

    Security EnforcementSecurity is an important part of policy. There are three elements of enforcing security in a Muleapplication--encryption/decryption transformers, security filters, and Mule's own security manager.

    Encryption Transformers

    When writing Java code that requires encryption, you use Mule's Java encryption transformers. Mule providesan abstract class called AbstractEncryptionTransformer that will transform an array of bytes or string into anencrypted array of bytes once implemented. There are two concrete classes called DecryptionTransformer andEncryptionTransformer that will transform an encrypted array of bytes or string into a decrypted array of bytes,or will transform an array of bytes or string into an encrypted array of bytes.

    Security Filters

    Mule incorporates an abstract class for security filters, AbstractEndpointSecurityFilter, that you can implementto increase security of your Mule application. To implement this abstract class, authenticate inbound andoutbound events, ensuring no anonymous or null users gain access, then throw the correspondingUnauthorisedException with a message.

    Configuring Security

    Mule ESB allows you to authenticate requests via endpoints using transport-specific or generic authenticationmethods. It also allows you to control method-level authorization on your components. The Security Manageris responsible for authenticating requests based on one or more security providers. All security is pluggable viathe

    Mule security API, so you can easily plug in custom implementations.

    For information on the elements you can configure for the Security Manager, see Security Manager. The following sections provide links to information on configuring different types ofConfiguration Reference

    security managers.

    Spring Security

    Spring Security is the next version of Acegi and provides a number of authentication and authorizationproviders such as JAAS, LDAP, CAS (Yale Central Authentication service), and DAO. The following topics willhelp you get started securing your flows using Spring Security:

  • 43

    Configuring the Spring Security ManagerComponent Authorization Using Spring SecuritySetting up LDAP Provider for Spring Security

    WS-Security

    WS-Security is a standard protocol for applying security to Web services. It contains specifications on howintegrity and confidentiality in a SOAP message can be enforced via XML signatures and binary securitytokens such as X.509 certificates and Kerberos tickets as well as encryption headers. It ensures end-to-endsecurity by working in the application layer as opposed to the transport layer.

    Other Security Technologies

    Mule also supports the following security technologies:

    Encryption Strategies - Secure your messages by encrypting them.PGP Security - Secure your messages by encrypting them with PGP.Jaas Security

    Your Rating: Results: 0 rates

  • 44

    Examples and Use Cases

    Examples and Use CasesThis page collects all the examples and use cases that are available to you for Mule's various products.

    ContentsMule ExamplesMule Studio Core ConceptsAnypoint Service Registry WalkthroughsAnypoint Enterprise Security ExamplesUse CasesTutorialsNext: Get started with Mule >>

    Mule Examples

    Mule Examples offer insight into how you can use Mule to manage system connection and integrationsituations. Based on real-life business use cases, the examples demonstrate Mule's features andfunctionality, and suggest how you can take advantage of them.

    In , Mule's graphical interface, these example apps exist in the form of Mule Studio templwhich you can use to build a Mule application without having to start from scratch.ates

    In , (Mule without Studio) these example apps exist as files in theMule Standaloneexamples folder of the product distribution. You can access these example applicationsfrom your computer's console, using them as foundations upon which to build your ownapps.

    View the Mule ExamplesComplexity Example App Key Concepts Included in Runtime

    Community Enterprise

    Low Hello World Interacts withan end user

    via an HTTPrequest.

    Low HTTPRequest-Response with Logger

    Logs activityin an

    application.

    Medium Connect withSalesforce

    Facilitatescommunica

    tion between afile-basedsystem(s) andSalesforce.

  • 45

    Medium DataMapper withFlowRefLookup

    Facilitatescommunica

    tion between afile-basedsystem(s) andSalesforce.

    Uses aFlowRefLoo

    kup Table toacquireinformationoutside themessage, thenappend it to thepayload.

    Medium LegacyModernization

    Acts as aWebservice

    proxy for a legacy,file-based system.

    Medium ForeachProcessing andChoice Routing

    Dynamicallyapplies

    routing criteria to amessage atruntime.

    Processescollectionsiteratively without losing any of thepayload.

    Enriches message

    payloads withdata, rather thanchanging payloadcontents.

    Medium Websphere MQ Facilitatesmessage

    processingbetween Mule andWMQ.

  • 46

    High XML-only SOAPWeb Service

    Orchestrates a sequence

    of calls to otherservices ormessage queues.

    Dynamicallyapplies routingcriteria to amessage atruntime.

    High SOAP WebService Security

    Implementsapplication-la

    yer security on aSOAP Webservice.

    High ServiceOrchestration andChoice Routing

    Orchestrates a sequence

    of calls to otherservices ormessage queues.

    Dynamicallyapplies routingcriteria to amessage atruntime.

    Processescollectionsiteratively without losing any of thepayload.

    Cachesmessage

    content duringprocessing toreuse frequentlycalled data.

    Mule Studio Core ConceptsIn order to become familiar with some of the key configuration activities in Mule Studio, check out theStudio Core Concepts series. Launch Studio and try mimicking the activities so as to gain familiarityand confidence in working with Studio.

    View the Core Concepts

  • 47

    Configuring an Endpoint Introduces Flows and Endpoints, anddemonstrates how to invoke a Mule applicationusing HTTP.

    Adding Message Processors to a Flow Demonstrates how to add message processingcomponents, in this example Logger and Echo, toa Flow.

    Adding Business Logic to a Flow Demonstrates how to add custom code to a flowusing a Component.

    Understanding the Mule Message Demonstrates using the Mule expression languageto view the composition of a typical Mule message,including the message scope, message properties,and payload data.

    Filtering Invalid Requests Demonstrates how to use Filters to screen outinvalid requests.

    Transforming Data in a Flow Demonstrates how to use Transformers to alterdata in an HTTP request within a Flow.

    Invoking Component Methods Demonstrates how to resolve the method entrypoint when invoking business logic in a Java classrepresented as a Component.

    Using Outbound Endpoints to Publish Data Demonstrates how to use an outbound Endpoint totake data received via an HTTP request andoutput it to a file.

    Understanding Mule Interaction with ExchangePatterns

    Demonstrates the difference between one-way andrequest-response exchange patterns.

    Anypoint Service Registry WalkthroughsThe three-part walkthrough guide examines three use cases for a fictitious global freight company,Global Freight Service (GFS), and allows you to experience how you would interact with AnypointService Registry in each case.

    View the WalkthroughsScenario 1: runtime policy management

    Scenario 2: dynamic endpoint lookup

    Scenario 3: contract management

    To run the scenarios yourself, follow the steps in the in the setup guide ( or ) to set upfor ESB for CloudHubyour service registry account and download and deploy the sample applications.

  • 48

    Anypoint Enterprise Security ExamplesTwo example applications are available to demonstrate some of the functionality of the AnypointEnterprise Security Suite:

    Mule Enterprise Security Example ApplicationMule STS OAuth 2.0a Example Application

    Use CasesThe following use cases provide some practical examples of real-life integration scenarios.

    CloudHub Use CasesMule ESB Use CasesMMC Use Case: Performance TuningMMC Use Cases: Business Events

    TutorialsIn addition to the examples and use cases listed here, there are a number of that can get you up totutorialsspeed with Mule Studio and CloudHub.

    Try the :Mule Studio tutorials

    Basic Tutorial: Spell CheckerIntermediate Tutorial: Ajax Spell CheckerAdvanced DataMapper Tutorial

    Try the . The tutorials build upon each other, so it's a good idea to work through them inCloudHub tutorialssequence:

    Hello World on CloudHubGetting Started with Cloud ConnectorsReal Time Integration with Twitter and TwilioSalesforce to SFTP with Data Mapping to CSVCreating an API for a MySQL DatabaseBuilding an HTTPS ServiceCustom Application Alerts

    Ready to dive into something more complex? Try the , which require a workingadvanced CloudHub tutorialsknowledge of and Java.Maven

    Integrating Salesforce.com with an On-Premise DatabaseSimple Mongo DB & Twilio exampleBuild Your First Project with Maven and the Command LineZuora & TwiML exampleBuilding a RESTful Web Service

    Witness the demonstration of as it processes messages in an applicationMule Management Consoledeployed on a cluster of servers.

    Evaluating Mule High Availability Clusters Demo

    Next: Get started with Mule >>

  • 49

    1. 2. 3. 4. 5.

    Get Started

    Get StartedNow that you're familiar with the fundamentals, you're ready to go! This page collects all the information youneed on how to get started with Mule. Follow the links below to download or sign up for the products that youwant to explore.

    ContentsMule Studio and ESB RuntimesCloudHub Account SetupInclusions and Add-ons

    Anypoint DataMapperDataSenseAnypoint ConnectorsMule Management ConsoleMule Enterprise SecurityAnypoint Service RegistryAPIkitMule Healthcare Toolkit

    Mule Studio and ESB RuntimesCheck system compatibility and requirements.Download, then launch Mule.Add Community runtime to Mule Studio ( ).optionalInstall an Enterprise license ( ).optionalGet Started with Studio.

  • 50

    CloudHub Account Setup

    First, for a CloudHub account. then follow the instructions in to deploysign up Getting Started with CloudHubyour first application.

    Inclusions and Add-ons

    Anypoint DataMapper

    Anypoint DataMapper is included in Mule Studio with Enterprise runtime, so by downloading, you will automatically have access to DataMapper. Studio

    To get started with DataMapper, try out the or read the .Advanced Tutorial User Guide

  • 51

    DataSenseMule DataSense is included in Mule Studio with Enterprise runtime, so by downloading

    , you will automatically have access to DataSense functionality. Studio

    To get started with DataSense, examine the Connect with Salesforce example or read the Mu materials.le DataSense

    Anypoint Connectors

    Both the Community and Enterprise versions of Mule ESB include many AnypointIf you want toConnectors you can use in Mule Studio to connect to third-party Web APIs.

    add to your catalog of Mule Studio Connectors, you can from thedownload many moreupdate site or browse the collection of .connectors contributed by the community

    Get started with Anypoint Connectors by reading this .user guide

    Mule Management Console

    To try out Mule Management Console, go to the download page, clickMule EnterpriseDownload, fill out and submit the brief registration form, and then choose the option on theright of the screen: . Runtime Mule ESB Enterprise (with Management Tools)

    Follow the for Mule Management Console, then refer to the , which introduces allinstallation guide User Guidethe main functionality of the console.

    Mule Enterprise SecurityMule Enterprise Security is a collection of security features that enforce secure access toinformation in Mule applications.

    Download and install the Mule Enterprise Security update on your instance of Mule Studiowith Enterprise Runtime 3.3.2 or later.

    Read the for this feature suite to learn how to implement them in your applications.user guide

    Anypoint Service RegistryAnypoint Service Registry integrates with Mule Enterprise or CloudHub. Because it iscloud-based, there is nothing to install. Simply to get set up with an account, thencontact usget started with one of the following setup guides:

    Integrating Anypoint Service Registry with Mule ESBIntegrating Anypoint Service Registry with CloudHub

    APIkitAPIkit is an open-source, declarative model specially designed to facilitate REST API designand development. As a simple framework that caters to API-first development, it enforcesgood API design practices helping you to code faster, test more efficiently, and documentyour API almost without thinking about it. Read all about it in the .APIkit documentation

    APIkit is currently released as a . Contact us to give it a try! Beta product

  • 52

    Mule Healthcare Toolkit

    The Mule Healthcare Toolkit is a collection of features that facilitates integration withhealthcare systems by providing the tools needed to easily create, read and transform HL7version v2.x messages within Mule.

    to get a license and download link for the toolkit, then follow this .Contact us user guide

    Mule FundamentalsMeet MuleAbout SOAHow Mule Differs from a Web Application Server

    Mule ConceptsMule Application ArchitectureUnderstanding the Mule ArchitectureMediationOrchestrationComponentsEndpointsUnderstanding the Logical Data FlowPolicy Enforcement

    Examples and Use CasesGet Started