Creating First Mule Application

MuleSoft – Creating First Mule Application ”; Previous Next In this chapter we are going to create our first Mule application in MuleSoft’s Anypoint Studio. For creating it, first we need to launch Anypoint Studio. Launching Anypoint Studio Click on Anypoint Studio to launch it. If you are launching it for first time, then you will see the following window − User Interface of Anypoint Studio Once you Click on the Go to Workspace button, it will lead you to the user interface of Anypoint Studio as follows − Steps for Creating Mule Application In order to create your Mule application, follow the below steps − Creating New Project The very first step for creating Mule application is to create a new project. It can be done by following the path FILE → NEW → Mule Project as shown below − Naming the Project After clicking on the new Mule Project, as described above, it will open a new window asking for the project name and other specifications. Give the name of the Project, ‘TestAPP1’ and then click on the finish button. Once you click on the Finish Button, it will open the workspace built for your MuleProject namely ‘TestAPP1’. You can see all the Editors and Views described in the previous chapter. Configuring the Connector Here, we are going to build a simple Mule application for HTTP Listener. For this, we need to drag the HTTP Listener connector from Mule Palette and drop it to the workspace as shown below − Now, we need to configure it. Click on the green color + sign after Connector configuration under Basic Settings as shown above. On clicking ok, it will take you back on HTTP Listener property page. Now we need to provide the path under General Tab. In this particular example, we have provided /FirstAPP as path name. Configuring Set Payload Connector Now, we need to take a Set Payload connector. We also need to give its value under Settings tab as follows − This is my first Mule Application, is the name provided in this example. Running Mule Application Now, save it and click Run as Mule Application as shown below − We can check it under Console which deploys the application as follows − It shows that you have successfully built your first Mule Application. Verifying Mule Application Now, we need to test whether our app is running or not. Go to POSTMAN, a Chrome app and enter the Url: http:/localhost:8081. It shows the message we have provided while building Mule application as shown below − Print Page Previous Next Advertisements ”;

MuleSoft – Testing with MUnit

MuleSoft – Testing with MUnit ”; Previous Next We understand unit testing is a method by which individual units of source code can be tested to determine whether they are fit for use or not. Java programmers can use Junit framework to write test cases. Similarly, MuleSoft is also having a framework called MUnit allowing us to write automated test cases for our APIs and integrations. It is a perfect fit for continuous integration/deployment environment. One of the biggest advantages of MUnit framework is that we can integrate it with Maven and Surefire. Features of MUnit Following are some of the very useful features of Mule MUnit testing framework − In MUnit framework, we can create our Mule test by using Mule code as well as Java code. We can design and test our Mule apps and APIs, either graphically or in XML, within Anypoint Studio. MUnit allows us to easily integrate the testing into existing CI/CD process. It provides auto-generated tests and coverage reports; hence the manual work is minimal. We can also use local DB/FTP/mail servers to make testing more portable through the CI process. It allows us to enable or disable tests. We can also extend the MUnit framework with plugins. It allows us to verify message processor calls. With the help of MUnit testing framework, we can disable endpoint connectors as well as flow inbound end points. We can check error reports with Mule stack trace. Latest Release of Mule MUnit Testing Framework MUnit 2.1.4 is the latest release of Mule MUnit testing framework. It requires following hardware and software requirements − MS Windows 8+ Apple Mac OS X 10.10+ Linux Java 8 Maven 3.3.3, 3.3.9, 3.5.4, 3.6.0 It is compatible with Mule 4.1.4 and Anypoint Studio 7.3.0. MUnit and Anypoint Studio As discussed, MUnit is fully integrated in Anypoint studio and we can design and test our Mule apps and APIs graphically or in XML within Anypoint studio. In other words, we can use graphical interface of Anypoint Studio to do the following − For creating and designing MUnit tests For running our tests For viewing test results as well as coverage report For debugging the tests So, let us start discussing each task one by one. Creating and Designing MUnit Tests Once you start new project, it will automatically add a new folder namely src/test/munit to our project. For example, we started a new Mule project namely test_munit, you can see in the below image, it adds the above-mentioned folder under our project. Now, once you started new project, there are two basic ways to create a new MUnit test in Anypoint Studio − By Right-Clicking the Flow − In this method, we need to right-click the specific flow and select MUnit from the drop-down menu. By Using the Wizard − In this method, we need to use the wizard for creating a test. It allows us to create a test for any flow in the workspace. We are going to use ‘Right-click the flow’ way to create a test for specific flow. First, we need to create a flow in the workspace as follows − Now, right click on this flow and select MUnit to create a test for this flow, as shown below − It will create a new test suite named after the XML file where the flow resides. In this case, test_munit-test-suite is the name of the new test suite as shown below − Following is the XML editor for the above message flow − Now, we can add an MUnit message processor to the test suite by dragging it from Mule Palette. If you want to create a test via the Wizard then follow File → New → MUnit and it will lead you to the following MUnit testing suite − Configuring the test In Mule 4, we have two new sections namely MUnit and MUnit Tools, collectively having all MUnit message processor. You can drag any of the message processor in your MUnit test area. It is shown in the below screenshot − Now, if you want to edit the configuration for your suit or test in Anypoint Studio, then you need to follow the below steps − Step 1 Go to the Package Explorer and right click on the .xml file for your suite or test. Then, select the Properties. Step 2 Now, in the Properties window, we need to click Run/Debug Settings. After this click New. Step 3 In the last step, click MUnit under Select Configuration Type window, and then click OK. Running the Test We can run a test suite as well as a test. First, we will see how to run a test suite. Running a Test Suite For running a test suite, right click on the empty part of the Mule Canvas where your test suite resides. It will open a drop-down menu. Now, click on the Run MUnit suite as shown below − Later, we can see the output in the console. Running a Test To run a specific test, we need to select the specific test and right-click on that. We will get the same drop-down menu as we got while running test suite. Now, click on the Run MUnit Test option as shown below − There after the output can be seen in the console. Viewing and Analyzing Test Result Anypoint studio displays the MUnit test result in the MUnit tab of the left-hand explorer pane. You can find successful tests in green color and failed tests in red one as shown below − We can analyze our test result by viewing the coverage report. The main feature of Coverage Report is to provide a metric on how much of a Mule application has been successfully executed by a set of MUnit tests. MUnit coverage is basically based on the amount of MUnit message processors executed. MUnit coverage report provides metric for the following − Application overall coverage Resource coverage Flow coverage To get the

