Mule Esb 3 Tutorial

March 26, 2018 | Author: Ashutosh Mishra | Category: Html, Areas Of Computer Science, Digital & Social Media, Digital Technology, Computer Engineering


Comments



Description

MueE B3T tr l l S uoi a1. Home . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.1 Creating an Application Using the Mule IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.2 Creating an Application Using Maven . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.3 Creating a Configuration File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.4 Testing Your Mule Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.5 Introducing Message Routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.6 Understanding Advanced Message Routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 2 5 6 11 13 16 If you would like to use the Mule IDE with these features. Mule IDE 2. Read this topic to learn the basics of how to do this. or just create a new configuration file by selecting the transports you want to use. It also covers advanced topics such as developing Mule applications using Maven and using advanced message routing. and creating a new configuration file for the project. It covers the essentials. Creating Configuration Files Creating configuration files is at the heart of Mule development. please see the documentation on Hot Deployment using the Mule IDE. this topic is a must-read. which you can base on one of the existing examples. lesser-known methods of message routing with Mule. Working with Maven Maven can help you develop Mule applications. such as using the Mule IDE. The Mule IDE allows you to quickly start a new project. Using the Mule IDE If you're curious about how to use the Mule IDE.1 is required to support Mule 3 but Mule 3's new Application Model and Hot Deployment capabilities are not yet natively supported by the Mule IDE. How to Test Your Application Testing is part and parcel of application development. Message Routing If you are ready to start moving data around your Mule application. so if you are ready to plunge into this new world. routing messages. and testing your application. Read this topic to learn some of the deeper. This lesson walks you through creating a new application called myHelloApp. which will be based on the Hello World Example. this topic will help you get started with this tool. Creating an Application Using the Mule IDE Creating an Application Using the Mule IDE [ Create the Application ] [ Run the Application ] [ Create a Configuration File for the New Application ] [ Use Eclipse Tools for Adding Elements ] [ Package and Deploy the JAR and Configuration File ] The simplest way to create an application in Mule ESB is to use the Mule IDE with Eclipse.Home Mule ESB 3 Tutorial This book provides a tutorial on how to develop Mule ESB 3 applications. writing a configuration file. Learn the Mule approach to testing here. Advanced Message Routing Routing messages can get complicated. running the application. Create the Application 1. this topic will help you understand the basics. . expand the Mule folder and select Mule Project.. how are you?" If you get any other response. as long as it is unique within the project and has an . Change the default name from mule-config. 2. initializing Mule. If you use the name of an existing file. 2.1..xml extension. . In Eclipse Workbench. it will overwrite that file. open a web browser with this url: http://localhost:8888?name=Ross The server should respond with "Hello Ross.xml. You can expand its folders to see the source code. Run the Application 1. A new run configuration is created automatically and the server is started. expand the myHelloApp project. and then click Next. After the Mule splash screen appears in the console window. You can use any name you like. 3. Let's run the application to see it in action. The application runs. we'll call the new configuration file my-hello-config.xml to my-hello-config. Create a Configuration File for the New Application Now let's create a new configuration file for the myHelloApp. and more. and then click Next. leave Spring Config selected. 4.xml. let's change the configuration to use the System I/O (also called STDIO) and VM transports. Choose Run As > Mule Server. For simplicity. Choose File > New > Other. You will now see the myHelloApp project in the navigation pane on the left. and right-click the mule-config.xml configuration file. Click Browse. 4. Instead of using the HTTP and Servlet transports and a browser to interact with the application.. and then click Finish. and then click OK. 2. select the src/main/app directory. Click Finish to have the Mule IDE generate your project. 3. Click Add sample project content and select the Hello example. 2. check the log in the console window for any errors. expand the src/main/app directory. Select the System I/O (also called STDIO) and VM transports. Click Next. Ensure that Mule 3 is your default Mule distribution or selected as the project specific one. Enter the name myHelloApp. ensuring that there is no space in the project name. 1. and then click the Libraries tab and verify that the Java 5 or later library is installed and available on the build path. 1. choose File > New > Project. configuration files. In the Package Explorer. expand the Mule folder and select Mule Configuration. You can also hover over a tag to see a description of the element and its supported attributes. Simply click anywhere between the opening and closing tags of an element.StdinToNameString"/> Append or replace the http and servlet inbound endpoints in the Hello World flow with a stdio one (if you append it. filters. and then add local routers. Double-click the element in the list that you want. It adds the namespaces for the STDIO and VM transports. Use Eclipse Tools for Adding Elements Now we'll use the Eclipse tools to add elements to the new configuration file.hello.mule. endpoints.xml example configuration to your new configuration file. copy the body (the content below the namespace declarations) of the default mule-config. You can add services within a <model> element.example. Eclipse provides a fast and error-proof method for entering these elements. which are at the top of the file. make sure you also declare the applicable namespaces for http and servlet transports): <stdio:inbound-endpoint system="IN" exchange-pattern="one-way"> <transformer ref ="StdinToNameString"/> </stdio:inbound-endpoint> . and Eclipse enters the opening and closing tags for that element. and transformers to the services. To add System I/O so that you can interact with the application from the console.hello-example-messages" messageDelayTime="1000"/> <custom-transformer name="StdinToNameString" class="org. then press Ctrl+space to see a list of the available elements. Open the new configuration file in the Eclipse editor. Then make the following changes. You can add global elements anywhere below the namespace declarations. Add a connector configuration and declare another custom transformer for STDIN: <stdio:connector name="SystemStreamConnector" promptMessageCode="3" resourceBundle="messages.Mule IDE creates the configuration file in the src/main/app directory of the myHelloApp project. Add a stdio outbound endpoint to the Hello World flow between the choice element and the default exception strategy: <stdio:outbound-endpoint system="OUT" exchange-pattern="one-way"> <transformer ref="ChatStringToString" /> </stdio:outbound-endpoint> Package and Deploy the JAR and Configuration File After you have finished creating your Mule application.0.x are the recommended versions to use with Mule. Alternatively. please specify the http and vm tranports. you will execute the archetype and generate the code.mule. see Setting Up the Development Environment and Using Maven. and creating a new configuration file for the project.x and 2. For an explanation of these see the project archetype documentation. settings. Maven 2. you will need to do the packaging manually to conform to the Mule application format.tools</pluginGroup> </pluginGroups> . > mvn mule-project-archetype:create -DartifactId=myHelloApp -DmuleVersion=3. Maven will download the archetype for you.0 (beta) is not currently supported with Mule. which will be based on the Hello World Example. Creating an Application Using Maven Creating an Application Using Maven [ Create a New Project ] [ Build the Application ] Mule's integrated support for the Maven project management tool means that you can quickly and easily create a new Mule project right from the command line. If this is your first time running this command. Maven 3.2. Enter org/mule/example as the Java package path. Since the Mule IDE does not yet natively support the new deployment structure of Mule 3. For information on downloading.xml <settings> <pluginGroups> <pluginGroup>org. running the application. you can follow the instructions for Hot Deployment using the Mule IDE. Navigate to the parent directory where you want to create this new project.0 The wizard will ask you a number of questions. This lesson walks you through creating a new application called myHelloApp.0.. you can deploy it by packaging up the application in a JAR file and then copying the JAR and configuration file to your Mule instance(s). you must sdd the following to the file settings. </settings> Create a New Project We are going to create a new project called 'myHelloApp'. Mule provides a Maven archetype (project wizard) for creating new Mule projects. http. org/mule/example When you get to the transports question. Before you can use it. Next. installing and setting up Maven with Mule.m2 directory) so that Maven will allow you to execute Mule plug-ins.xml (usually in your Maven conf or $HOME/..vm . empty mule-config. we're using the HTTP and VM transports. You can now browse the myHelloApp project structure. you declare the namespace for the core Mule schema.java Build the Application mvn package This will build your project. Please enter at least one module name (note this is a limitation of the archetype. Although the easiest way to create a Mule configuration file is to use the Mule IDE as described in Creating an Application Using the Mule IDE. it will ask you which modules to include.0" encoding="UTF-8"?> Next. To get started. Mule will detect your application archive and automatically deploy it. create an empty Mule Project using the Mule IDE or Maven project archetype and open a new. You then use the XSI namespace to declare the locations of the schemas. For example: .xml --java/org/mule/example/myhelloapp/MyHelloAppTestCase. and construct a mule application archive named myhelloapp-1. In this example. You can then run Mule using this file and the compiled Java classes.0-SNAPSHOT.Next. It should look like this: myHelloApp --assembly.zip. in the <mule> element. you can repeat the last two steps for each instance. and the transports and modules you want to use.xml --java/org/mule/example/myhelloapp --src/test --resources/myhelloapp-functiona-test-config.xml file in your favorite editor. Creating a Configuration File Creating a Configuration File [ Add the XML Declaration and Namespaces ] [ Add the Description ] [ Configure Global Connectors ] [ Configure Global Custom Transformers ] [ Configure Models and Services ] [ Configure Error Handling ] [ Configure the Final Service ] [ View the Full Example ] [ Run the Application ] Creating a Mule ESB application is as simple as creating a configuration file and pointing to a Java class that performs any required custom logic on the messages that come through. To deploy your application to additional Mule instances.xml --MULE-README. the XML declaration goes at the top of the file: <?xml version="1.xml --pom. run the tests. Now just copy this archive to you {$MULE_HOME/apps} directory and start mule . Lesson Three provides you with the information you need to create the file manually in any XML editor or IDE and helps you understand all the elements involved. If there are any errors in your configuration you will need to correct the. Add the XML Declaration and Namespaces First.txt --src/main --resources/mule-config. Maven will now create a skeleton project structure for you. You will walk through creating a configuration file for the Hello World application. Spring. repackage and copy the archive over again. you must specify at least one item).{$MULE_HOME/bin/mule}. XSI. System error handling logs errors.w3. <description>The Hello World sample application has two components: 1. To see which attributes you can set for a connector. which you can then reference in multiple places. so you do not need to add the above connector to your configuration.hello-example-messages" messageDelayTime="1000"/> The example does not use the STDIO transport.mulesoft.mulesoft. User error handling returns an error message to the end user.xsd http://www.org/schema/beans/spring-beans-2. If we defined multiple STDIO connectors. the description could be about the entire application.xsd"> The HTTP transport will allow a user to interact with the application using any http client.xsd http://www. you can add the <description> element with a description of this configuration file. Add the Description Optionally.springframework. The ChitChatter component that adds some additional conversation to the message it receives A message is triggered by input through an http endpoint and the outbound message is also written out through the http response. If you are creating only one configuration file for your entire application. add them to the configuration now. including a web browser.mulesoft.mulesoft. if you want to configure custom transformers that you can reference from multiple places. For example. The <connector> element must be prefixed by the namespace of its transport. Configure Global Custom Transformers Similarly. you would use the connector-ref attribute on the endpoint to specify the one you want to use.0/mule.org/schema/mule/vm http://www.org/schema/beans" xmlns:http="http://www.springframework. we need a transformer that will convert it from an HTTP request to a name string. </description> Configure Global Connectors While there are several ways in Mule to configure a transport. Because we have only one connector defined for the STDIO transport.5.0/mule-http.org/2001/XMLSchema-instance" xmlns:spring="http://www.org/schema/mule/http" xmlns:vm="http://www.mulesoft. the following connector will be available to endpoints that use the STDIO transport: <stdio:connector name="SystemStreamConnector" promptMessageCode="3" resourceBundle="messages.org/schema/mule/vm" xsi:schemaLocation=" http://www.org/schema/mule/http/3.<mule xmlns="http://www.mulesoft.org/schema/mule/core http://www.org/schema/mule/core" xmlns:xsi="http://www.xsd http://www. The Hello World example includes a Java class that performs this transformation.0/mule-vm. the best practice is to use the <connector> element to define a global connector configuration.org/schema/beans http://www.org/schema/mule/http http://www.mulesoft.org/schema/mule/core/3. Because we're going to send the string through HTTP. this connector will be used by default whenever we create an STDIO transport.mulesoft.mulesoft.org/schema/mule/vm/3.springframework. go to the transport's reference page by clicking its name on the Available Transports page. The Greeter component that adds a greeting to the message it receives 2. which you configure as follows: . This configuration also demonstrates user and system error handling. example.example..myhelloapp.ico from being processed by the service. No connector is referenced so the default HTTP connector will be used.StringToNameString"/> <custom-transformer name="NameStringToChatString" class= "org.HttpRequestToNameString"/> It also uses several other transformers that format the message payload and convert it to the datatype expected by each component: <custom-transformer name="StringToNameString" class= "org.mule. Services are contained within models. so we specify the request-response pattern.<custom-transformer name="HttpRequestToNameString" class= "org.example.myhelloapp.. see the Service Configuration Reference. This inbound endpoint specifies that only messages that are received on http://localhost:8888 will be received by this service. Configure the Component . A filter is configured to explicitly exclude any request for the favicon.myhelloapp. Here we reference one of the global transformers we defined earlier in the configuration. start configuring your services by adding <service> tags with a name attribute that contains a unique name for the service.NameStringToChatString"/> <custom-transformer name="ChatStringToString" class= "org. it's HTTP. Where the message originates.mule. and they will be transformed by the HttpRequestToNameString transformer before they are passed to the component. it's http://localhost:8888 can receive messages using standard HTTP GET request.mule. HTTP expects a synchronous response.ExceptionToString" /> Go ahead and add all of the above transformer declarations to your mule configuration after the <description> element. The exchange pattern to follow.example. so you add the <model> tag first: <model name="myHelloApp"> . a <component>. In this case. we've specified the inbound endpoint. and an <outbound> section in that order. For details on the elements you can configure in a service. which is where you specify your components that do the actual work.myhelloapp. The Hello World example has four services.mule. In this case.services will go here Now.ChatStringToString"/> <custom-transformer name="ExceptionToString" class="org.ico"/> </not-filter> </inbound-endpoint> </inbound> Notice that within the inbound section. each of which has an <inbound> section.example. so all messages received on this endpoint will be processed by the service.myhelloapp. The transformer to use. Configure the Inbound Section Let's add the inbound section for the GreeterUMO service first: <service name="GreeterUMO"> <inbound> <inbound-endpoint address="http://localhost:8888" transformer-refs="HttpRequestToNameString" exchange-pattern="request-response"> <not-filter> <wildcard-filter pattern="/favicon. The inbound endpoint defines which messages this service will handle by specifying the following: The transport.mule. Configure Models and Services You are now ready to add your services. There is no inbound router specified. that will convert the HTTP request to a NameString object. getInvalidUserNameError()). <outbound> <filtering-router> <vm:outbound-endpoint path="chitchatter" exchange-pattern="request-response"/> <payload-type-filter expectedType="org. The outbound router will filter exceptions * as user errors and return the messages to the original requester accordingly.myhelloapp.mule. /** * <code>Greeter</code> expects a valid <code>NameString</code> object. */ public class Greeter { private String greeting = "". we use filtering routers. our component is a POJO. We specify this in the outbound section. if (person.The component is the next element to configure.setGreeting(greeting). see Entry Point. or anything that can perform logic on the messages.Greeter"/> By default. we want to use an outbound router to send the message to one service if the message was processed successfully and to a different service if the message had errors. Mule automatically discovers the correct method in the Java class to execute (the entry point) by matching the return type on the transformer (in this case. web service.isValid()) { person. package org.example.lang.mule. } return payload. In this case. Spring Bean. so you specify the class in the <component> tag: <component class="org. and b) the criteria the message must meet to be routed there.mule.example. } else { payload = new Exception(LocaleMessage. } } Configure the Outbound Section Now we need to specify what the service will do after the component has finished with it. The component can be a plain Java class. } public Object greet(NameString person) { Object payload = person.myhelloapp. If invalid.myhelloapp. public Greeter() { greeting = LocaleMessage. If a message does not meet the criteria of the first router.Exception"/> </filtering-router> </outbound> .example. it's checked against the second router's criteria. To do this.getGreetingPart1().NameString"/> </filtering-router> <filtering-router> <vm:outbound-endpoint path="userErrorHandler" exchange-pattern="request-response"/> <payload-type-filter expectedType="java. * an exception is created and returned. NameString) to the methods in the component. The code for the Greeter component is below. each of which specifies a) the outbound endpoint where the message will go next. and so on until there's a match. In this example. For information on other ways of resolving the entry point. JSR-223 script. into an error file. into an error file. the message is routed to the userErrorHandler path using the VM transport. This service transforms the message. just an inbound and outbound endpoint that re-routes all messages to STDERR. Errors could also be routed elsewhere. In this case there is no outbound. In this case.This error handler returns user error messages to caller. If you deploy your services on separate Mule instances instead. you add the response transformer and declare the request-response exchange pattern.Route unexpected errors to separate error handler --> <default-service-exception-strategy> <vm:outbound-endpoint path="systemErrorHandler" exchange-pattern="one-way"/> </default-service-exception-strategy></service> In the Hello World example. you must ensure that they specify chitchatter or userErrorHandler as the path on their inbound endpoints. Configure Error Handling Mule provides support for error handling for unexpected errors. stored in a database. send via email to a list. the first router sends it to the chitchatter path using the VM transport. stored in a database. if the message payload was transformed correctly into a NameString object. --> <flow name="SystemErrorHandler"> <vm:inbound-endpoint path="systemErrorHandler" exchange-pattern="request-response"/> <outbound-endpoint address="stdio://ERR" exchange-pattern="one-way"/> </flow> The SystemErrorHandler uses a new construct in Mule 3 called <flow>. etc. adds text to it and returns it to the caller.Handle any unexpected errors.myhelloapp. you could easily replace this with a JMS provider. Therefore.g. which will transform the string after the component is done with it and send it back to the caller. we're simply going to configure a response transformer. If the message was not transformed correctly and the payload contains an exception.In this case. These error-handling services are defined below: <!-. --> <service name="UserErrorHandler"> <inbound> <vm:inbound-endpoint path="userErrorHandler" responseTransformer-refs="ExceptionToString" exchange-pattern="request-response"/> </inbound> </service> The UserErrorHandler just transforms the message using the response transformer and returns it to the caller. we use the simpler flow construct to specify the inbound endpoint and component. e. Again.err. Flow-based configuration allows a more flexible model than service and can be useful for processing messages where the service-based model is not required. <flow name="ChitChat"> <vm:inbound-endpoint path="chitchatter" transformer-refs="NameStringToChatString" responseTransformer-refs="ChatStringToString" exchange-pattern="request-response"/> <component class="org. user errors are routed back to the caller and system errors are routed to system. Errors could also be routed elsewhere.example.ChitChatter"/> </flow> The code for the ChitChatter component is below: .mule. send via email to a list. VM is an internal messaging service that routes messages between services running inside the same JVM for faster processing. there is no component or outbound router. e. <!-. When you configure the services that will handle the message in each of these cases. Exception strategies allow you to handle messages when there is a system error: <!-. Instead of using an outbound endpoint. Configure the Final Service There is one last service in the example: the ChitChat service.g. namely the HTTP endpoint. etc. Test the Application It's time to test the application. It then passed the message to the ChitChat service for processing. Create an HTML Interface Because it's unlikely that users would enter their names as part of a URL string. where it was displayed in the web browser. } } Lastly. Follow the directions in Creating an Application Using the Mule IDE (Mule IDE) or Creating an Application Using Maven (Maven) to package and deploy your application to Mule. 1.. public ChitChatter() { chitchat = LocaleMessage. Run the Application To run the application. This assumes you previously packaged and deployed the application to Mule. which was picked up and processed by the GreeterUMO service. } public void chat(ChatString string) { string. the custom classes must be compiled and the entire application packaged into a Mule application archive.getGreetingPart2(). end the file with the closing </model> and </mule> tags: . This URL passed "Ross" to the endpoint http://localhost:8888. which sent it back to the calling endpoint.mule. navigate to the examples/hello/src directory under your Mule home directory or create a new project from the Hello World example using the Mule IDE (See Creating an Application Using the Mule IDE). Testing Your Mule Application Testing Your Mule Application [ Test the Application ] [ Create an HTML Interface ] [ Unit Test Cases ] [ Functional Test Case ] This lesson builds on Creating a Configuration File and shows you how to test the Hello World example using a web page and Mule's functional test framework. Open a web browser and enter the URL http://localhost:8888/?name=Ross. The configuration file is included in examples/hello/src/main/apps and the custom classes referenced in the configuration file are included with the example under the examples/hello/src/main/java directory. public class ChitChatter { private String chitchat = "".example. </model> </mule> View the Full Example To see the entire configuration file and source code for this example.package org.myhelloapp.append(chitchat).. you could create an HTML page that prompts users for their . //TODO Assert the correct data has been received assertEquals("some data Received".mule. import import import import org. assertFalse(result. with the Hello World application still running. a test case can be used to test a flow. If you examine the test cases in the Hello World example. org.mule. and then click Submit Name.api. For example. It displays the greeting with your name.FunctionalTestCase.w3.w3. If you used the Maven archetype to create your project.getPayload() instanceof NullPayload). launch this HTML page in a web browser.tck. it is easy to run an entire Mule Server inside a test case.0 Strict//EN" "http://www. Mule provides an abstract JUnit test case called org. The org. including FunctionalTestComponent.MuleClient. so unit testing is easy.tck.names and submits it via a form. Unit Test Cases Most custom objects in Mule are POJOs.transport. The test case looks like this: package org. org. create a simple page with the following code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. } public void testMyHelloApp() throws Exception { MuleClient client = new MuleClient(muleContext). assertNull(result.getExceptionPayload()). null). assertNotNull(result). It should look like this: Enter your name. public class MyHelloAppTestCase extends FunctionalTestCase { protected String getConfigResources() { //TODO You'll need to edit this file to make the test applicable to your module return "myhelloapp-functional-test-config. This means. you'll see how the various components and transformers are easily tested with standard unit tests.module.FunctionalTestCase that runs Mule inside a test case and manages the lifecycle of the server. "some data".MuleMessage. then you already have a skeleton test case and configuration file.functional package contains a number of supporting classes for functionally testing Mule code. } } .getPayloadAsString()).org/TR/xhtml1/DTD/xhtml1-strict.client. MuleMessage result = client.mule.send("vm://in". Functional Test Case Because Mule ESB is light-weight and embeddable.dtd"> <html xmlns="http://www.myhelloapp.tck. More detail on Functional Testing with Mule can be found in the documentation.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Get Name</title> </head> <body> <form method="GET" action="http://localhost:8888"> <input type="text" name="name"/> <input type="submit" value="Submit Name" /> </form><br /> </body> </html> Now. org.NullPayload.xml".mule.mule.mule. result.example.mule. //TODO Assert the correct data has been received assertEquals("Hello Ross. Asynchronous reply routers are used in request/response scenarios where message traffic is triggered by a request and the traffic needs to be consolidated before a response is given.getExceptionPayload()). result. } That's it. It is important to know that . Filters provide the logic used to invoke a particular router. such as selectively consuming only those messages that meet specific criteria or grouping messages together that share a group ID before forwarding them on. you will need to modify the verification string to match the one created for your locale. An inbound or outbound endpoint can be associated with a catch-all strategy so that any orphaned messages can be caught and routed to a common location. We will now include an inbound VM endpoint which we'll use to test the application. OrFilter. Introducing Message Routing Introducing Message Routing [ Overview ] [ Selecting a Message Style ] [ Summary ] This lesson provides an introduction to message routing and describes when to use the different message styles. assertFalse(result. "Ross". MuleMessage result = client. If you execute the test case it should pass. assertNull(result. new users sometimes get confused about when to use an outbound router and when it's sufficient to simply get a reply. Add the following to the inbound element of your GreeterUMO service in the test configuration: <vm:inbound-endpoint path="greeter" transformer-refs="StringToNameString" exchange-pattern= "request-response"/> Now let's modify the test case to call this endpoint and assert the result: public void testMyHelloApp() throws Exception { MuleClient client = new MuleClient(muleContext). The classic example of this is where a request is made and tasks are executed in parallel. The exchange-pattern attribute in Mule is how you explicitly define the message style you want. Each task must finish executing and the results processed before a response can be sent back. and NotFilter.First replace the generated configuration file with the one you created for the application. assertNotNull(result). Filters can be combined using the logic filters AndFilter.send("vm://greeter". Outbound routers control how a message is dispatched after the service has processed it. but all routers support them. For more information on all topics related to configuring and using Mule.getPayload() instanceof NullPayload).getPayloadAsString()). such as sending it to a list of recipients or splitting up the message and sending the parts to different endpoints. Catch-all strategies are invoked if no routing path can be found for the current message. This simple example assumes the English locale and is not testing for different locales. Not all routers need to use filters. see the Mule User's Guide (login required). how are you?". Overview Message routers control how messages are routed among the services in your Mule ESB application. Selecting a Message Style When wiring your Mule services together. If you are in a different locale. Following is a description of the key concepts: Inbound routers control how a service handles incoming messages. null). each transport has a default exchange pattern that will be enforced if you do not specify one. This is the synchronous message style To enable this you would put the request-response exchange pattern on both the inbound and outbound endpoints. For example. After the second service processes the message. This is the request-response message style and is defined using the request-response exchange pattern. and no response to the caller is required. For example: <model name="Asynchronous_Message_Pattern"> <service name="AsynchronousService"> <inbound> <jms:inbound-endpoint queue="test. the first service sends it back to the caller as a reply.in" exchange-pattern="one-way"/> </inbound> <component class="org.WidgetHandler" /> <outbound> <pass-through-router> <jms:outbound-endpoint queue="test. and then sends it back to the caller as a reply. Following is a description of the message styles you can use in Mule.out" exchange-pattern="one-way"> <pass-through-router> </outbound> </service> </model> Request-Response In simple scenarios that require a response. Asynchronous If you simply want to put a message on a SEDA queue after processing it. you can simply configure a synchronous inbound endpoint on the service that does the transformation.WidgetHandler" /> </service> </model> Synchronous If you need to pass the message to a second service for additional processing. and you want to transform that value and display the results in the same page. a service receives a request on a synchronous inbound endpoint. For example: .myorg.myorg. if a user enters a value in an HTML form. This scenario does not use an outbound router. you would configure an outbound router on the first service to pass the message to the second service. You should specify this on both the inbound and outbound endpoints. processes the request. you can use the asynchronous message style as defined by the one-way exchange pattern. For example: <model name="Request-Response_Message_Pattern"> <service name="SynchronousService"> <inbound> <http:inbound-endpoint host="localhost" port="8080" path="/mule/services" exchange-pattern= "request-response"/> </inbound> <component class="org. is broadcast to two endpoints using the Multicast router. This is the asynchronous request-response message style. You can set the inbound endpoint's exchange-pattern attribute to one-way.out" exchange-pattern="request-response"/> </inbound> <component class="org. since the response will be handled by the asynchronous reply router. and the results are sent asynchronously to a JMS endpoint.out" exchange-pattern="request-response"/> </chaining-router> </outbound> </service> <service> <inbound> <jms:inbound-endpoint queue="test. a request comes in on an HTTP endpoint. In the following example.in" exchange-pattern="request-response"/> </inbound> <component class="org.myorg.<model name="Synchronous_Message_Pattern"> <service name="SynchronousService"> <inbound> <jms:inbound-endpoint queue="test. .WidgetPackager" /> </service> </model> Asynchronous Request-Response In the most complex scenario.myorg. unless you also want to send a response to the caller. you can enable request-response messaging and allow the back-end process to be forked to invoke other services. returning a reply asynchronously based on the results of multiple service invocations.WidgetHandler" /> <outbound> <chaining-router> <jms:outbound-endpoint queue="test. you can use a selective consumer to ensure that only those with the result code "success" are processed.queue"/> <jms:outbound-endpoint queue="service1" exchange-pattern="one-way"/> <jms:outbound-endpoint queue="service2" exchange-pattern="one-way"/> </multicasting-router> </outbound> </service> </model> Summary This section described the different message styles you can use. Understanding Advanced Message Routing Understanding Advanced Message Routing [ Filtering Messages ] [ Chaining Outbound Endpoints Together ] [ Splitting Messages ] [ Processing a Message Only Once ] This lesson builds on Introducing Message Routing and shows you how to use specific message routers to control how a message is routed through your application. The Filtering Router works on outbound endpoints to control which messages the service sends along to the next endpoint. see Service Messaging Styles in the Mule User's Guide. Filtering Messages You can control which messages a service handles by using filters.queue" exchange-pattern="one-way"/> </async-reply> <outbound> <multicasting-router> <reply-to address="jms://reply. Understanding Advanced Message Routing describes several routers you can use for achieving finer control over message routing. For complete information. You can use a combination of these approaches to control the message flow. For example.myorg.<model name="Async_Request-Response_Message_Pattern"> <service name="AsyncRequestResponseService"> <inbound> <http:inbound-endpoint host="localhost" port="8080" path="/mule/services" exchange-pattern= "one-way"/> </inbound> <component class="org. Now that you understand which message styles to use for routing in different scenarios. You can then use a Catch-all Strategy to forward all other messages to another endpoint for error handling: . if you only want to process messages that don't have errors.WidgetHandler" /> <async-reply timeout="5000"> <collection-async-reply-router/> <jms:inbound-endpoint queue="reply. The Selective Consumer Router works on inbound endpoints to control which messages that service will process. You could achieve this using the chaining router.*)"/> </and-filter> </filtering-router> </outbound> Similar routers are the forwarding router. and if the message fails validation.queue" exchange-pattern="one-way"/> <and-filter> <payload-type-filter expectedType="java. In the following example. the chaining router always returns a response.<inbound> <selective-consumer-router> <mulexml:jxpath-filter expression="msg/header/resultcode = 'success'"/> </selective-consumer-router> <forwarding-catch-all-strategy> <jms:endpoint topic="error.lang. Unlike the pass-through router.String"/> <regex-filter pattern="the quick brown (. see Inbound Routers in the Mule User's Guide.lang. For example: .lang.Exception"/> </filtering-router> <filtering-router> <jms:outbound-endpoint queue="string. Chaining Outbound Endpoints Together Let's assume we have a validation service. messages that contain an exception are sent to the system administrator's email address. which is a fast and lightweight configuration for sending a message to an endpoint and then sending the result of that endpoint to another endpoint. and all other messages are picked up by the forwarding catch-all router and sent to an error queue: <outbound> <forwarding-catch-all-strategy> <jms:outbound-endpoint queue="error.queue" exchange-pattern="one-way"/> </forwarding-catch-all-strategy> <filtering-router> <smtp:outbound-endpoint to="ross@muleumo. and the wiretap router.org" exchange-pattern="one-way"/> <payload-type-filter expectedType="java. you can use filtering outbound routers. For example: <chaining-router> <vm:outbound-endpoint path="ValidationService" exchange-pattern="request-response"/> <vm:outbound-endpoint path="ValidationError" exchange-pattern="request-response"> <exception-type-filter expectedType="java. messages whose payload contains a specific string are sent to the string queue.Exception"/> </vm:outbound-endpoint> </chaining-router> You can also use the chaining router to perform protocol bridging to a single outbound endpoint.topic" exchange-pattern="one-way"/> </forwarding-catch-all-strategy> </inbound> If you want the service to process all messages but then want to specify criteria to determine where the message is sent next. which allows you to process some messages and selectively forward others. which allows you to process all messages and send them on as normal but also send a copy to another endpoint. the message and its exception are forwarded to another service AND the message and its exception are returned to the caller. For more information. foo.foo.request\]" exchange-pattern="request-response"/> </chaining-router> </outbound> </service> Splitting Messages A message splitter can be used to break down an outgoing message into parts and dispatch those parts over different endpoints configured on the router.Order"/> </vm:outbound-endpoint> <vm:outbound-endpoint path="item" exchange-pattern="one-way"> <payload-type-filter expectedType="com.xsd"> <vm:outbound-endpoint path="order" exchange-pattern="one-way"> <payload-type-filter expectedType="com.net#\[header:http.asmx?wsdl --> <inbound-endpoint address="http://localhost:8888" exchange-pattern="request-response"/> </inbound> <outbound> <chaining-router> <outbound-endpoint address="http://www.queue" exchange-pattern="one-way"> <payload-type-filter expectedType="com. You could do this using one of the following routers: List Message Splitter: accepts a list of objects that will be routed to different endpoints. For example: .Item"/> </vm:outbound-endpoint> </mulexml:filter-based-splitter> </outbound> Expression Splitter Router: similar to the List Message Splitter but splits the message based on an expression that returns one or more message parts.foo.Order"/> </jms:outbound-endpoint> <jms:outbound-endpoint queue="item. For example: <outbound> <list-message-splitter-router"> <jms:outbound-endpoint queue="order.queue" exchange-pattern="one-way"> <payload-type-filter expectedType="com. For example: <outbound> <mulexml:filter-based-splitter splitExpression="root/nodes" validateSchema="true" externalSchemaLocation="/com/example/TheSchema. you might want to send different parts of the message to different services for processing.webservicex.<service name="HttpProxyService"> <inbound> <!-.WSDL URL: http://localhost:8888/stockquote. in an order-processing application.foo.Item"/> </jms:outbound-endpoint> </list-message-splitter-router> </outbound> Filtering XML Message Splitter: similar to the List Message Splitter but operates on XML documents. For example. The Round Robin Message Splitter splits the message into parts and sends them to endpoints in a round-robin approach. which means the underlying endpoint must support unique message IDs for this to work. which is set by the outbound router. After splitting messages. By default. <inbound> <message-chunking-aggregator-router> <expression-message-info-mapping correlationIdExpression="#[header:correlation]"/> <payload-type-filter expectedType="org.Object"/> </message-chunking-aggregator-router> </inbound> Processing a Message Only Once The Idempotent Receiver ensures that only unique messages are received by a service by checking the unique message ID of the incoming message. the expression used is #[message:id]. to identify which parts belong to the same message. you use the Message Chunking Aggregator to aggregate the message parts back together again. In the following example. a unique ID is a combination of the message ID and the contents of the label field in the header. The ID can be generated from the message using an expression defined in the idExpression attribute. and the IDs are then written to a simple text file to keep track of which messages have already been processed: <inbound> <idempotent-receiver-router idExpression="#[message:id]-#[header:label]"> <simple-text-file-store directory=".some. The Message Chunking Router splits a single message into a number of fixed-length messages that will all be routed to the same endpoint.<outbound> <expression-splitter-router evaluator="xpath" expression="/mule:mule/mule:model/mule:service" disableRoundRobin="true" failIfNoMatch="false"> <outbound-endpoint ref="service1"> <expression-filter evaluator="xpath" expression="/mule:service/@name = 'service splitter'"/> </outbound-endpoint> <outbound-endpoint ref="service2"> <expression-filter evaluator="xpath" expression="/mule:service/@name = 'round robin deterministic'"/> </outbound-endpoint> </expression-splitter-router> </outbound> You could also split a message into parts to improve performance./idempotent"/> </idempotent-receiver-router> </inbound> .foo. The aggregator uses the correlation ID.
Copyright © 2024 DOKUMEN.SITE Inc.