Content Based Routing using Choice flow control Mule

What is Content based routing?

Content-based routing is used to examine messages and route them to the correct channel or destination depending on a message’s content. We use content-based routing when we want to route messages to its right destination.

Choice flow Control

In mule Choice flow control is used to achieve the content-based routing where routing will be done based on the message content like inbound properties , flow variables and payload .Choice Router will always choose only one route. If no route matches, then the default route is used. In Choice Router we use the MEL expression to specify path for the message.

choice flow control adds the conditional programming to a flow, it is similar to an if/else if /else code block in java.

Use case:

Let’s take an application use case here. When we are expecting a message or payload to be received from the many inbound sources like file channel , FTP channel and a messaging queue and after receiving based on the type of the source we want to process the message accordingly than in this case we can appl choice flow control in the mule flow.

Let’s walk through how to use choice flow control in application.

Search for Composite Source componsnt in Mule Palette and drag and drop it to the source region of the flow.Now we can drag and drop multiple connectors under the composite source (i.e. wrap multiple connectors with the composite source). Here, we will use one HTTP Listener and one File Connector as inbound endpoints and one JMS (ActiveMQ) endpoint to receive messages from different sources. Now grab the choice flow control Mule Palette and drag and drop it after the composite source component.Choice flow control dynamically routes messages based on message payload or properties. use the attribute “expression” of choice flow control to filter the values based on the content of the message.

Flow:

Image title

Code:

<mule xmlns:jms=”http://www.mulesoft.org/schema/mule/jms&#8221;
xmlns:file=”http://www.mulesoft.org/schema/mule/file&#8221; xmlns:http=”http://www.mulesoft.org/schema/mule/http&#8221;
xmlns=”http://www.mulesoft.org/schema/mule/core&#8221; xmlns:doc=”http://www.mulesoft.org/schema/mule/documentation&#8221;
xmlns:spring=”http://www.springframework.org/schema/beans&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://www.mulesoft.org/schema/mule/jms http://www.mulesoft.org/schema/mule/jms/current/mule-jms.xsd
http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd”&gt;
<file:connector name=”File” autoDelete=”true” doc:name=”File” />
<http:listener-config name=”HTTP_Listener_Configuration” host=”localhost” port=”8081″ basePath=”/composite” doc:name=”HTTP Listener Configuration” />
<jms:activemq-connector name=”Active_MQ” brokerURL=”tcp://localhost:61616″ validateConnections=”true” doc:name=”Active MQ”>
<receiver-threading-profile maxThreadsActive=”200″ maxBufferSize=”100″ />
</jms:activemq-connector>
<flow name=”compositeSourceFlow”>
<composite-source doc:name=”Composite Source”>
<file:inbound-endpoint connector-ref=”File” path=”/file/in/processing/” moveToDirectory=”/file/data/processed” doc:name=”File”>
<file:filename-wildcard-filter pattern=”*.xml” caseSensitive=”false” />
</file:inbound-endpoint>
<http:listener config-ref=”HTTP_Listener_Configuration” path=”/composite” doc:name=”HTTP”> </http:listener>
<jms:inbound-endpoint queue=”myqueue1″ connector-ref=”Active_MQ” doc:name=”JMS”>
<jms:selector expression=”JMSPriority = 4″ />
</jms:inbound-endpoint>
</composite-source>
<logger level=”INFO” message=”#[message]” doc:name=”Logger”></logger>
<choice doc:name=”Choice”>
<when expression=”#[message.inboundProperties[‘http.query.params’]]”>
<logger level=”INFO” message=”Message is triggered from the Http Source”
doc:name=”Logger”></logger>
<byte-array-to-string-transformer
doc:name=”Byte Array to String” />
</when>
<when expression=”#[message.inboundProperties[‘originalDirectory’]]”>
<logger level=”INFO” message=”Message is triggered from the File Channel” doc:name=”Logger”></logger>
<file:file-to-string-transformer doc:name=”File to String” />
</when>
<when expression=”#[message.inboundProperties[‘JMSPriority’]]”>
<logger level=”INFO” message=”Message is triggered from the JMS call” doc:name=”Logger”></logger>
<byte-array-to-string-transformer doc:name=”Byte Array to String” />
</when>
<otherwise>
<logger level=”INFO” message=”Message is triggered from the Unknown Source” doc:name=”Logger”></logger>
</otherwise>
</choice>
</flow>
</mule>

Hope this helps.

Thanks

Keep Learning.

Until Successful scope in Mule

Until Successful scope in Mule

The until-successful scope is one of the scope available in mule which processes messages through its processors until the process succeeds. By default, until-successful’s processing occurs asynchronously from the main flow. After passing a message into the until-successful scope, the main flow immediately regains control of the thread. However, you can configure until-successful to run synchronously relative to the main flow.

The until successful component requires a mandatory object store to work. However Anypoint Studio doesn’t enforce this . If an object store is not declared, Studio throws an InitialisationException. The object store needs to be exclusive for each until-successful instance.

Below is the exception which will be thrown if object store is not declared for UntilSuccessful.

Exception:

org.mule.module.launcher.DeploymentInitException: InitialisationException: A ListableObjectStore must be configured on UntilSuccessful.

By default, until successful scope runs asynchronously but you can always configure as synchronous. For example, If parent flow is calling child flow in until successful scope, the main flow will not halt for child flow to complete, it will immediately regains control of thread.

IMP Attributes of Until Successful scope:

objectStore-ref

Reference to the org.mule.api.store.ListableObjectStore that is used to store events pending to process or reprocess.

maxRetries

Specifies the maximum number of retries that are attempted.

millisBetweenRetries

Specifies the minimum interval between two attempts to process, in milliseconds. The actual interval depends on the previous execution, but should not exceed twice this number. The default value is 60000 milliseconds (one minute).

deadLetterQueue-ref

The endpoint or message processor to which undeliverables messages are sent after all retries have been executed unsuccessfully.

Syntax:

<until-successful objectStore-ref=”objectStore”
failureExpression=”#[message.inboundProperties[‘http.status’] != 202]”
maxRetries=”6″ secondsBetweenRetries=”600″>
<http:request config-ref=”HTTP_Request_Configuration” path=”flakey” method=”POST” doc:name=”HTTP”/>
</until-successful

When all Else has Failed

If message processing keeps failing and the maximum number of retries is exceeded, the default behavior of the Until Successful message processor consists in logging the message details and dropping it.

If we want to perform a specific action on the discarded message (for example, storing it in a file or database), it is possible to configure a “Dead Letter Queue endpoint” where dropped messages are sent.

Until-Successful and Object Store