Message Processor & Script Components

MuleSoft – Message Processor & Script Components ”; Previous Next The scripting modules facilitate users to use scripting language in Mule. In simple words, the scripting module can exchange custom logic written in scripting language. Scripts can be used as Implementations or transformers. They can be used for expression evaluation, i.e., for controlling message routing. Mule has the following supported scripting languages − Groovy Python JavaScript Ruby How to Install Scripting Modules? Actually, Anypoint Studio comes with the scripting modules. If you do not find the module in Mule Palette, then it can be added by using +Add Module. After adding, we can use the scripting module operations in our Mule application. Implementing Example As discussed, we need to drag and drop the module into canvas for creating workspace and use it in our application. Following is an example of it − We already know how to configure the HTTP Listener component; hence we are going to discuss about configuring the Scripting Modules. We need to follow the steps written below to configure scripting module − Step 1 Search for the Scripting module from Mule Palette and drag the EXECUTE operation of the scripting module into your flow as shown above. Step 2 Now, open the Execute configuration tab by double clicking on the same. Step 3 Under the General tab, we need to provide the code in the Code text window as shown below − Step 4 At last, we need to choose the Engine from the execute component. The list of engines is as below − Groovy Nashorn(javaScript) jython(Python) jRuby(Ruby) The XML of the above execution example in the Configuration XML editor is as follows − <scripting:execute engine=”jython” doc:name = “Script”> <scripting:code> def factorial(n): if n == 0: return 1 return n * factorial(n-1) result = factorial(10) </scripting:code> </scripting:execute> Message Sources Mule 4 has a simplified model than Mule 3 message making it easier to work with data in a consistent way across connectors without overwriting information. In Mule 4 message model, each Mule event consists of two things: a message and variables associated with it. A Mule message is having payload and its attributes, where attribute is mainly metadata such as file size. And a variable holds the arbitrary user information such as operation result, auxiliary values, etc. Inbound The inbound properties in Mule 3 now becomes Attributes in Mule 4. As we know that inbound properties store additional information about the payload obtained through a message source, but this is now, in Mule 4, done with the help of attributes. Attributes have the following advantages − With the help of attributes, we can easily see which data is available, because attributes are strongly typed. We can easily access information contained in attributes. Following is the example of a typical message in Mule 4 − Outbound The outbound properties in Mule 3 must be explicitly specified by Mule connectors and transports in order to send additional data. But in Mule 4, each of those can be set separately, using a DataWeave expression for each one of them. It does not produce any side effect in the main flow. For example, below DataWeave expression will perform a HTTP request and generates headers and query parameters without a need to set message properties. This is shown in the below code − <http:request path = “M_issue” config-ref=”http” method = “GET”> <http:headers>#[{”path”:”input/issues-list.json”}]</http:headers> <http:query-params>#[{”provider”:”memory-provider”}]</http:query-params> </http:request> Message Processor Once Mule receives a message from a message source, the work of message processor starts. The Mule uses one or more message processors to process the message through a flow. The main task of message processor is to transform, filter, enrich and process the message as it passes through the Mule flow. Categorization of Mule Processor Following are the categories of Mule Processor, based on functions − Connectors − These message processors send and receive data. They also plug data into external data sources via standard protocols or third-party APIs. Components − These message processors are flexible in nature and perform business logic implemented in various languages like Java, JavaScript, Groovy, Python or Ruby. Filters − They filter the messages and allow only specific messages to continue to be processed in a flow, based on specific criteria. Routers − This message processor is used to control the flow of message to route, resequencing or split. Scopes − hey basically wrap snippets of code for the purpose of defining fine-grained behavior within a flow. Transformers − The role of transformers is to convert message payload type and data format to facilitate communication between systems. Business Events − They basically capture data associated with key performance indicators. Exception strategies − These message processors handle errors of any type that occur during message processing. Print Page Previous Next Advertisements ”;

