Tuesday, June 21, 2016

Mule Controlling Message Flow

Mule Controlling Message Flow



 About flow control and filter elements.
To multicast a message.
To route message based on conditions.
To filter messages.
About synchronous and asynchronous flows.

To create an asynchronous flow.

Walkthrough 8-1: Multicast a message
In this walkthrough, you will create one flow that calls each of the three airline services and combines
and returns the results back to the web form. You will:
• Use a Scatter-­Gather router to concurrently call all three flight services.
• Use a Combine Collections transformer to combine a collection of three ArrayLists of objects
into one collection.
• Use DataWeave to sort the flights and return them as JSON to the form.













Add a router to call all three airline services
1. Return to getFlights.xml.
2. Add a Scatter-­Gather flow control element before the Flow Reference in getFlightsFlow.
3. Drag the Flow Reference component into the Scatter-­Gather router.










4. Add a second Flow Reference component to the Scatter-­Gather router.
5. In the Properties view for the Flow Reference, set the flow name to getDeltaFlightsFlow.
6. Add a third Flow Reference component to the Scatter-­Gather router.



7. In the Properties view for the Flow Reference, set the flow name to getAmericanFlightsFlow.
8. Add a breakpoint to the Set payload and destination flowVar component.
9. Add a breakpoint to the Logger.
10. Save the file.




Test the application
11. Debug the application.
12. Make a request to http://localhost:8081/flights and submit the form.
13. Step through the application to the Logger;; you should step through each of the airline flows.
14. Look the Mule Debugger view and see what the data type of the payload is after the router.




15. Click the Resume button.


Flatten the results
16. Add a Combine Collections transformer before the Logger.






Test the application
17. Save the file to redeploy the application.
18. Make a request to http://localhost:8081/flights and submit the form.
19. Step through the application to the Logger after the router;; you should see the payload is now
one ArrayList of HashMaps.


20. Step through to the end of the application;; you should see a jumble of data returned.



Review HTML form code to see what data format it expects
21. Open FlightFinder.html in src/main/resources and locate in what format it expects the data to be
sent back.




Return the data as JSON and sort by price
22. In getFlights.xml, add a Transform Message component after the Combine Collections
transformer.
23. Change its name to Java to JSON



24. In the Java to JSON Properties view, change the output type to application/json.
25. Write a DataWeave expression to transform the payload and order by price.


Test the application
26. Save the file and run the application.
27. Make a request to http://localhost:8081/flights and submit the form;; you should see SFO flights
for all three airlines returned and the flights should be sorted by price.



28. Submit the form for different destinations;; flights for SFO are returned every time.
Use the destination in the airline flows
29. Locate the Set Destination transformer in the getAmericanFlightsFlow.
Note: There are two options at this point: 1) to remove the HTTP endpoints and Set Destination
transformers from each of the airline flows or 2) to use a more complicated expression to check
and see if a destination flow variable already exists so that the individual airline flows can still be
called and tested individually.


30. Modify the value so it only uses the expression to set the destination flowVars variable if it does
not already exist.
#[(flowVars.destination ==empty &&
message.inboundProperties.'http.query.params'.code == empty) ? 'SFO' :
(flowVars.destination != empty ? flowVars.destination :
message.inboundProperties.'http.query.params'.code)]
Note: This expression is located in the course snippets.txt file and can be copied from there.
31. Use the same expression in the Set Destination in getDeltaFlightsFlow and
getUnitedFlightsFlow.


Test the application
32. Save the file to redeploy the application.
33. Make a request to http://localhost:8081/flights and submit the form;; you should still see SFO
flights.
34. Submit the form for a different destination including LAX, CLE, or PDX;; you should see the
correct flights returned.




35. Submit the form for a destination of PDF or FOO;; you should get an error in the console but no
return error message to the form.
36. Submit the form for SFO, LAX, CLE, or PDX and a different airline;; you should still see flights for all three airlines returned.

Wednesday, June 15, 2016

MULE ESB JMS

MULE ESB JMS

