Mule Complete Training

download Mule Complete Training

If you can't read please download the document

Transcript of Mule Complete Training

By : Sourabh Aggarwal & Sumit GoleDate : 21 OCT 2015

Mule ESB is a lightweight Java-based enterprise service bus (ESB) and integration platform that allows developers to connect applications together quickly and easily, enabling them to exchange data. Mule ESB enables easy integration of existing systems, regardless of the different technologies that the applications use, including JMS, Web Services, JDBC, HTTP, and more.

The key advantage of an ESB is that it allows different applications to communicate with each other by acting as a transit system for carrying data between applications within your enterprise or across the Internet. Mule ESB includes powerful capabilities that include:Service creation and hosting expose and host reusable services, using Mule ESB as a lightweight service container

Service mediation shield services from message formats and protocols, separate business logic from messaging, and enable location-independent service calls

Message routing route, filter, aggregate, and re-sequence messages based on content and rules

Data transformation exchange data across varying formats and transport protocols.

What is Mule?

Mule Architecture

ComponentAnypoint Platform - Transform your business with API-led connectivity.

Mule runtime engine - Deploy an ESB, iPaaS or API gateway on a single, unified runtime.

Studio - Connect apps and data on our powerful IDE

API Designer - Build, design and test enterprise grade APIs, using RAML.

API Manager - Generate proxies, or apply pre-built or custom policies with clicks.

Analytics - Get real-time views on API consumption and performance.

API Portal - Create a rich onramp for your API with docs, sample code, and interactive tools.

ComponentAnypoint Platform - Transform your business with API-led connectivity.

Mule runtime engine - Deploy an ESB, iPaaS or API gateway on a single, unified runtime.

Studio - Connect apps and data on our powerful IDE

API Designer - Build, design and test enterprise grade APIs, using RAML.

API Manager - Generate proxies, or apply pre-built or custom policies with clicks.

Analytics - Get real-time views on API consumption and performance.

API Portal - Create a rich onramp for your API with docs, sample code, and interactive tools.

Mule Connectors.

https://docs.mulesoft.com/mule-fundamentals/v/3.7/mule-connectors

SFTP TransportWe can use the SFTP transport to download from or upload to a secured resource accessible via SFTP. This transport does not currently support transactions or retry policies. Some uses for the SFTP transport are downloading data into a database and picking up files and uploading them via SFTP.

We can use this transport to implement the file transfer Enterprise Integration Pattern. As explained in the EIP book, the file transfer pattern allows you to loosely couple two applications together, with delays in processing time

Using the SFTP transport allows you to optionally use streaming support for larger files and asynchronous and synchronously chain other endpoints with an SFTP endpoint. It also allows you to use Mules robust error handling in your Mule application.

Features:1. Streaming support of resources.2. For inbound endpoints, poll the resource at a specified interval.3. For outbound endpoints, choices on how to handle duplicate files: throw and exception, overwrite, append a sequence number to the file name.

SFTP TransportThe Secure Shell (SSH) File Transfer Protocol (SFTP) transport allows files to be read and written to and from directories over SFTP. Unlike the Virtual File System (VFS) transport, it can handle large files because it streams message payloads. The SFTP transport can be used as an inbound or an outbound endpoint. Files can be retrieved from an SFTP server and processed as Mule messages, or Mule messages can be uploaded as files to an SFTP server. Mule uses the JCraft library for SFTP SSH.

XML Namespace:xmlns:sftp="http://www.mulesoft.org/schema/mule/sftp"

XML Schema Location:http://www.mulesoft.org/schema/mule/sftp http://www.mulesoft.org/schema/mule/sftp/3.7/mule-sftp.xsd

SFTP TransportConnector Syntax:

SFTP Transport Endpoint Syntax :We can define your endpoints two different ways:

Prefixed endpoint:

Non-prefixed URI:

SFTP TransportUsage:To include the SFTP transport in your configuration:1. Define namespaces :

2. Define a connector:

SFTP TransportDefine an inbound and/or outbound endpoint:1. Use an inbound endpoint if you want new files found on the SFTP site to trigger a Mule flow2. Use an outbound endpoint if you want to upload files to an SFTP site. These files typically start as Mule messages and are converted to files.