MuleSoft – Anypoint Studio

MuleSoft – Anypoint Studio ”; Previous Next MuleSoft’s Anypoint Studio is a user-friendly IDE (integration development environment) used for designing and testing Mule applications. It is an Eclipse-based IDE. We can easily drag Connectors from the Mule Palette. In other words, Anypoint Studio is an Eclipse based IDE for development of flow, etc. Prerequisites We need to satisfy following prerequisites before installing Mule on all OS, i.e., Windows, Mac and Linux/Unix. Java Development Kit (JDK) − Before installing Mule, verify that you have supported version of Java on your system. JDK 1.8.0 is recommended to successfully install Anypoint on your system. Downloading and Installing Anypoint Studio The procedure to download and install Anypoint Studio on different operating systems may vary. Next, there are steps to be followed for downloading and installing Anypoint Studio on various operating systems − On Windows To download and install Anypoint Studio on Windows, we need to follow the steps below − Step 1 − First, click on the link https://www.mulesoft.com/lp/dl/studio and choose the Windows operating system from top-down list to download the studio. Step 2 − Now, extract it into the ‘C:’ root folder. Step 3 − Open the extracted Anypoint Studio. Step 4 − For accepting the default workspace, click OK. You will get a welcome message when it loads for the first time. Step 5 − Now, click on Get Started button to use Anypoint Studio. On OS X To download and install Anypoint Studio on OS X, we need to follow the steps below − Step 1 − First, click on the link https://www.mulesoft.com/lp/dl/studio and download the studio. Step 2 − Now, extract it. In case if you are using OS version Sierra, make sure to move the extracted app to /Applications folder before launching it. Step 3 − Open the extracted Anypoint Studio. Step 4 − For accepting the default workspace, click OK. You will get a welcome message when it loads for the first time. Step 5 − Now, click on Get Started button to use Anypoint Studio. If you are going to use custom path to your workspace, then please note that Anypoint Studio does not expand the ~ tilde used in Linux/Unix systems. Hence, it is recommended to use the absolute path while defining the workspace. On Linux To download and install Anypoint Studio on Linux, we need to follow the steps below − Step 1 − First, click on the link https://www.mulesoft.com/lp/dl/studio and choose the Linux operating system from top-down list to download the studio. Step 2 − Now, extract it. Step 3 − Next, open the extracted Anypoint Studio. Step 4 − For accepting the default workspace, click OK. You will get a welcome message when it loads for the first time. Step 5 − Now, click on Get Started button to use Anypoint Studio. If you are going to use custom path to your workspace, then please note that Anypoint Studio does not expand the ~ tilde used in Linux/Unix systems. Hence, it is recommended to use the absolute path while defining the workspace. It is also recommended to install GTK version 2 to use complete Studio Themes in Linux. Features of Anypoint Studio Following are some features of Anypoint studio enhancing the productivity while building Mule applications − It provides an instant run of Mule application inside a local runtime. Anypoint studio gives us visual editor for configuring API definition files and Mule domains. It has embedded unit testing framework enhancing the productivity. Anypoint studio provides us the Built-in support to deploy to CloudHub. It has the facility to integrate with Exchange for importing templates, examples, definitions and other resources from other Anypoint Platform organization. Print Page Previous Next Advertisements ”;