This message processor needs an ListableObjectStore instance in order to persist messages pending (re)processing. There are several implementations available in Mule, including the following:

•DefaultInMemoryObjectStore: default in-memory store

•DefaultPersistentObjectStore: default persistent store

•FileObjectStore: file-based store

•QueuePersistenceObjectStore: global queue store

•SimpleMemoryObjectStore: in-memory store

Synchronous Until-Successful

Out of the box, the until-successful scope processes messages asynchronously. After passing a message into the until-successful scope, the main flow immediately regains control of the thread thus prohibiting any returned response from the processing activities which occur within the scope.

However, in some situations, you may need until-successful to process messages synchronously so that the main flow waits for processing within the scope to complete before continuing processing. To address these needs, the Mule enables you to configure the scope to process messages synchronously.

When set to process message synchronously, until-successful executes within the thread of the main flow, then returns the result scope’s processing on the same thread.

When set to process synchronously, the until-successful scope does not accept the configuration of the following child element and attributes:

•threading-profile (synchronous until-successful does not need a ThreadPool)

•objectStore-ref (synchronous until-successful is not required to persist messages between retries)

•deadLetterQueue-ref (when the retry count is exhausted, Mule executes the exception strategy)

Use Cases:

The Until Successful message processor acts very much like a store-and-forward station: it stores any MuleEvent it receives and tries to process it a configured number of times at the defined retry frequency.

Let’s walk through how to use Until Successful scope in Mule application.

In this example we have two flow’s , First flow is “until-sucessfulFlow” with HTTP Request connector which is making a request on localhost and 8083 port wrapped in Until Successful scope.Second flow is “until-sucessfulRequestFlow” which is listening on localhost and 8083 port.After making a request “http://localhost:8081/until/until”  through REST client flow “until-sucessfulFlow” will be invoked and start calling the flow “until-sucessfulRequestFlow” until its able to deliver the message successfully .To replicate the failure case we can comment out our second flow “until-sucessfulRequestFlow” which will lead to the exception.

In case of failure we will be getting below exception.

Exception message

Root Exception stack trace:

org.mule.retry.RetryPolicyExhaustedException: until-successful retries exhausted. Last exception message was: Response code 404 mapped as failure.

Flow:

Image title

Image title

Code:

<?xml version=”1.0″ encoding=”UTF-8″?>

<mule xmlns:objectstore=”http://www.mulesoft.org/schema/mule/objectstore&#8221; xmlns:db=”http://www.mulesoft.org/schema/mule/db&#8221; xmlns:http=”http://www.mulesoft.org/schema/mule/http&#8221;
xmlns=”http://www.mulesoft.org/schema/mule/core&#8221; xmlns:doc=”http://www.mulesoft.org/schema/mule/documentation&#8221;
xmlns:spring=”http://www.springframework.org/schema/beans&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://www.mulesoft.org/schema/mule/db http://www.mulesoft.org/schema/mule/db/current/mule-db.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/objectstore http://www.mulesoft.org/schema/mule/objectstore/current/mule-objectstore.xsd”&gt;
<http:listener-config name=”HTTP_Listener_Configuration”
host=”0.0.0.0″ port=”8081″ basePath=”/until” doc:name=”HTTP Listener Configuration” />
<http:request-config name=”HTTP_Request_Configuration”
host=”localhost” port=”8083″ basePath=”/restcall” doc:name=”HTTP Request Configuration” />
<http:listener-config name=”HTTP_Listener_Configuration1″
host=”localhost” port=”8083″ basePath=”/restcall” doc:name=”HTTP Listener Configuration” />
<spring:beans>
<spring:bean id=”myListableObjectStore”
class=”org.mule.util.store.SimpleMemoryObjectStore” />
</spring:beans>
<objectstore:config name=”ObjectStore__Configuration” objectStore-ref=”_defaultUserObjectStore” doc:name=”ObjectStore: Configuration”/>

<flow name=”until-sucessfulFlow”>
<http:listener config-ref=”HTTP_Listener_Configuration”
path=”/until” doc:name=”HTTP” />
<until-successful maxRetries=”5″ objectStore-ref=”myListableObjectStore”
millisBetweenRetries=”3000″ doc:name=”Until Successful”>
<http:request config-ref=”HTTP_Request_Configuration”
path=”/restcall” method=”POST” doc:name=”HTTP” />
</until-successful>
<set-payload value=”Request Processed successfully2″
doc:name=”Set Payload” />
</flow>

<flow name=”until-sucessfulRequestFlow”>
<http:listener config-ref=”HTTP_Listener_Configuration1″
path=”/restcall” allowedMethods=”POST” doc:name=”HTTP” />
<set-payload value=”Request Processed successfully1″
doc:name=”Set Payload” />
</flow>

</mule>

Success Case:

Image title

Hope this helps.

Thanks

Keep Learning.

First Successful Router in Mule

First Successful Router in mule

First successful in one of the flow control component in the mule which iterates through message processors until one succeeds.

The First Successful message processor iterates through its list of child message processors, routing a received message to each of them in order until one processes the message successfully. If none succeed, an exception is thrown.

Success and failure is defined as:

•If the child message processor throws an exception, this is a failure.

•Otherwise:

If the child message processor returns a message that contains an exception payload, this is a failure.

If the child message processor returns a message that does not contain an exception payload, this is a success.

If the child message processor does not return a message (e.g. is a one-way connector), this is a success.

If the child message processor does not return a message (e.g. is a one-way connector), this is a success.

Defining failureExpression

We can further customize the behavior of this router by specifying a ‘failureExpression’ that allows you to use Mule Expressions to define a failure. The failureExpression attribute is configured as follows:

Syntax:

a failure expression is being used to more exactly define the exception type that’s considered a failure.

Note:

Let’s walk through how First Successful Router works in a Mule application.

In this example we have defined two routes ,where in both of the routes we are connecting with HSQL databases .One of the route is configured with  correct DB configuration “Generic_Database_Configuration_success” whereas other with the wrong DB configuration “Generic_Database_Configuration_failed”  which is configured to connect HSQL DB on port 9002. After making a requst through REST client second route configured will be able to process the message successfully.

If none of the route is able to process then below exception will be thrown.

Root Exception stack trace:

org.mule.api.routing.CouldNotRouteOutboundMessageException: Failed to route event via endpoint: org.mule.routing.FirstSuccessful@79baf566.

at org.mule.routing.FirstSuccessful.route(FirstSuccessful.java:58)

Flow:

Image title

Code:

<?xml version=”1.0″ encoding=”UTF-8″?>
<mule xmlns:db=”http://www.mulesoft.org/schema/mule/db&#8221;
xmlns:http=”http://www.mulesoft.org/schema/mule/http&#8221; xmlns=”http://www.mulesoft.org/schema/mule/core&#8221;
xmlns:doc=”http://www.mulesoft.org/schema/mule/documentation&#8221;
xmlns:spring=”http://www.springframework.org/schema/beans&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”
http://www.mulesoft.org/schema/mule/db http://www.mulesoft.org/schema/mule/db/current/mule-db.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd”&gt;
<http:listener-config name=”HTTP_Listener_Configuration”
host=”0.0.0.0″ port=”8081″ basePath=”/first” doc:name=”HTTP Listener Configuration” />
<db:generic-config name=”Generic_Database_Configuration_success”
url=”jdbc:hsqldb:hsql://localhost:9001″ driverClassName=”org.hsqldb.jdbcDriver”
doc:name=”Generic Database Configuration” />
<db:generic-config name=”Generic_Database_Configuration_failed”
url=”jdbc:hsqldb:hsql://localhost:9002″ driverClassName=”org.hsqldb.jdbcDriver”
doc:name=”Generic Database Configuration” />
<flow name=”first-successfulFlow”>
<http:listener config-ref=”HTTP_Listener_Configuration”
path=”/first” doc:name=”HTTP” />
<first-successful doc:name=”First Successful”>
<processor-chain>
<db:select config-ref=”Generic_Database_Configuration_failed”
doc:name=”Select * from Employee”>
<db:dynamic-query><![CDATA[select name from employee where id=3]]></db:dynamic-query>
</db:select>
<logger level=”INFO” message=”Processed by first message Processor”
doc:name=”Logger” />
</processor-chain>
<processor-chain>
<db:select config-ref=”Generic_Database_Configuration_success”
doc:name=”Select * from Employee”>
<db:dynamic-query><![CDATA[select name from employee where id=3]]></db:dynamic-query>
</db:select>
<logger level=”INFO” message=”Processed by second message Processor”
doc:name=”Logger” />
</processor-chain>
</first-successful>
<object-to-string-transformer />
</flow>
</mule>

Failed Request:

Image title

Success Request:

Image title

Hope this helps.

Thanks.

Keep Learning

Iterative Processing using For Each Scope Mule

Iterative Processing using For Each Scope in Mule

For Each scope is one of the scope available in mule which splits a collection into individual elements and processes them iteratively through the processors embedded in the scope, then returns the original message to the flow.This scope basically simplifies the splitting and aggregation of message collections.

How it works?
Foreach scope does not change the type of the message collection and as well does not change the contents of the of the original message collection, if the individual collection elements are immutable. That is, after Foreach splits a message collection and processes the individual elements, it does not re-aggregate those individual elements into a MuleMessageCollection; rather, it returns the original message. (This means “Java in, Java out”, rather than “Java in, MuleMessageCollection out”).

The Foreach scope is versatile; it can iteratively process elements from any type of collection, including maps, lists, arrays, and MuleMessageCollection.

IMP Points of Foreach:
1.) You can insert any message processor, except inbound connector in the Foreach scope.If we drag a two-way connector into a Foreach scope, Mule automatically converts it to an outbound-only connector.
2.)When foreach scope receives a message payload that is not a collection type like maps, lists, arrays, and MuleMessageCollection it throws an IllegalArgumentException.
3.)The rootMessage variable(flow Variable) is default associated with the message, contains a reference of the complete, unsplit message collection .
4.)The counter variable (flow Variable)is default associated with the message , Foreach uses counter variable to record the number of the elements it has processed.

In this Example Mule uses a Foreach message processor to extract, and iteratively process, records from a database.

Flow:

Image title

Code:

<?xml version=”1.0″ encoding=”UTF-8″?>

<mule xmlns:dw=”http://www.mulesoft.org/schema/mule/ee/dw&#8221;
xmlns:db=”http://www.mulesoft.org/schema/mule/db&#8221; xmlns:http=”http://www.mulesoft.org/schema/mule/http&#8221;
xmlns:ee=”http://www.mulesoft.org/schema/mule/ee/core&#8221; xmlns:cxf=”http://www.mulesoft.org/schema/mule/cxf&#8221;
xmlns=”http://www.mulesoft.org/schema/mule/core&#8221; xmlns:doc=”http://www.mulesoft.org/schema/mule/documentation&#8221;
xmlns:spring=”http://www.springframework.org/schema/beans&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://www.mulesoft.org/schema/mule/db http://www.mulesoft.org/schema/mule/db/current/mule-db.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd
http://www.mulesoft.org/schema/mule/cxf http://www.mulesoft.org/schema/mule/cxf/current/mule-cxf.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/ee/dw http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd”&gt;