• Message-oriented middleware:
- aka "Enterprise Messaging"
• Allows for exchange of data and events:
- supports creation of message-based applications
• Messages can be sent/received asynchronously:
- supports loosely-coupled middleware
• Messages can participate in transactions
• API defined by the JMS standard
- multiple implementations
- WebLogic, WebSphere, MQSeries, ActiveMQ

- each implementation has its own server & client libs

JMS messaging models


• Standard queue concept
• First in, first out (FIFO)
• Single Consumer, potentially many Producers
• VM one-way endpoint acts as simple in memory Queue



• Publish/Subscribe mechanism
• Multiple subscribers allowed
• Messages published while subscribers disconnected
• Similar to RSS feeds

JMS elements in Mule

Types of JMS element

  •    JMS connector
  •    JMS endpoints
  •    JMS transformers
  •    JMS selector
JMS transport package supports JMS elements

JMS elements in Mule Studio


 Connect to any JMS-compliant server:
- org.mule.transport.jms for JMS transport protocol
- some servers require specific configuration
• Read & write JMS messages:
- message models
∙ can consume from both queues and topics
∙ can produce or publish to both queues and topics
- message serialization
∙ serialize data automatically
∙ de-serialize data on demand
• EE only:
- enhanced support for WebSphereMQ, including transactions

JMS connector in Mule Studio



JMS inbound endpoint in Mule Studio


JMS transformers in Mule Studio


JMS selectors in Mule

• JMS-specific filters
• Added in XML only

<jms:inbound-endpoint queue="myQueue">
<jms:selector expression="JMSPriority=9" />
</jms:inbound-endpoint>

• Can access JMS header properties
• Filter applied before message is de-queued
- non-matching messages remain available on queue

Backchannel


• JMS does not provide backchannels automatically or by default
• A Mule application must create its own backchannel using JMS
queue features built into Mule elements
• Two options for element:
1. outbound endpoint with request-response exchange
pattern
∙ just as with HTTP or VM transports
2. using <request-reply> message processor in XML
∙ gives more explicit control over message routing
-. each has pros and cons (see next)
• The "reply-to" header tells Mule where to send a response
-. e.g. JMS_REPLY_TO="jms://myResponseQueue"
-. responses are sent after the message has finished processing
• JMSCorrelationId ensures proper sequencing

Request-response JMS endpoints

Request-reply message processor


MULE ESB REST Web Services

MULE ESB REST Web Services

• Creating a JAX-RS resource
• Deploying a JAX-RS resource
• Consuming a REST resource

• JSON capabilities in Mule

What is REST?

• REpresentational State Transfer (REST)
• Architectural style for a well-designed (RESTful) hypertext application
• Design of the Web supports the REST architectural style
• REST applies to client–server architecture:
- resources are found on a server
- client requests a "representation" of a resource’s current state
• Every resource has a URI (similar to web pages)
• REST methods are conceptual and general, but use same names as methods in HTTP:
- GET | PUT | POST | DELETE

JAX-RS

• Annotation-based API for creating RESTful services
• Maps a POJO to a resource
• Part of J2EE
• There are a number of implementations:
- Jersey
- Restlet
- RESTEasy (JBoss project)
• Jersey is Oracle’s reference implementation:

- used by Mule

JAX-RS Annotations

• Specify path of resource (the resource’s URI):
- @Path placed on class or method
• Specify REST method (request type):
- @GET|@PUT|@POST|@DELETE placed on method
• Specify return MIME type (e.g. text/html or application/json):
- @Produces placed on method
• Specify accepted request types:
- @Consumes placed on method
• Specify parameters:
- @PathParam gets parameter from URI
- @QueryParam gets parameter from query string (?x=1&y=2)
- @HeaderParam gets parameter from HTTP header

Creating JAX-RS Resource