MuleSoft – Quick Guide

MuleSoft – Quick Guide ”; Previous Next MuleSoft – Introduction to Mule ESB ESB stands for Enterprise Service Bus which is basically a middleware tool for integrating various applications together over a bus-like infrastructure. Fundamentally, it is an architecture designed to provide a uniform means of moving work among integrated applications. In this way, with the help of ESB architecture we can connect different applications through a communication bus and enable them to communicate without depending on one another. Implementing ESB The main focus of ESB architecture is to decouple the systems from each other and allow them to communicate in a steady and controllable way. ESB’s implementation can be done with the help of ‘Bus’ and ‘Adapter’ in the following way − The concept of “bus”, which is achieved through a messaging server like JMS or AMQP, is used to decouple different applications from one another. The concept of “adapter”, responsible for communicating with backend application and transforming data from application format to bus format, is used between applications and bus. The data or message passing from one application to another through the bus is in a canonical format which means there would be one consistent message format. The adapter can also perform other activities like security, monitoring, error handling and message routing management. ESB’s Guiding Principles We can call these principles as core integration principles. They are as follows − Orchestration − Integration of two or more services to achieve synchronization between data and process. Transformation − Transforming data from canonical format to application specific format. Transportation − Handling protocol negotiation between formats like FTP, HTTP, JMS, etc. Mediation − Providing multiple interfaces to support multiple versions of a service. Non-functional consistency − Providing mechanism for managing transactions and security also. Need of ESB ESB architecture enables us to integrate different applications where each application can communicate through it. Following are some guidelines on when to use ESB − Integrating two or more applications − Use of ESB architecture is beneficial when there is a need to integrate two or more services or applications. Integration of more applications in future − Suppose if we want to add more services or applications in future, then it can be easily done with the help of ESB architecture. Using multiple protocols − In case if we need to use multiple protocols like HTTP, FTP, JMS etc., ESB is the right option. Message routing − We can use ESB in case if we require message routing based on message content and other similar parameters. Composition and consumption − ESB can be used if we need to publish services for composition and consumption. P2P integration vs. ESB integration With the increase in number of applications, a big question in front of developers was how to connect different applications? The situation was handled by hand-coding a connection between various application. This is called point-to-point integration. Rigidity is the most obvious drawback of point-to-point integration. The complexity increases with the increased number of connections and interfaces. The disadvantages of P-2-P integration leads us to ESB integration. ESB is a more flexible approach to application integration. It encapsulates and exposes each application functionality as a set of discrete reusable capabilities. No application directly integrates with other, instead they integrate through an ESB as shown below − For managing the integration, ESB has the following two components − Service Registry − Mule ESB has Service Registry/Repository where all the services exposed into the ESB are published and registered. It acts as a point of discovery from where one can consume the services and capabilities of other applications. Centralized Administration − As the name implies, it provides a view of transactional flows of performance of interactions occurring inside the ESB. ESB Functionality − VETRO abbreviation is generally used to summarize the functionality of ESB. It is as follows − V(Validate) − As the name implies, it validates the schema validation. It requires a validating parser and up-to-date schema. One example is an XML document confirming to an up-to-date schema. E(Enrich) − It adds additional data to a message. The purpose is to make message more meaningful and useful to a target service. T(Transform) − It converts the data structure to a canonical format or from a canonical format. Examples are conversion of date/time, currency, etc. R(Routing) − It will route the message and act as a gatekeeper of the endpoint of a service. O(Operate) − The main job of this function is to invoke the target service or interacts with the target app. They run at the backend. VETRO pattern provides overall flexibility to the integration and ensures that only consistent and validated data will be routed throughout the ESB. What is Mule ESB? Mule ESB is a lightweight and highly scalable Java-based enterprise service bus (ESB) and integration platform provided by MuleSoft. Mule ESB allows the developer to connect applications easily and quickly. Regardless of various technologies used by applications, Mule ESB enables easy integration of applications, enabling them to exchange data. Mule ESB has the following two editions − Community Edition Enterprise Edition An advantage of Mule ESB is that we can easily upgrade from Mule ESB community to Mule ESB enterprise because both the editions are built on a common code base. Features & Capabilities of Mule ESB Following features are possessed by Mule ESB − It has simple drag-and-drop graphical design. Mule ESB is capable of visual data mapping and transformation. User can get the facility of 100s of pre-built certified connectors. Centralized monitoring and administration. It provides robust enterprise security enforcement capabilities. It provides the facility of API management. There is secure Data Gateway for cloud/on-premise connectivity. It provides the service registry where all the services exposed into the ESB are published and registered. Users can have control through a web-based management console. Rapid debugging can be performed using service flow analyzer. MuleSoft – The Mule Project The motivations behind the Mule project were − to make things simpler