<db:generic-config name=”Generic_Database_Configuration”
url=”jdbc:hsqldb:hsql://localhost:9001″ driverClassName=”org.hsqldb.jdbcDriver”
doc:name=”Generic Database Configuration” />
<http:listener-config name=”HTTP_Listener_Configuration”
host=”localhost” port=”8081″ basePath=”/foreach” doc:name=”HTTP Listener Configuration” />
<flow name=”forEachFlow”>
<http:listener config-ref=”HTTP_Listener_Configuration”
path=”/foreach” doc:name=”HTTP” />
<dw:transform-message doc:name=”Transform Message”>
<dw:set-payload><![CDATA[%dw 1.0
%output application/java

payload]]></dw:set-payload>
</dw:transform-message>
<foreach doc:name=”For Each Loop”>
<logger level=”INFO” message=”#[payload]” doc:name=”Logger” />
<enricher doc:name=”Message Enricher”>
<db:select config-ref=”Generic_Database_Configuration”
doc:name=”Select * from Employee”>
<db:dynamic-query><![CDATA[select name from employee where id=’#[payload.id]’]]></db:dynamic-query>
</db:select>
<enrich target=”#[flowVars.name]” source=”#[payload[0].name]”/>
</enricher>
<logger level=”INFO” message=”#[flowVars.name]” doc:name=”Logger” />
<expression-component doc:name=”Expression”><![CDATA[
payload.name= flowVars.name;
]]></expression-component>
</foreach>

<object-to-string-transformer />
<set-payload value=”#[payload]” doc:name=”Set Payload”/>
<logger level=”INFO” message=”#[payload]” doc:name=”Logger” />
</flow>
</mule>

Request:

[{
“id”:1,
“role”:”Application Developer”
},
{
“id”:3,
“role”:”Application Manager”
}
]

Image title

Response:

Image title

Hope this helps.

Thanks

Keep Learning

CORS(Cross-Origin Request Sharing) in Mule

CORS(Cross-Origin Request Sharing) in Mule

Here we will discuss about how to enable Cross-Origin Request Sharing in mule by adding outbound header properties.

The Same-Origin Policy:

The same-origin policy is an important security concept implemented by web browsers to prevent JavaScript from making requests across domain boundaries(e.g., different domain) than the one from which it was served.it does not allow interactions between resources from different origins.

For example, your JavaScript code hosted at http://domain-a.com  might want to use a REST API hosted at http://domain-b.com . However, because these are two different origins from the perspective of the browser, the browser won’t allow a script from http://domain-a.com to fetch resources from http://domain-b.com because the resource being fetched is from a different origin.

What is a Cross-Origin Request ?

If the script on your page is running from domain http://domain-a.com and would like to request a resource which is in another domain http://domain-b.com, this is a cross-origin request.These types of request is called Cross-Origin Request, For security reasons these types of requests have been prohibited by browsers.

CORS (Cross-Origin Request Sharing)

The solution of above issue is Cross-Origin Resource Sharing(CORS).CORS introduces a standard mechanism that can be used by all browsers for implementing cross-domain requests (Cross-Origin Request), allowing Javascript on a web page to consume a REST API served from a different origin.

The Cross-Origin Resource Sharing (CORS) mechanism gives web servers cross-domain access controls, which enable secure cross-domain data transfers.

How CORS works ?

The Cross-Origin Resource Sharing standard works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. In it’s simplest form; the requesting application specifies a Origin header in the request which describes the origin of the request and the requested resource will reply intern with an Access-Contol-Allow-Origin header indicating specific origins that are allowed to access a particular resource.

This exchange of headers is what makes CORS a secure mechanism. The server must support CORS and indicate that the domain of the client making the request is permitted to do so. The beauty of this mechanism is that it is automatically handled by the browser and web application developers do not need to concern themselves with its details.

Request headers:

GET /awesomeapi/list HTTP/1.1

Host: myawesomeapp.com

User-Agent: Mozilla/5.0

Accept: */*

Accept-Language: en-US,en;q=0.5

Accept-Encoding: gzip, deflate

Connection: keep-alive

Origin: http://myawesomeapp.com

Response headers:

HTTP/1.1 200 OK

Access-Control-Allow-Origin: http://myapp.com

Content-Type: application/json; charset=utf-8

Let’s walk through how to enable CORS in  mule application.

We need to add the following outbound properties into the flow as shown below. Following properties are added to accept any origin, method and headers so that cross origin/domain requests can be allowed.

<set-property propertyName=”Access-Control-Allow-Origin” value=”*” doc:name=”Access-Control-Allow-Origin” />
<set-property propertyName=”Access-Control-Allow-Headers” value=”*” doc:name=”Access-Control-Allow-Headers”/>
<set-property propertyName=”Access-Control-Allow-Methods” value=”*” doc:name=”Access-Control-Allow-Methods” />

This Enable Mule flows to accept cross domain requests.

mule Flow :

Image title

Code:

<mule xmlns:http=”http://www.mulesoft.org/schema/mule/http&#8221; xmlns=”http://www.mulesoft.org/schema/mule/core&#8221; xmlns:doc=”http://www.mulesoft.org/schema/mule/documentation&#8221;
xmlns:spring=”http://www.springframework.org/schema/beans&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd”&gt;
<http:listener-config name=”HTTP_Listener_Configuration” host=”0.0.0.0″ port=”8081″ basePath=”/cors” doc:name=”HTTP Listener Configuration”/>
<flow name=”corsFlow”>
<http:listener config-ref=”HTTP_Listener_Configuration” path=”/cors” doc:name=”HTTP”/>
<set-payload value=”Enabling cross domain requests in Mule using HTTP Headers”/>
<set-property propertyName=”Access-Control-Allow-Origin” value=”*” doc:name=”Property” />
<set-property propertyName=”Access-Control-Allow-Headers” value=”Content-Type, Accept” doc:name=”Property” mimeType=”application/json”/>
<set-property propertyName=”Access-Control-Allow-Methods” value=”*” doc:name=”Property” />
</flow>
</mule>

Request:

http://localhost:8081/cors/cors

Below are the screen shot of the response headers as part of the response.

Image title

Hope this helps.

Thanks

Ankit Lawaniya

Improving Performance with Cache Scope in Mule Application

Improving Performance with Cache in Mule Application

Caching:Caching is all about application performance optimization ,cache can be very useful in gaining fast application performance .

Cache scope is one of the scope in mule which saves on time and processing load by storing and reusing frequently called data in the memory, file system or database which saves processing time and load if it would have to be access from original source location every time.We can put any number of message processors into a cache scope and configure the caching strategy to store the responses (which contain the payload of the response message) produced by the scope’s subflow.

Even though mule has its default caching strategy its recommended to define the global caching strategy because The default caching strategy uses an InMemoryObject store and should only be used for testing;

Implementation Without Cache:

When an end user of a flight booking system is looking for the flight information between Delhi to Kolkata for a particular date, it then goes through the processing of various steps where it connects to multiple vendors to collect the flight details. Finally after collecting all the details the response will be returned to the user. Same processing steps will be executed for each incoming requests even if multiple users are looking for the same information. Which means if we receive 100 requests for the same source and destination search for a particular date, then all of the processing (steps) will be done 100 times.

Implementation With Cache:

Once the application receives the search request between Delhi to Kolkata for a particular date the response that has been returned to the user will be stored in a cache and for all of the next searches for the same source and destination for that particular date the result can just be returned from the cache without executing the same steps repititively.

Image title

how it works?

Mule sends a message into the cache scope and the parent flow expects an output. The cache scope processes the message, delivers the output to the parent flow and saves the output (i.e. caches the response). The next time Mule sends the same kind of message into the cache scope, the cache scope may offer a cached response rather than invoking, again, a potentially time-consuming process.

Each item in the cache is a key/value pair where the key represents the payload at the cache scope entry point. The value is the result at the end of the cache scope.By default, Mule uses SHA256KeyGenerator and a SHA256 digest to generate a key on the payload. For the cache entry value, Mule will cache not just the payload at the end of the cache scope, but the whole MuleEvent. The idea behind all of this is that apart from the payload, you might need other information such as message properties.

Use Case of Cache:

You can use a cache scope to reduce the processing load on the Mule instance and speed up message processing within a flow. It is particularly effective for:

1)Processing repeated requests for the same information.

2)Processing requests for information that involve large, non-consumable message payloads.

Configuring an Object Store for Cache

By default, Mule stores all cached responses in an InMemoryObjectStore. Below are the multiple ways of creating a caching strategy and define a new object store if you want to customize the way Mule stores cached responses.

  • custom-object-store:Custom object stores are useful when you want to use a custom persistence mechanism for your ObjectStore’s
  • In-memory: This store the data inside system memory. The data stored with In-memory is non-persistent which means in case of application restart or crash, the data been cached will be lost.
  • Managed-store: This stores the data in a place defined by ListableObjectStore. The data stored with Managed-store is persistent which means in case of application restart or crash, the data been cached will no be lost.
  • Simple-test-file-store:This stores the data in a file. The data stored with Simple-test-file-store configuration is persistent which means in case of application restart or crash, the data been cached will no be lost.

Image title

Invalidating a Cache

Mule provides the InvalidatableCachingStrategy interface, which allows you to invalidate a complete cache or a cache key without the need for custom code or configuration.

There are two message processors for invalidating caches:

  invalidate-cache – Completely invalidates a cache. Must reference an invalidatable caching strategy.

<ee:invalidate-cache cachingStrategy-ref=”InvalidatableCachingStrategy”/>

invalidate-key – Calculates a cache key from the current event, then searches for it in the cache and removes it if present. Must reference an invalidatable caching strategy and, optionally, a MuleEventKeyGenerator. If no MuleEventKeyGenerator is provided, Mule uses the default implementation (SHA256MuleEventKeyGenerator).

<ee:invalidate-key cachingStrategy-ref=”InvalidatableCachingStrategy” keyGenerator-ref=”MD5MuleEventKeyGenerator”/>

Let’s walk through how to use Cache scope in mule application.
In this example flow “cachFlow” will be invoked through REST client . All of the steps including message processor’s in the cache scope will be executed for the first request made for ID= 1 and response will be returned to the user. The same will be stored in a cache which will be used to return response hereafter for all of the subsequent requests made for the same ID without executing the message processor in the cache scope.

Flow :

Image title

Code:

<?xml version=”1.0″ encoding=”UTF-8″?>
<mule xmlns:dw=”http://www.mulesoft.org/schema/mule/ee/dw&#8221;
xmlns:db=”http://www.mulesoft.org/schema/mule/db&#8221;
xmlns:core=”http://www.mulesoft.org/schema/mule/core&#8221;
xmlns:http=”http://www.mulesoft.org/schema/mule/http&#8221; xmlns:cxf=”http://www.mulesoft.org/schema/mule/cxf&#8221;
xmlns:ee=”http://www.mulesoft.org/schema/mule/ee/core&#8221; xmlns=”http://www.mulesoft.org/schema/mule/core&#8221;
xmlns:doc=”http://www.mulesoft.org/schema/mule/documentation&#8221;
xmlns:spring=”http://www.springframework.org/schema/beans&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://www.mulesoft.org/schema/mule/ee/dw http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd
http://www.mulesoft.org/schema/mule/db http://www.mulesoft.org/schema/mule/db/current/mule-db.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/cxf http://www.mulesoft.org/schema/mule/cxf/current/mule-cxf.xsd
http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd”&gt;

<ee:object-store-caching-strategy
name=”CacheStrategy” doc:name=”Caching Strategy” keyGenerationExpression=”#[flowVars.id]”>
<in-memory-store name=”inMemooryStore” maxEntries=”200″ entryTTL=”20000″ expirationInterval=”20000″/>
</ee:object-store-caching-strategy>
<db:generic-config name=”Generic_Database_Configuration”
url=”jdbc:hsqldb:hsql://localhost:9001″ driverClassName=”org.hsqldb.jdbcDriver”
doc:name=”Generic Database Configuration” />
<http:listener-config name=”HTTP_Listener_Configuration”
host=”localhost” port=”8081″ basePath=”/cache” doc:name=”HTTP Listener Configuration” />

<flow name=”cacheFlow”>
<http:listener config-ref=”HTTP_Listener_Configuration”
path=”/cache” doc:name=”HTTP” />
<byte-array-to-string-transformer
doc:name=”Byte Array to String” />
<set-variable variableName=”id” value=”#[message.inboundProperties.’http.query.params’.id]” doc:name=”Variable”/>
<logger level=”INFO” message=”#[flowVars.id]” doc:name=”Logger”/>
<ee:cache doc:name=”Cache” cachingStrategy-ref=”CacheStrategy”>
<logger level=”INFO” message=”Before calling the GET Flights Info” doc:name=”Logger” />
<db:select config-ref=”Generic_Database_Configuration”
doc:name=”Save to fgwy_user_role”>
<db:dynamic-query><![CDATA[select id,name from employee where id=’#[flowVars.id]’]]></db:dynamic-query>
</db:select>
<logger level=”INFO” message=”After calling the GET Flights Info” doc:name=”Logger” />
</ee:cache>
<dw:transform-message doc:name=”Transform Message”>
<dw:set-payload><![CDATA[%dw 1.0
%output application/json

payload map ((payload01 , indexOfPayload01) -> {
id: payload01.id,
name: payload01.name
})]]></dw:set-payload>
</dw:transform-message>
<logger level=”INFO” message=”#[payload]” doc:name=”Logger” />
</flow>
</mule>

 

Request URL:

http://localhost:8081/cache/cache?id=1

Image title

Hope this helps

Thanks

Ankit Lawaniya

Content Enrichment Using Mule Message Enricher Component

Content Enrichment Using Mule Message Enricher Component

Mule Message Enricher is one of the scope in Mule which allows the current message to be augmented using data from the separate resource which we call it as Enrichment resource.The Mule implementation of the Enrichment Resource (a source of data to augment the current message) can be any Message Processor .

In simple language, we can say a message enricher enrich the current payload with some additional message or information and this is done without disturbing the current payload.

Enricher is used if the target system needs more information than the source system can provide. It enriches the mule message by calling external system or do some transformation to existing payload and save it into some scope of variable like session or outbound or invocation and the transformation happened in en-richer scope doesn’t affect the actual payload. Set-property: Save some information extracted from payload or original payload to some invocation or flow scope variable.

Image title

Now, for example ,

Example 1: If in your flow, if you need to call a external service with HTTP outbound/HTTP request component in middle of the flow, After getting the response from the HTTP external service call you will find that , your current payload is modified with the response of the external service but you don’t wanted to change or disturb the existing payload ,In that case we can wrap our HTTP outbound/HTTP request component inside enricher and it will make a call to external system, store the result and your existing payload will not be modified.

Example 2: We call a web service and after getting the response either the complete response or one value  we can extract from the response and keep it in the variable which will e added to the original payload.

Use Cases:

The Mule Message Enricher is designed for performing interactions like calling an outbound endpoint and bringing the result back to the main flow ,which will be used to add the additional information in the existing payload.

One common scenario involves the need to enrich an incoming message with information that isn’t provided by the source system. You can use a content enricher if the target system needs more information than the source system can provide.

Mule message Enricher allows the current message to be used in performing a particular task separately without disturbing the original message.Mule message enricher is best used in the case when you do not to lose your existing payload.

How Does Message Enricher Work?

Below are the step by step process to demonstrate how message Enricher works.

  •    Enricher sends a copy of the original message into the processor.
  •     The original message waits.
  •     The copy is processed.
  •     The copy’s response is a message.
  •     Part(s) of the response are added to part(s) of the original message.
  •     The enriched message moves forward.

The way in which the message is enriched (or modified) is by explicitly configuring mappings (source->target) between the result from the Enrichment Resource and the message using Mule Expressions. Mule Expression are used to both select the value to be extracted from the result that comes back from the Enrichment Resource (source) and to define where this value to be inserted into the message (target). The default source, if not configured, is the payload of the result from the Enrichment Resource.

The “enrichment resource” can be any message processor, outbound connector, processor-chain or flow-ref.  If using an outbound-connector then of course it should have a request-response exchange pattern.

IMP Note:

As only one component can reside inside Message Enricher. Use of processor chain is recommended if more components are needed to reside inside Message Enricher.

Let’s walk through how to use Mule Message Enricher in application.
In this example we are receiving the JSON Request consisting Employee data with id and role of the employee through HTTP call from the REST client.  Our objective here is to add the additional information which is the name of the employee to the source data. For this we will be calling Database to get the information about the employee name and that will be added in the source JSON to be sent back to the user .

Flow :Image title

Code :

<?xml version=”1.0″ encoding=”UTF-8″?>
<mule xmlns:dw=”http://www.mulesoft.org/schema/mule/ee/dw&#8221;
xmlns:db=”http://www.mulesoft.org/schema/mule/db&#8221; xmlns:http=”http://www.mulesoft.org/schema/mule/http&#8221;
xmlns:ee=”http://www.mulesoft.org/schema/mule/ee/core&#8221; xmlns:cxf=”http://www.mulesoft.org/schema/mule/cxf&#8221;
xmlns=”http://www.mulesoft.org/schema/mule/core&#8221; xmlns:doc=”http://www.mulesoft.org/schema/mule/documentation&#8221;
xmlns:spring=”http://www.springframework.org/schema/beans&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://www.mulesoft.org/schema/mule/db http://www.mulesoft.org/schema/mule/db/current/mule-db.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd
http://www.mulesoft.org/schema/mule/cxf http://www.mulesoft.org/schema/mule/cxf/current/mule-cxf.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/ee/dw http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd”&gt;
<db:generic-config name=”Generic_Database_Configuration” url=”jdbc:hsqldb:hsql://localhost:9001″ driverClassName=”org.hsqldb.jdbcDriver”
doc:name=”Generic Database Configuration” />
<http:listener-config name=”HTTP_Listener_Configuration” host=”localhost” port=”8081″ basePath=”/enricher” doc:name=”HTTP Listener Configuration” />
<flow name=”messageEnricherFlow”>
<http:listener config-ref=”HTTP_Listener_Configuration” path=”/enricher” doc:name=”HTTP” />
<byte-array-to-string-transformer doc:name=”Byte Array to String” />
<logger level=”INFO” message=”Printing id #[json:id]” doc:name=”Logger” />
<enricher doc:name=”Enricher”>
<db:select config-ref=”Generic_Database_Configuration” doc:name=”Select * from Employee”>
<db:dynamic-query><![CDATA[select name from employee where id=’#[json:id]’]]></db:dynamic-query>
</db:select>
<enrich target=”#[sessionVars.name]” source=”#[groovy:payload[0].name]” />
</enricher>
<set-payload value=”#[payload]” mimeType=”application/json” />
<logger level=”INFO” message=”#[payload]” doc:name=”Logger” />
<dw:transform-message doc:name=”Transform Message”>
<dw:set-payload><![CDATA[%dw 1.0
%output application/json

{
“id” : payload.id,
“name” : sessionVars.name,
“Role”: payload.role
}]]></dw:set-payload>
</dw:transform-message>

</flow>
</mule>

Request:

{
“id”: 1,
“role”: “Application Developer”
}

Response:

{
“id”: 1,
“name”: “Ankit”,
“Role”: “Application Developer”
}

Image title

Hope this helps.

Thanks

Keep Learning

Schema Validation Filter (XML Schema validation)

Schema Validation Filter (XML Schema validation)
The Schema Validation filter takes XML inputs and validates these against a referenced XSD schema.Typically, we’ll place it in starting of the mule flow,to determine whether the incoming message or event should be handled or not, allowing the message to only continue on along the flow when the filter validations are met and the included XML is considered valid.Schema Validator is provided out of the box with Mule.

Use Case:
A common use case Mule ESB flows is validating if an XML document is valid against a corresponding XSD so we can make sure we are receiving the correct XML and will forward it for the further processing.

Syntax:
<mulexml:schema-validation-filter schemaLocations=”src/main/resources/File/Process/Schema.xsd” returnResult=”true” name=”OrderData_Schema_Validation”
doc:name=”Schema Validation” />

The ‘standard’ way of Validating XML schema in Mule is by using the schema-validation-filter and especially in combination with the message-filter.
In the case when you want to get an exception and/or call another flow when the validation fails, you could wrap the schema validation filter inside a message filter and then use “onUnaccepted” and “throwOnUnaccepted” configuration attributes to determinate the behavior.
Here we have wrap the schema-validation-filter in a message-filter and set throwOnUnaccepted to “true”

Syntax:
<message-filter throwOnUnaccepted=”true” >
<mulexml:schema-validation-filter schemaLocations=”/File/Process/Schema.xsd” returnResult=”true” name=”OrderData_Schema_Validation”
doc:name=”Schema Validation” />
</message-filter>

Note: schmaLocations attribute accepts a comma separated list of schemas to validate the payload against.

Passing the XML Forward
In order to allow a valid XML to pass the filter you need to set the returnResult to false in your schema-validation-filter. This way the payload of the message that is passed onward to the next element in your flow will retain the XML content.

Let’s walk through how to use All Validator in Mule application.
In this example we are receiving the XML file through file inbound endpoint which will be validated against an XSD schema file defined in the application.If validation fails then we are catching the exception and printing the “Schema Not Validated” message along with the exception.

Flow:

SchemaValidationFLow

Code:
<mule xmlns:encryption=”http://www.mulesoft.org/schema/mule/encryption&#8221; xmlns:filters=”http://www.mulesoft.org/schema/mule/filters&#8221; xmlns:mulexml=”http://www.mulesoft.org/schema/mule/xml&#8221;
xmlns:file=”http://www.mulesoft.org/schema/mule/file&#8221;
xmlns:json=”http://www.mulesoft.org/schema/mule/json&#8221; xmlns:http=”http://www.mulesoft.org/schema/mule/http&#8221; xmlns=”http://www.mulesoft.org/schema/mule/core&#8221; xmlns:doc=”http://www.mulesoft.org/schema/mule/documentation&#8221;
xmlns:spring=”http://www.springframework.org/schema/beans&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://www.mulesoft.org/schema/mule/xml http://www.mulesoft.org/schema/mule/xml/current/mule-xml.xsd
http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd
http://www.mulesoft.org/schema/mule/filters http://www.mulesoft.org/schema/mule/filters/current/mule-filters.xsd
http://www.mulesoft.org/schema/mule/encryption http://www.mulesoft.org/schema/mule/encryption/current/mule-encryption.xsd”&gt;
<flow name=”SchemaValidationFLow” >
<file:inbound-endpoint path=”src/main/resources/File/Process/input” responseTimeout=”10000″ doc:name=”File” moveToDirectory=”src/main/resources/File/Process/output” >
<file:filename-wildcard-filter pattern=”*.xml” caseSensitive=”false”/>
</file:inbound-endpoint>
<file:file-to-string-transformer doc:name=”File to String” />
<mulexml:dom-to-xml-transformer doc:name=”DOM to XML” />
<message-filter throwOnUnaccepted=”true” doc:name=”Message”>
<mulexml:schema-validation-filter schemaLocations=”src/main/resources/File/Process/Schema.xsd” returnResult=”true” name=”OrderData_Schema_Validation”
doc:name=”Schema Validation” />
</message-filter>
<logger message=”Validation successful: #[message.payload]” level=”INFO” doc:name=”Logger” />
<catch-exception-strategy doc:name=”Catch Exception Strategy”>
<logger level=”INFO” message=”Schema Not Validated” doc:name=”Logger”/>
</catch-exception-strategy>
</flow>
</mule>

XSD Schema :

src/main/resources/File/Process/Schema.xsd
<?xml version=”1.0″ encoding=”UTF-8″ ?>
<xs:schema xmlns:xs=”http://www.w3.org/2001/XMLSchema”&gt;
<xs:element name=”shiporder”>
<xs:complexType>
<xs:sequence>
<xs:element name=”orderperson” type=”xs:string”/>
<xs:element name=”shipto”>
<xs:complexType>
<xs:sequence>
<xs:element name=”name” type=”xs:string”/>
<xs:element name=”address” type=”xs:string”/>
<xs:element name=”city” type=”xs:string”/>
<xs:element name=”country” type=”xs:string”/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name=”item” maxOccurs=”unbounded”>
<xs:complexType>
<xs:sequence>
<xs:element name=”title” type=”xs:string”/>
<xs:element name=”note” type=”xs:string” minOccurs=”0″/>
<xs:element name=”quantity” type=”xs:positiveInteger”/>
<xs:element name=”price” type=”xs:decimal”/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name=”orderid” type=”xs:string” use=”required”/>
</xs:complexType>
</xs:element>
</xs:schema>

Success Sample XML :

src/main/resources/File/Process/input/order.xml
<?xml version=”1.0″ encoding=”UTF-8″?>
<shiporder orderid=”889923″
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:noNamespaceSchemaLocation=”shiporder.xsd”>
<orderperson>John Smith</orderperson>
<shipto>
<name>Ola Nordmann</name>
<address>Langgt 23</address>
<city>4000 Stavanger</city>
<country>Norway</country>
</shipto>
<item>
<title>Empire Burlesque</title>
<note>Special Edition</note>
<quantity>1</quantity>
<price>10.90</price>
</item>
<item>
<title>Hide your heart</title>
<quantity>1</quantity>
<price>9.90</price>
</item>
</shiporder>

Now in the above XML if we change the any of the element against the schema defined ,we will be getting the below exception.

Exception:

ERROR 2017-08-08 21:01:19,585 [[schemavalidation1].SchemaValidationFLow.stage1.02] org.mule.exception.CatchMessagingExceptionStrategy:
********************************************************************************
Message : Message has been rejected by filter.
Filter : org.mule.module.xml.filters.SchemaValidationFilter@39c5e4bb (null)
Payload : <?xml version=”1.0″ encoding=”UTF-8″?>
Element XML : <message-filter throwOnUnaccepted=”true” doc:name=”Message”>
<mulexml:schema-validation-filter schemaLocations=”src/main/resources/File/Process/Schema.xsd” returnResult=”true” name=”OrderData_Schema_Validation” doc:name=”Schema Validation”></mulexml:schema-validation-filter>
</message-filter>
Payload Type : org.apache.xerces.dom.DocumentImpl
Element : /SchemaValidationFLow/processors/2 @ schemavalidation1:schemavalidation1.xml:23 (Message)
——————————————————————————–
Root Exception stack trace:
org.mule.api.routing.filter.FilterUnacceptedException: Message has been rejected by filter.

Hope this helps

Thanks
Keep Learning

Validation Module in Mule

Validation Module in Mule

The Validations module provides an easy out-of-the-box way to verify that the content of a message in your flow matches a given set of criteria.

Difference between Mule Filter’s Component and Validation Module
The main advantage of Validation Module over using Filters is traceability, as filters all raise identical exceptions, making it hard for us to know where the exception was caused.So if we have two filters in the same flow we cannot know which one failed and we cannot customize the exception type. Validators, on the other hand, raise an exception with a meaningful message attached and also we can customize the exception type..

Note: This feature is supported by the Mule run-time as of Mule ESB 3.7.0 in both Community and Enterprise editions.

The validations module was designed following these principles:
• If the message doesn’t meet the specified criteria, the validation fails and a ValidationException is thrown.
• By default, this exception has a meaningful message attached. You can optionally customize this message and change the type of exception thrown, as long as the new exception type has a constructor that overrides Exception(String).
• In case you want to throw an Exception type that lacks this constructor, or in which its creation is not trivial, or in which you want it to contain additional information.

How To use Validator
There are two ways of using a validator: through a Message Processor or through a MEL function.

Types of built-in validator

Below is not the complete list of Validator , please refer mule soft article on Validation component for the complete list.

Email Address Validator
<validation:is-email email=”#[json:email]” />

Regular Expression Validator
<validation:matches-regex value=”#[json:Name]” regex=”/^[A-z]+$/” message=”Name can not contain Integer value” />

Not Empty check Validator
<validation:is-not-empty value=”#[json:employeeId]” message=”Employee Id is mandatory to supply” />

Size Validator
<validation:validate-size value=”#[json:age]” min=”2″ max=”3″ message=”Please provide correct age” />

Not Null Validator
<validation:not-null expression=”#[value]” value=”#[payload]” />

Number Validator
<validation:is-number value=”#[json:Id]” numberType=”INTEGER” message=”ID can not be String or any other data Type” />

How to validate many conditions at once?
There are scenarios in which you may want to evaluate several conditions, out of which more than one could fail simultaneously. In these cases, it’s ideal to generate a single error that contains all of the descriptions.

And the solution is All validator.

Let’s walk through how to use All Validator in Mule application.
In this example we are receiving the JSON Request through HTTP call from the REST client which will be validated against the ALL Validator Component.

Mule Flow:

ValidationComponent flow

Code:

<?xml version=”1.0″ encoding=”UTF-8″?>
<mule xmlns:json=”http://www.mulesoft.org/schema/mule/json&#8221;
xmlns:http=”http://www.mulesoft.org/schema/mule/http&#8221; xmlns:validation=”http://www.mulesoft.org/schema/mule/validation&#8221;
xmlns=”http://www.mulesoft.org/schema/mule/core&#8221; xmlns:doc=”http://www.mulesoft.org/schema/mule/documentation&#8221;
xmlns:spring=”http://www.springframework.org/schema/beans&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/validation http://www.mulesoft.org/schema/mule/validation/current/mule-validation.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd”&gt;
<http:listener-config name=”HTTP_Listener_Configuration”
host=”localhost” port=”8081″ basePath=”/validation” doc:name=”HTTP Listener Configuration” />
<validation:config name=”Validation_Configuration”
doc:name=”Validation Configuration” />
<flow name=”ValidationComponent”>
<http:listener config-ref=”HTTP_Listener_Configuration”
path=”/validation” doc:name=”HTTP” />
<byte-array-to-string-transformer
doc:name=”Byte Array to String” />
<validation:all config-ref=”Validation_Configuration”
doc:name=”Validation”>
<validation:validations>
<validation:is-number value=”#[json:id]”
numberType=”INTEGER” message=”ID can not be String data Type” />
<validation:is-not-empty value=”#[json:account]”
message=”Account Number Required” />
<validation:matches-regex value=”#[json:name]”
regex=”^[a-zA-Z]+$” message=”Name can not contain Integer value and other special charectors” />
<validation:validate-size value=”#[json:age]”
min=”2″ max=”3″ message=”Please provide correct age” />
<validation:is-email email=”#[json:email]” />
</validation:validations>
</validation:all>
<logger level=”INFO” message=”Validation Successful” doc:name=”Logger”></logger>
</flow>
</mule>

Success Request:

{
“id”: 123,
“account”: 1234,
“name”:”Ankit”,
“age”: 24 ,
“email” :”ankit.lawaniya@live.com”
}

success use case

Failed Request:
{
“id”: “dummyId”,
“account”: 12,
“name”:”Ankit1″,
“age”: 2 ,
“email” :”ankit.lawaniyalive.com”
}

failure use case

Below is the exception thrown for the validation failure.

Exception:
Root Exception stack trace:
org.mule.extension.validation.api.MultipleValidationException: ID can not be String data Type
Name can not contain Integer value and other special charectors
Please provide correct age
ankit.lawaniyalive.com is not a valid email address
at org.mule.extension.validation.internal.ValidationStrategies.all(ValidationStrategies.java:71)

Hope This Helps

Thanks
Keep Learning

Parse Template Transformer Mule

Parse Template Transformer Mule
The Parse Template component loads a file into the Mule payload.The ‘Parse Template’ transformer parses a template file that can contain MEL expressions and places the resulting string into the message payload.We can use the payload,flowVars and inboundProperties in the template to create the dynamic content.

Use Case 1:
When we want to prepare the payload to be used by the Web Service Consumer or for a SOAP request.

Use Case 2 :
When we want to create a template for emailing.

Use Case 3 :
There are other scenario’s where it can be useful , such as returning HTML to a client from an HTTP transport.We can load an HTML file into the payload that includes embedded MEL.

Samples of MEL that we can define in template.
#[message.inboundProperties.’http.query.params’.name]
#[flowVars.order_no]
#[payload[0][‘order_no’]]

Let’s walk through how to use JSON Schema validator in Mule application.
In this example we are receiving the order through HTTP call from the end user , We are using a parse template to load a file from an external location – a file which, behaving as a template, expects values for “order number” ,”Order Description” and “order provisioning date” .The parse template extracts info from the Mule message variables to insert as values into the template and set the resulting contents as the message payload.

Mule Flow:

parseTempateFlow

Code:
<?xml version=”1.0″ encoding=”UTF-8″?>

<mule xmlns:json=”http://www.mulesoft.org/schema/mule/json&#8221;
xmlns:http=”http://www.mulesoft.org/schema/mule/http&#8221;
xmlns:jms=”http://www.mulesoft.org/schema/mule/jms&#8221;
xmlns=”http://www.mulesoft.org/schema/mule/core&#8221; xmlns:doc=”http://www.mulesoft.org/schema/mule/documentation&#8221;
xmlns:spring=”http://www.springframework.org/schema/beans&#8221; version=”EE-3.8.1″
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”
http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/jms http://www.mulesoft.org/schema/mule/jms/current/mule-jms.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd”&gt;

<http:listener-config name=”HTTP_Listener_Configuration”
host=”localhost” port=”8081″ basePath=”/parse” doc:name=”HTTP Listener Configuration” />
<flow name=”parseTempate”>
<http:listener config-ref=”HTTP_Listener_Configuration” path=”/parse”/>
<set-payload mimeType=”application/json” value=”#[payload]” />
<json:json-to-object-transformer
returnClass=”java.lang.Object” doc:name=”JSON to Object” />
<parse-template location=”responseHtml.template”
doc:name=”Parse Template” />
<set-property doc:name=”Content Type” propertyName=”Content-Type”
value=”text/html” />
</flow>
</mule>

responseHtml.template

<html>
<body>
<table border=4>
<tr>
<th>Order No</th>
<th>Order Description</th>
<th>Provisioning Date</th>
</tr>
<tr>
<td>#[payload[0][‘order_no’]]</td>
<td>#[payload[0][‘order_description’]]</td>
<td>#[payload[0][‘provisioning_date’]]</td>
</tr>
</table>
</body>
</html>

Request:
[
{
“order_no” : “199”,
“order_description” : “PostpaidOrder”,
“provisioning_date” : “28/07/2017”
}
]

Response:

responsescreesnhot

Thanks

Keep Learning

 

Design a site like this with WordPress.com
Get started