• import javax.ws.rs.GET;
• import javax.ws.rs.Path;
• import javax.ws.rs.PathParam;
• import javax.ws.rs.Produces;
• @Path("/")
• public class HelloRestComponent {
• @GET
• @Produces("text/plain")
• @Path("/greeting/{name}")
• public String greet(@PathParam("name") String input)
• {
• return "Hello "+ input;
• }
• }
Creating JAX-RS Resource


http://localhost:8080/{endpointpath}/{classpath}/{methodpath}/{value}

Deploying Jersey Resource





Consuming a RESTful Web Service





JSON Support

• Jersey:
- Specify @Produces/@Consumes (application/json)
• JSON module:
- uses Jackson to support binding JSON data to objects
- JSON to Object transformer:
∙ set returnClass attribute
∙ JSON engine can be configured with jsonConfig attribute
- Object to JSON transformer:
∙ a map of JSON object attributes can be configured using mapper-ref attribute, usually default is enough
• Querying JSON payloads with JSONPath:
- similar to how XPath can query XML documents

Resources

• Using Mule with Web Services documentation
http://www.mulesoft.org/documentation/display/current/Using+Mule+with+Web+
Services

• REST Component Reference documentation
http://www.mulesoft.org/documentation/display/current/REST+Component+Reference

Friday, June 10, 2016

Mule ESB Data Mapper

Mule ESB DataMapper

Complex data mapping using drag a and drop interface

• Scripting support (MEL, XPath, and CTL2)
• Live, design-time previews for transformation results

• DataSense support for automatic metadata discovery




DataMapper Data Formats

• Support for
- XML and JSON
- CSVs, MS Excel, Fixed Width
- Pojo, Map<k,v>
- Connector

DataSense enabled
- Connector attributes are picked up automatically
- When DataSense is enabled





Input Arguments


Allows us to evaluate mule expressions
and map those to metadata or output arguments

• Great for accessing properties and
variables during mapping
















DataMapper Implementation



Wednesday, June 8, 2016

MULE JSON Transformers


MULE JSON Transformers

JSON Primer

 JavaScript Object Notation is a lightweight data inter change format
                     
Human-Readable Syntax   [ element1, element2, element3..... ]

• Supports
1. Collections

2. Maps                                                  { "name1":"value", "name2":"value" }

JSON Transformer

• Object to JSON - receives an object and returns JSON syntax  

- uses reflection (no configuration necessary)








• JSON to Object - populates a Java object from a JSON structure

- requires at least the name of the class


JSON Example

1. JSON input enters with an order request
2. Order business logic exists in a java component                
3. After processing, a response comes back with the tax included






• XML to JAXB

- Uses the JAXB binding framework to serialize to xml or in reverse to an object

- Counterpart exists at JAXB to XML

• XML to Object

- Utilizes Xstream to convert data to and from XML and Java Objects

- Counterpart exists as Object to XML




Tuesday, June 7, 2016

Mule Transforming Data

Mule Messages





Payloads are Java Objects

• This means, a Payload can be any Java Type
• The focus of this module will be how we change between types and
prepare a message for delivery / future processing



Goal:
- Determine desired type
- Determine our input type(s)
- Implement the correct transformer

Common Transformation Attributes

returnClass           • Optionally a specify return type
                            • Useful for more specific types than the default
                                    - Example: an extension class

IgnoreBadInput     • Turns off the processing of messages with bad input
                            • Message is returned as it was before engaging the transformer

Encoding               • Specify encoding

MIME Type          • Explicitly set internet media type

                                    - text/html, text/csv, text/xml.

Transformer Flow




Transformer Example




1. Mule Message comes in on a VM Endpoint
2. Core transformer turns the byte array into an object (based on the return
class attribute via deserialization
3. Message is passed to a Java Component implementing business logic






• There exists multiple ways of handling > 1 input type
- Routers, Filters, etc
• Limiting ourselves to just one transformer, how could we
dynamically transform messages coming to a desired type?



• Searches for a transformer per the returnClass
• Transformers implementing
com.mule.api.transformer.DiscoverableTransformer are searched.

MULE Flows, Sub Flows and Private Flows

Mule Flow, Sub Flows and Private Flows