Code :

SFTP TransportRules for Using the Transport :1. On the connector, you define the connection pool size, and your inbound and outbound temporary directories. The endpoint is where you define the authentication information, polling frequency, file name patterns, etc. See below for the full list of configuration options.2. One-way and request-response exchange patterns are supported. If an exchange pattern is not defined, 'one-way' is the default.3. This is a polling transport. The inbound endpoint for SFTP uses polling to look for new files. The default is to check every second, but it can be changed via the 'pollingFrequency' attribute on the inbound endpoint.4. Streaming is supported by the SFTP transport and is enabled by default. Retries and transactions are not currently supported.

SFTP TransportAttributes of

preferredAuthenticationMethods || string || no

maxConnectionPoolSize || integer || no

PollingFrequency || long || no

AutoDelete || boolean || no

FileAge || long || no

SizeCheckWaitTime || long || no

ArchiveDir || string || no

ArchiveTempReceivingDir || string || no

ArchiveTempSendingDir || string || no

OutputPattern || string || no

KeepFileOnError || boolean || no

DuplicateHandling || duplicateHandlingType || no

IdentityFile || string || no

Passphrase || string || no

TempDirInbound || string || no

TempDirOutbound || string || no

UseTempFileTimestampSuffix || boolean || no

SFTP TransportMaven Dependency if using maven

org.mule.transportsmule-transport-sftp

ExampleCreate the sftp.properties properties file in your Classpath or set your PATH variable to the files location.

Provide these parameters:sftp.user=sourabhsftp.host=localhostsftp.port=22sftp.password=sa

A properties file which holds the SFTP server login credentials is defined on 1. Next a SFTP inbound endpoint is declared on.2. Which checks the /opt/pantha/sftp/xtr/sftp/incoming/ directory for new files every one second by default.3. Defines a file filter which only sends files ending with .txt or .xml to the outbound endpoint. Any conforming files found on the inbound endpoint are then written to the /opt/pantha/sftp/xtr/sftp/outgoing/ sftp directory with the same file name it had on the sftp server.

Example

SFTP

Hands on!!!!

http://www.mulesoft.org/docs/site/current3/schemadocs/namespaces/http_www_mulesoft_org_schema_mule_sftp/namespace-overview.html

HTTP TransportThe HTTP transport provides support for exposing applications over HTTP and making HTTP client requests from Mule flows to external services. Mule supports inbound, outbound, and polling HTTP endpoints. These endpoints support all common features of the HTTP spec, such as ETag processing, cookies, and keepAlive. Both HTTP 1.0 and 1.1 are supported.

HTTP/S endpoints are synchronous by default, so you do not have to set exchange-pattern="request-response". If you set exchange-pattern="one-way", the messages are sent asynchronously.

For asynchronous POST, streaming is disabled.

Namespace and Syntax :http://www.mulesoft.org/schema/mule/http

XML schema locationhttp://www.mulesoft.org/schema/mule/http/3.6/mule-http.xsd

HTTP TransportURI Example :http://sourabh:sa@localhost:8080/httptestpath?query

XML Version :

Features :

1. Server acts as an HTTP server or client2. Create HTTP services such as SOAP, REST, or XML-RPC3. Make HTTP requests to external services4. Support for polling an HTTP endpoints including ETag support5. Transfer binary or text files, including forms and attachment6. Security includes SSL, certificates, and authentication7. Build flows to different paths on the same port8. Support for reading and writing cookies9. Streaming for transferring large files10. Custom HTTP header support11. Redirect Handling12. Handling of Content-Type and Encoding13. Serve up static content such as HTML, JavaScript, Images, and CSS (since Mule 3.2).

HTTP TransportTo create a HTTP server : you just need to create a flow with an inbound HTTP endpoint.

This with accept incoming HTTP requests on 'http://localhost:8080/sourabh' and echo the response back to the client.

To make a client invocation of an HTTP endpoint we can use the Mule client to invoke an HTTP endpoint directly in your code.

Or from within your code :MuleClient client = muleContext.getClient();MuleMessage result = client.send("http://localhost:8080/sourabh", "");