Web Services Using Anypoint Studio

MuleSoft – Web Services Using Anypoint Studio ”; Previous Next REST Web Service The full form of REST is Representational State Transfer which is bound with HTTP. Hence, if you want to design an application to be used exclusively on the web, REST is the best option. Consuming RESTful Web Services In the following example, we will be using REST component and one public RESTful service provided by Mule Soft called American Flights details. It has various details but we are going to use GET:http://training-american-ws.cloudhub.io/api/flights that will return all flight details. As discussed earlier, REST is bound with HTTP, hence we need two HTTP components ― one is Listener and other is Request, for this application too. Below screenshot shows the configuration for HTTP listener − Configuring and passing arguments The configuration for HTTP request is given below − Now, as per our workspace flow, we have taken logger so it can be configured as below − In the message tab, we write code to convert the payload into strings. Testing the Application Now, save and run the application and go to POSTMAN to check the final output as shown below − You can see it gives the flight details by using REST component. SOAP Component The full form of SOAP is Simple Object Access Protocol. It is basically a messaging protocol specification for exchanging information in the implementation of web services. Next, we are going to use SOAP API in Anypoint Studio to access the information using web services. Consuming SOAP-based Web Services For this example, we are going to use public SOAP service whose name is Country Info Service which retains the services related to country information. Its WSDL address is: http://www.oorsprong.org/websamples.countryinfo/countryinfoservice.wso?WSDL First, we need to drag SOAP consume in our canvas from Mule Palette as shown below − Configuring and Passing Arguments Next, we need to configure HTTP request as done in above example as given below − Now, we also need to configure the Web Service Consumer as shown below − At the place of WSDL Location, we need to provide the web address of WSDL, which is provided above (for this example). Once you give the web address, Studio will search for service, Port and Address by itself. You need not provide it manually. Transfer Response from Web Service For this, we need to add a logger in the Mule flow and configure it for giving the payload as shown below − Testing the Application Save and run the application and go to Google Chrome for checking the final output. Type http://localhist:8081/helloSOAP (for this example) and it will show the country name by code as shown in the screenshot below − Print Page Previous Next Advertisements ”;

MuleSoft – Discussion

Discuss MuleSoft ”; Previous Next Mule ESB is a lightweight and highly scalable Java-based enterprise service bus (ESB) and integration platform provided by MuleSoft. Mule ESB allows developer to connect applications easily and quickly. Regardless of various technologies used by applications, Mule ESB enables easy integration of applications, enabling them to exchange data. Print Page Previous Next Advertisements ”;

MuleSoft – Mule Error Handling