HTTP TransportFinally, you can reference an endpoint by name from your Mule configuration in the Mule client. Using the previous example, you can create a global HTTP endpoint from the flow or code:

Java Code :MuleClient client = muleContext.getClient();MuleMessage result = client.send("deleteEndpoint", "");

Global endpoints allow you to remove actual addresses from your code and flows so that you can move Mule applications between environments.

HTTP TransportSecurity :We can use the HTTPS Transport Reference to create secure connections over HTTP. If you want to secure requests to your HTTP endpoint, the HTTP connector supports HTTP Basic/Digest authentication methods (as well as the Mule generic header authentication). To configure HTTP Basic, you configure a Security Endpoint Filter on an HTTP endpoint.

You must configure the security manager on the Mule instance against which this security filter authenticates.

HTTP Response Header :The default behavior of the HTTP connector is to return, among other things, the X_MULE_SESSION header as part of every HTTP response. The content of this header is a base64-encoded Java serialized object. As such, if you decode the value and look at the plain text, you can view all the names and values of the properties stored in the Mule session. To tighten security, you can prevent Mule from adding this header when it encounters an endpoint that references this connector by including the following code.

If the X_MULE_SESSION header already exists as a property of the message, it is not removed by this sessionHandler attribute it is passed through. The header may be present due to another connector in the application having added it. If you need to purge this header completely, add the NullSessionHandler to all connectors referenced in the application.

HTTP TransportSending Credentials :If you want to make an HTTP request that requires authentication, you can set the credentials on the endpoint:http://user:[email protected]/secure

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

Polling HTTP Services :The HTTP transport supports polling an HTTP URL, which is useful for grabbing periodic data from a page that changes or to invoke a REST service, such as polling an Amazon Queue.1. To configure the HTTP Polling receiver, you include an HTTP polling-connector :

2. To use the connector in your endpoints, use:

HTTP TransportHandling HTTP Content-Type and Encoding :Sending :

For a String, char[], Reader, or similar:If the endpoint has encoding set explicitly, use thatOtherwise, take it from the messages property Content-TypeIf none of these is set, use the Mule Contexts configuration default.

For Content-Type, send the messages property Content-Type but with the actual encoding set.

For binary content, encoding is not relevant. Content-Type is set as follows:If the Content-Type property is set on the message, send that.Send "application/octet-stream" as Content-Type if none is set on the message.

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

Including Custom Header Properties :When making a new HTTP client request, Mule filters out any existing HTTP request headers because they are often from a previous request. For example, if you have an HTTP endpoint that proxies another HTTP endpoint, you wouldnt want to copy the Content-Type header property from the first HTTP request to the second request.

HTTP TransportIncluding Custom Header Properties :If you do want to include HTTP headers, you can specify them as properties on the outbound endpoint as follows:

or use Message Properties Transformer, as follows:

Building the Target URL from the Request :The HTTP request URL is available in the Mule header. You can access this using the expression #[message.inboundProperties['http.request']]. For example, if you want to redirect the request to a different server based on a filter, you can build the target URL as shown below:

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

The following example flow listens on the local address http://localhost:8080/mine and sends a response with the redirection code.

You must set the exchange-pattern attribute to request-response. Otherwise, a response immediately returns while the request is being placed on an internal queue.

If you configure a property as a child element of an inbound endpoint in Anypoint Studios XML editor, you receive a validation error indicating that this is not allowed as a child element. However, your flow runs successfully, so you can safely ignore this error.

HTTP TransportTo follow redirects when making an outbound HTTP call, use the followRedirect attribute :

Response Timeout :If no response is received for a set period of time, the connector will cease its attempts. By default, this time period is 1000 milliseconds, but you can set another value through the parameter responseTimeout.

If you set responseTimeout to 0, you will disable the timeout entirely.

HTTP TransportGetting a Hash Map of POST Body Parameters :We can use the custom transformerHttpRequestBodyToParamMapon your inbound endpoint to return the message properties as a hash map of name-value pairs. This transformer handles GET and POST with application/x-www-form-urlencoded content type.

Example :

Processing GET Query Parameters :GET parameters posted to an HTTP inbound endpoint are automatically available in the payload on the Mule Message in their raw form and the query parameters are also passed and stored as inbound-scoped headers of the Mule Message.

Example to creates a simple HTTP server :

HTTP TransportDoing a request from a browser using the URL:http://localhost:8081/echo?reverb=4&flange=2

Results in a message payload of /echo?reverb=4&flange=2 and two additional inbound headers on the message reverb=4 and flange=2.

You can access these headers using expressions such as the following, which can be used in filters and routers, or injected into code:

#[header:INBOUND:reverb]

Serving Static Content :The HTTP connector can be used as a web server to deliver static content such as images, HTML, JavaScript, CSS files etc. To enable this, configure a flow with an HTTP static-resource-handler:

The important attribute here is the resourceBase since it defines where on the local system from which to serve files. Typically, set this to ${app.home}/docroot, but it can point to any fully qualified location.

The default file allows you to specify the default resource to load if none is specified. If not set the default is index.html.

HTTP TransportContent-Type Handling :The static-resource-handler uses the same MIME type mapping system as the JDK, if you need to add your own MIME type to file extension mappings, add the following file to your application /src/main/resources/META-INF/mime.types:

HTTP Properties :http.context.path: The context path of the endpoint being accessed. This is the path that the HTTP endpoint is listening on.http.context.uri: The context URI of the endpoint being accessed, it corresponds to the address of the endpoint.http.headers: A Map containing all the HTTP headers.http.method: The name of the HTTP method as used in the HTTP request line.http.query.params: A Map containing all the query parameters. It supports multiple values per key and both key and value are unescaped.http.query.string: The query string of the URL.http.request: The path and query portions of the URL being accessed.http.request.path: The path the URL being accessed. It does not include the query portion.http.relative.path: The relative path of the URI being accessed in relation to the context path.http.status: The status code associated with the latest response.http.version: The HTTP-Version.

parameters are also stored plain on the inbound properties. This behavior was improved in Mule 3.3 with the http.headers and http.query.params properties.

For example, giving the following HTTP GET request: http://localhost:8080/clients?min=1&max=10, the query parameters can be easily accessed by:

#[message.inboundProperties['min']] and` #[message.inboundProperties['max']]`

Examples:Filtering HTTP Requests :

Examples:Polling HTTP :

foo

Examples:Setting Custom Headers :

Examples:WebServer - Static Content :

Examples:Setting Cookies on a Request :

HTTP TransportAttributes of

cookieSpec || enumeration || no

proxyHostname || string || no

proxyPassword || string || no

proxyPort || port number || no

proxyUsername || String || no

proxyNtlmAuthentication || boolean || no

enableCookies || boolean || no

HTTP TransportAttributes of

cookieSpec || enumeration || no

proxyHostname || string || no

proxyPassword || string || no

proxyPort || port number || no

proxyUsername || String || no

proxyNtlmAuthentication || boolean || no

enableCookies || boolean || no

PollingFrequency || long || no

checkEtag || boolean || no

discardEmptyConten || boolean || no

HTTP TransportAttributes of

httpMethod || enumeration || no

serviceUrl || || yes

Child Elements of

error-filter || 0..1

payloadParameterName || 0..*

RequiredParameter || 0..*

OptionalParameter || 0..*

Attributes of

Path || string || no

user || string || no

password || string || no

host || string || no

port || port number || no

contentType || string || no

method || httpMethodTypes || no

keep-alive || boolean || no

keep-alive || boolean || no

HTTP TransportAttributes of

followRedirects || boolean || no

exceptionOnMessageError || boolean || no

user || string || no

password || string || no

host || string || no

port || port number || no

path || string || no

contentType || string || no

method || httpMethodTypes || no

keep-alive || boolean || no

keep-alive || boolean || no

Attributes of

followRedirects || boolean || no

exceptionOnMessageError || boolean || no

user || string || no

password || string || no

host || string || no

port || port number || no

path || string || no

contentType || string || no

method || httpMethodTypes || no

keep-alive || boolean || no

keep-alive || boolean || no

HTTP

Hands on!!!!

https://docs.mulesoft.com/mule-user-guide/v/3.7/http-transport-reference