MuleSoft – Mule Error Handling ”; Previous Next The new Mule error handling is one of the biggest and major changes done in Mule 4. The new error handing may seem complex, but it is better and more efficient. In this chapter, we are going to discuss about components of Mule error, Error types, categories of Mule error and components for handling Mule errors. Components of Mule Error Mule error is the result of Mule exception failure has the following components − Description It is an important component of Mule error which will give description about the problem. Its expression is as follows − #[error.description] Type The Type component of Mule error is used to characterize the problem. It also allows routing within an error handler. Its expression is as follows − #[error.errorType] Cause The Cause component of Mule error gives the underlying java throwable that causes the failure. Its expression is as follows − #[error.cause] Message The Message component of Mule error shows an optional message regarding the error. Its expression is as follows − #[error.errorMessage] Child Errors The Child Errors component of Mule error gives an optional collection of inner errors. These inner errors are mainly used by elements like Scatter-Gather to provide aggregated route errors. Its expression is as follows − #[error.childErrors] Example In case of failure of HTTP request with a 401 status code, the Mule Errors are as follows − Description: HTTP GET on resource ‘http://localhost:8181/TestApp’ failed: unauthorized (401) Type: HTTP:UNAUTHORIZED Cause: a ResponseValidatorTypedException instance Error Message: { “message” : “Could not authorize the user.” } Sr.NO Error Type and Description 1 TRANSFORMATION This Error Type indicates an error occurred while transforming a value. The transformation is Mule Runtime internal transformation and not the DataWeave transformations. 2 EXPRESSION This kind of Error Type indicates an error occurred while evaluating an expression. 3 VALIDATION This kind of Error Type indicates a validation error occurred. 4 DUPLICATE_MESSAGE A kind of validation error which occurs when a message being processed twice. 5 REDELIVERY_EXHAUSTED This kind of Error Type occurs when maximum attempts to reprocess a message from a source has been exhausted. 6 CONNECTIVITY This Error Type indicates a problem while establishing a connection. 7 ROUTING This Error Type indicates an error occurred while routing a message. 8 SECURITY This Error Type indicates a security error occurred. For example, invalid credentials received. 9 STREAM_MAXIMUM_SIZE_EXCEEDED This Error Type occurs when the maximum size allowed for a stream exhausted. 10 TIMEOUT It indicates the timeout while processing a message. 11 UNKNOWN This Error Type indicates an unexpected error occurred. 12 SOURCE It represents the occurrence of an error in the source of the flow. 13 SOURCE_RESPONSE It represents the occurrence of an error in the source of the flow while processing a successful response. In the above example, you can see the message component of mule error. Error Types Let us understand the Error Types with the help of its characteristics − The first characteristics of Mule Error Types is that it consists of both, a namespace and an identifier. This allows us to distinguish the types according to their domain. In the above example, the Error Type is HTTP: UNAUTHORIZED. The second and important characteristic is that the Error Type may have a parent type. For example, the Error Type HTTP: UNAUTHORIZED has MULE:CLIENT_SECURITY as the parent which in turn also has a parent named MULE:SECURITY. This characteristic establishes the Error Type as specification of more global item. Kinds of Error Types Following are the categories under which all the errors fall − ANY The errors under this category are the errors that may occur in a Flow. They are not so severe and can be handled easily. CRITICAL The errors under this category are the severe errors that cannot be handled. Following is the list of Error Types under this category − Sr.NO Error Type and Description 1 OVERLOAD This Error Type indicates an error occurred due to problem of overloading. In this case, the execution will be rejected. 2 FATAL_JVM_ERROR This kind of Error Type indicates the occurrence of a fatal error. For example, stack overflow. CUSTOM Error Type The CUSTOM Error Types are the errors that are defined by us. They can be defined when mapping or when raising the errors. We must give a specific custom namespace to these Error Types for distinguishing them from the other existing Error Types within Mule application. For example, in Mule application using HTTP, we cannot use HTTP as the custom error type. Categories of Mule Error In broad sense, the errors in Mule can be divided into two categories namely, Messaging Errors and System Errors. Messaging Error This category of Mule error is related to the Mule flow. Whenever a problem occurs within a Mule flow, Mule throws a messaging error. We can set up On Error component inside the error handler component to handle these Mule errors. System Error System error indicates an exception occurring at the system level. If there is no Mule event, the system error is handled by a system error handler. The following kind of exceptions handle by a system error handler − Exception that occurs during an application start-up. Exception that occurs when a connection to an external system fails. In case a system error occurs, Mule sends an error notification to the registered listeners. It also logs the error. On the other hand, Mule executes a reconnection strategy if the error was caused by a connection failure. Handling Mule Errors Mule has following two Error Handlers for handling the errors − On-Error Error Handlers The first Mule error handler is On-Error component, that defines the types of errors they can handle. As discussed earlier, we can configure On-Error components inside the scope-like Error Handler component. Each Mule flow contain only one error handler, but this error handler can contain as many On-Error scope as we needed. The steps for handling the Mule error inside the flow, with

MuleSoft – Mule exception Handling