FTP TransportThe FTP transport allows integration of the File Transfer Protocol into Mule. Mule can poll a remote FTP server directory, retrieve files. and process them as Mule messages. Messages can also be uploaded as files to a directory on a remote FTP server.

Namespace and Syntax :Namespace (Community):http://www.mulesoft.org/schema/mule/ftpNamespace (Enterprise):http://www.mulesoft.org/schema/mule/ee/ftp

Syntax:Straight URI example ftp://theUser:secret@theHost:port/pathXml VERSION :

Connector and endpoint syntax :

FTP TransportFeatures :1. Poll a directory on a remote FTP server for new files2. Retrieve files an FTP server3. Transfer binary or text files4. Filter files at the endpoint based on filename wildcards5. Filter files at the endpoint based on Mule expressions6. Upload and store files on an FTP server7. Rename output files based on Mule expressions8. Streaming for transferring large files9. Support for reconnection strategies

Usage :

Each endpoint carries all the information for the FTP connection, such as, host, port, path, username and password at least. Additional properties (like binary or passive) can be specified on the connector and overridden at the endpoint level.

The FTP transport periodically polls the FTP server. Upon each poll request, a new connection to the FTP server is opened, the specified user is logged in and all files are listed under the specified path. This means that if the FTP server goes down no special provisions need to be made - the current poll attempt fails but polling doesnt stop.

If reconnection strategies are configured, the FTP connection can be re-established automatically by Mule based on the policy you have configured.

The FTP transport does not support transactions as the File Transfer Protocol itself is not transactional. Instead you should design compensating transactions into your architecture using exception strategies in Mule.

FTP TransportAttributes of

Path || string || no

user || string || no

password || string || no

host || string || no

port || port number || no

outputPattern || string || no

keepFileOnError || boolean || no

duplicateHandling || duplicateHandlingType || no

IdentityFile || string || no

Passphrase || string || no

TempDir || string || no

UseTempFileTimestampSuffix || boolean || no

ExampleThis example shows a simple flow that picks up all available files on the FTP server (in its root directory) and stores them into a directory on the local filesystem.

This example shows how to pick only certain files on the FTP server. You do this by configuring filename filters to control which files the endpoint receives. The filters are expressed in a comma-separated list. Note that in order to use a filter from the file transports schema it must be included.

DependeciesFor community edition :

org.mule.transports mule-transport-ftp 3.6.0

For enterprise edition :

com.mulesoft.muleesb.transports mule-transport-ftp-ee 3.6.0

ExampleThis example shows a simple flow that picks up all available files on the FTP server (in its root directory) and stores them into a directory on the local filesystem.

This example shows how to pick only certain files on the FTP server. You do this by configuring filename filters to control which files the endpoint receives. The filters are expressed in a comma-separated list. Note that in order to use a filter from the file transports schema it must be included.

FTP

Hands on!!!!

Database TransportThe Database connector allows you to connect with almost any Java Database Connectivity (JDBC) relational database using a single interface for every case. The Database connector allows you to run diverse SQL operations on your database, including Select, Insert, Update, Delete, and even Stored Procedures.

The Database connector lets you perform predefined queries as well as queries that take the connectors input to specify variable parameters or even to construct sections of the query dynamically.

The Database connector also allows the use of template queries that are both self sufficient and customizable. You can also perform multiple SQL requests in a single bulk update.

The connector also allows you to perform Data Definition Language (DDL) requests, that alter the data structure rather than the data itself.

The Database connector is available with both Mule Community and Mule Enterprise runtimes.

Database TransportSupported Operations :The database connector supports the following operations:SelectInsertUpdate DeleteStored ProcedureBulk ExecuteDDL operations such as CREATE, ALTER, etc.Additionally, you can run a TRUNCATE query on the database by selecting Update as the operation.

Database TransportConfiguring a Database Connector :The example below illustrates a very simple Mule application in Studio that meets the minimum configuration requirements: configured Database connector, configured Global Database connector, and installed database driver. Of course, the only one of these three required parts that is visible in the graphical representation of the application is the Database connector itself.

Database TransportTo prepare an application to use a Database connector as in the example above, you must first add the databases driver to your Mule project, then configure, at minimum, the required parameters for the Database connector element and a Global Database connector element. The diagram and section below describe how to address these requirements.

Database TransportDatabase Engines Supported Out of the Box :The database connector currently includes out of the box support for three database engines:OracleMySQLDerbyAll other database engines including MS SQL are supported by the Generic Database Configuration option.When using the Generic Database Configuration, you manually import the driver for your database engine and specify the driver class as one of the connection parameters. This allows you to use the database connector with any database engine for which you have a driver.

Database TransportConfiguring the Global Database Connector for Database Engines Supported Out of the Box :

Attribute, RequiredUse

NameUse to define a unique identifier for the global Database connector element in your application.

Database Configuration Parameters OR Configure via spring-bean OR Database URL Use to define the details needed for your connector to actually connect with your database. When you have completed the configuration, click Test Connection to confirm that you have established a valid, working connection to your database.

Required dependenciesClick Add File to add the database driver to your project.

Database TransportConfiguring the Global Database connector for Database Engines supported Out of the Box :

ExampleCreate database :CREATE DATABASE company;CREATE USER 'generatedata'@'localhost' IDENTIFIED BY 'generatedata';GRANT ALL PRIVILEGES ON company.* TO generatedata@localhost IDENTIFIED BY 'generatedata'; FLUSH PRIVILEGES;USE company;CREATE TABLE employees (no INT NOT NULL,dob DATE NOT NULL,first_name VARCHAR(14) NOT NULL,last_name VARCHAR(16) NOT NULL,gender ENUM ('M','F') NOT NULL,hire_date DATE NOT NULL,PRIMARY KEY (no));CREATE TABLE roles (id mediumint(8) unsigned NOT NULL auto_increment,emp_no mediumint,role varchar(255) default NULL,PRIMARY KEY (id)) AUTO_INCREMENT=1;INSERT INTO employees (no,dob,first_name,last_name,gender,hire_date) VALUES (1011,'1985-09-02','Chava','Puckett','F','2008-10-12');INSERT INTO employees (no,dob,first_name,last_name,gender,hire_date) VALUES (1012,'1971-12-03','Christopher','Tillman','M','2006-11-01');INSERT INTO employees (no,dob,first_name,last_name,gender,hire_date) VALUES (1013,'1975-07-31','Judith','David','F','10-11-20');INSERT INTO employees (no,dob,first_name,last_name,gender,hire_date) VALUES (1014,'1957-08-03','Neil','Ford','F','08-09-04');INSERT INTO employees (no,dob,first_name,last_name,gender,hire_date) VALUES (1015,'1977-01-09','Daryl','Wolfe','M','07-09-14');INSERT INTO employees (no,dob,first_name,last_name,gender,hire_date) VALUES (1016,'1986-03-08','Maryam','Burt','M','09-09-16');

ExampleMule FLOW :

Database

Hands on!!!!

FILE TransportThe File transport allows files on the local file system to be read from and written to. The connector can be configured to filter the file it reads and the way files are written, such as whether Mule places the output in a new file or appends the output to an existing file.

Namespace and Syntax:XML Namespace :xmlns:file="http://www.mulesoft.org/schema/mule/file"XML Schema Location :http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/3.6/mule-file.xsd

Connector Syntax:

FILE TransportEndpoint Syntax :file://[MULE:?params]

Inbound Endpoint :

Outbound Endpoint :

Features :1. Read files at a regular polling interval2. Write files

To use the file transport in your Mule configuration, Schema and use the , and/or elements.

You can use the following expressions inside attributes:

#[function:dateStamp]

#[function:datestamp:dd-MM-yy]

#[function:systime]

#[function:uuid]

#[message.inboundProperties.originalFilename]

#[function:count]

#[message.inboundProperties['_messagepropertyname'_]

ExampleThe following simple example copies files from /tmp/input to /tmp/output every 1 second (1000 ms). As input files are not deleted they are processed every time. Changing autoDelete to true just moves files. FileAge prevents moving files that are still being generated as the file has to be untouched for at least half a second.

File

Hands on!!!!

https://docs.mulesoft.com/mule-user-guide/v/3.7/file-transport-reference