MuleSoft – Mule Exception handling ”; Previous Next In case of every project, the fact about the exceptions is that they are bound to happen. That is why it is important to catch, categorize and handle exceptions so that the system/application is not left in an inconsistent state. There is a default exception strategy which is implicitly applied to all Mule applications. Rollback any pending transaction automatically is the default exception strategy. Exceptions in Mule Before diving deep into exceptional handling, we should understand what kind of exceptions can occur along with three basic questions that a developer must have while designing exception handlers. Which Transport is important? This question has ample relevance before designing exception handlers because all transports do not support transnationality. File or HTTP does not support transactions. That is why, if an exception occurs in these cases, we must manage it manually. Databases support transactions. While designing exception handlers in this case, we must keep in mind that database transactions can automatically rollback (if required). In case of REST APIs, we should keep in mind that they should return the correct HTTP status codes. For example, 404 for a resource not found. Which Message Exchange Pattern to be used? While designing exception handlers, we must take care about Message exchange pattern. There can be synchronous (request-reply) or asynchronous (fire-forget) message pattern. Synchronous message pattern is based on request-reply format which means this pattern will expect a response and will be blocked until a response is returned or time out happens. Asynchronous message pattern is based on fire-forget format which means this pattern assumes that the requests will ultimately be processed. Which type of exception is it? Very simple rule is that you will handle the exception based on its type. It is very important to know whether the exception is caused by a system/technical issue or a business issue? An exception occurred by system/technical issue (such as network outage) should be automatically handled by a retry mechanism. On the other hand, an exception occurred by a business issue (such as invalid data) should not be solved by applying retry mechanism because it is not useful to retry without fixing the underlying cause. Why to Categorize Exceptions? As we know that all the exceptions are not same, it is very important to categorize the exceptions. At high level, the exceptions can be classified into the following two types − Business Exceptions The main reasons for the occurrence of business exceptions are incorrect data or incorrect process flow. These kind of exceptions are typically non-retriable in nature and hence it is not good to configure a rollback. Even applying retry mechanism would not make any sense because it is not useful to retry without fixing the underlying cause. In order to handle such exceptions, the processing should stop immediately, and the exception sent back as a response to a dead letter queue. A notification should also send to the operations. Non-business Exceptions The main reasons for the occurrence of non-business exceptions are system issue or technical issue. These kinds of exceptions are retriable in nature and hence it’s good to configure a retry mechanism in order to solve these exceptions. Exception Handling Strategies Mule has the following five exception handling strategies − Default Exception Strategy Mule implicitly applies this strategy to the Mule flows. It can handle all the exceptions in our flow, but it can also be overridden by adding a catch, Choice or Rollback exception strategy. This exception strategy will roll back any pending transactions and logs the exceptions too. An important characteristic of this exception strategy is that it will also log the exception if there is no transaction. As being the default strategy, Mule implements this when any error occurs in the flow. We cannot configure in AnyPoint studio. Rollback Exception Strategy Suppose if there is no possible solution to correct the error then what to do? A solution is to use Rollback Exception Strategy which will roll back the transaction along with sending a message to the inbound connector of parent flow to reprocess the message. This strategy is also very useful when we want to reprocess a message. Example This strategy can be applied to banking transaction where funds are getting deposited in a checking/savings account. We can configure a rollback exception strategy here because in case if an error occurs during the transaction, this strategy rolls the message back to the beginning to the flow to reattempt processing. Catch Exception Strategy This strategy catches all the exceptions that are thrown within its parent flow. It overrides Mule’s default exception strategy by processing all the exceptions thrown by the parent flow. We can use a catch exception strategy to avoid propagating exceptions to inbound connectors and parent flows as well. This strategy also ensures that a transaction processed by the flow is not rolled back when an exception occurs. Example This strategy can be applied to flight booking system in which we have a flow for processing messages from a queue. A message enricher adds a property on the message for assignment of seat and then sends the message to another queue. Now if any error occurs in this flow, then the message will throw an exception. Here, our catch exception strategy can add a header with an appropriate message and can push that message out of the flow to the next queue. Choice Exception Strategy In case you want to handle the exception based on the message content, then choice exception strategy would be the best choice. The working of this exception strategy will be as follows − First, it catches all the exceptions thrown within the parent flow. Next, it checks for the message content and exception type. And at last, it routes the message to the appropriate exception strategy. There would be more than one exception strategy like Catch or Rollback, defined within choice exception strategy. In case there is no strategy defined under this

MuleSoft – Useful Resources

MuleSoft – Useful Resources ”; Previous Next The following resources contain additional information on MuleSoft. Please use them to get more in-depth knowledge on this. Useful Links on MuleSoft MuleSoft − Official site of MuleSoft MuleSoft @ Wikipedia − MuleSoft, its history and various other terms has been explained in simple language. To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;