Web service consumers

Hands on!!!!

RMI

Hands on!!!!

Mule Components.

https://docs.mulesoft.com/mule-fundamentals/v/3.7/mule-components

Mule Transformers.

https://docs.mulesoft.com/mule-fundamentals/v/3.7/mule-transformers

Mule Filters.

https://docs.mulesoft.com/mule-fundamentals/v/3.7/mule-filters-scopes-and-routers

Mule scopes.

https://docs.mulesoft.com/mule-fundamentals/v/3.7/mule-filters-scopes-and-routers

Scopes Scopes are the wrappers on a process flow. Type of scopesAsync :The child flow receives a message, it immediately sends one copyof that message to the next message processor in the parent flow.

Though the copy of messaage is passed to Async flow but payload is not copied i.e. if async flow change the payload then those changes are reflected in the original flow also.

till

Scopes Sync :the main flow halts, and all the message processors in the child flow execute before the parent flow resumes processing.

Cache: caches the subflow output for reusability. How this works?Mule genrate a key corresponding to a messages payload.

Cache scope checks the value corresponding to key.

If key exist then corresponding value is passed without executing the flow.

Else the value present in the memory iss passed.

ScopesConfiguring an Object StoreCustome object store: create custome class to store the cached responses.

In-memory-store: by configureing properties use in memory option to store the object.

Managed-store: store the cached responses in a place defined by ListableObjectStore.

Simple-text-file-store: Store the object in a file.

ScopesComposite source:Accept messages from multiple input channels and pass the payload to message processors.

ScopesMessage Enricher: Used to enrich the incoming message with additional information.Eg:

Mule currently supports enrichment of flow variables and message headers only.

ScopesForeach : splits a collection in to elements and process individusal element using the processor in the scope.Eg:

ScopesTransactional: execute a flow as a single unit i.e. series of steps in a flow must succeed or fail as one unit.

Following connectors support transactional demarcation:JMS

JDBC (Deprecated)

VM

ScopesTransactional tips:

Operations that occur inside a transaction execute synchronously.Scope is from first outbound connector to next outbound connector.

ScopesUntil Successful: scope processes messages through the processors within it until the process succeeds.

---------

Scopes

Hands on!!!!

Mule routers or flow control.

https://docs.mulesoft.com/mule-fundamentals/v/3.7/mule-filters-scopes-and-routers

Mule Error handling.

https://docs.mulesoft.com/mule-fundamentals/v/3.7/mule-exception-strategies

Exception Handling When ever any activity in mule instance fails then mule throws an exception. Mule exceptions are categorised in two parts.System Exceptions

Messaging Exceptions

System Exceptions : For instance exceptions occures during application startup.

When a connection to external system fails.Eg: Before receving any message , Mule tries to connect to any messaging server and get exception. Then this is called system exception.

System Exception strategy is not configurable in mule.

Exception Handling When ever any activity in mule instance fails then mule throws an exception. Mule exceptions are categorised in two parts.System Exceptions

Messaging Exceptions

System Exceptions : For instance exceptions occures during application startup.

When a connection to external system fails.

Exception Handling Messaging Exceptions : While processing the payload if any exception occures then cooresponding defined exception strategy is executed.

Exception Handling Messaging Exceptions : Five ways to configure messaging exceptions.Default Exception Strategy : Implicitly and globally handles all messaging exceptions that are thrown in Mule applications.

Catch Exception Strategy : It catches all the exceptions thrown by the parent flow.

Exception HandlingChoice Exceptions : Catches all the exceptions of parent flow and on the bases of message content route the message to appropriate exception strategy.

Rollback Exception Strategy: For transactional flow if exception occures then it rollback the transaction in the flow.

The rollback exception strategy catches the exception and rolls the message back for reprocessing; the message throws an error again, the rollback exception strategy catches the exception again

Exception HandlingRollback Exception Strategy: There are two ways to handle two exceptions.One way: instructs the inbound connector transport to execute corrective actions.

Request and response: changes the payload of a message and returns it to the client.

Exception HandlingReference Exception Strategy: is used to refer the Global exception strategy in flows. Eg:

Exception Handling

Hands on!!!!